<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matthew Ghannoum on Medium]]></title>
        <description><![CDATA[Stories by Matthew Ghannoum on Medium]]></description>
        <link>https://medium.com/@matthewghannoum?source=rss-8de6ff69bd4f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oSPD5YLDBO5SOP27BmqmtA.jpeg</url>
            <title>Stories by Matthew Ghannoum on Medium</title>
            <link>https://medium.com/@matthewghannoum?source=rss-8de6ff69bd4f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:09:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matthewghannoum/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Hypothesis Testing to Determine if Temperature Impacts Workout Performance]]></title>
            <link>https://medium.com/@matthewghannoum/using-hypothesis-testing-to-determine-if-temperature-impacts-workout-performance-17aa9caaf396?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/17aa9caaf396</guid>
            <category><![CDATA[statsmodels]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gym-workout]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Sat, 04 May 2024 03:51:10 GMT</pubDate>
            <atom:updated>2024-05-04T06:21:06.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XxIE8DRsQFxB44gV" /><figcaption>Photo by <a href="https://unsplash.com/@samuelgirven?utm_source=medium&amp;utm_medium=referral">Samuel Girven</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Motivation and Dataset</h3><p>One of my hobbies outside of work is weight lifting. I would say I take it somewhat seriously, and enjoy a mixture of both strength (high weight) and hypertrophy (high repetition) training.</p><p>During this past summer I realised (particular on leg days), that if it was quite hot I would feel weaker and lift less weight and repetitions.</p><p>As such, I wanted to check if there was actually a significant difference between “gym performance” between hot and regular days, so that if there is I can prepare better (increase hydration, go earlier/later in the day, etc).</p><p>To do this, I used a spreadsheet where I tracked my repetitions, weight and <a href="https://my.clevelandclinic.org/health/articles/17450-rated-perceived-exertion-rpe-scale">RPE</a> for every set of every workout I’ve done. I combined this dataset, with my Apple Health data which records the temperature and humidity of each workout recorded in the “Fitness” app.</p><p>I’ve created a dataset from cleaning and processing the aforementioned data which you can find on <a href="https://github.com/LGXprod/environmental-workout-performance">Github here</a> along with the completed Jupyter Notebook for the following experiments.</p><p>The “exertion score” is simply the sum of product of repetitions, weight and RPE for each set for a given workout:</p><figure><img alt="Exertion score equation." src="https://cdn-images-1.medium.com/max/288/1*dKcQek0stwP0PMDytYgpRg.png" /></figure><p>Where n is the number of sets, i is the index of the current set, R is number of repetitions, W is the weight used and E is RPE.</p><h3>Defining the Hypothesis for the Problem</h3><p>Defining your hypothesis so it can be tested and proven “correct”, can be slightly confusing but there are steps you can follow it define it properly.</p><p>My original hypothesis is that on average, exertion score (workout performance metric) is higher on regular days than it is on hot or humid days (temperature and humidity will be tested separately).</p><p>However, we cannot directly prove a hypothesis to be true, rather we can prove a negation (opposite) of the hypothesis to be false. Thereby, implying the original hypothesis is true.</p><p>Hence a new hypothesis is needed, which if rejected implies the original hypothesis is correct. This “new hypothesis” is formally referred to as <strong>the Null Hypothesis</strong>. In our case:</p><p>(1). Null Hypothesis (H0): mean exertion score on hot days is greater than the mean exertion score on regular days:</p><figure><img alt="Null hypothesis: regular exertion score less than or equal to hot exertion score." src="https://cdn-images-1.medium.com/max/331/1*ad7qd7JVaqr-lkz2yxnQ6Q.png" /></figure><p>(2). Alternative Hypothesis (HA):</p><figure><img alt="Null hypothesis: regular exertion score greater than to hot exertion score." src="https://cdn-images-1.medium.com/max/331/1*JMWRD4kuWDs_JhA11AfllA.png" /></figure><p>The hypothesis test for humidity is similar:</p><p>(1). Null Hypothesis (H0): mean exertion score on humid days is greater than the mean exertion score on regular days:</p><figure><img alt="Null hypothesis: regular exertion score less than or equal to humid exertion score." src="https://cdn-images-1.medium.com/max/352/1*gDBXA3T3gwjiLcnjCBfS9Q.png" /></figure><p>(2). Alternative Hypothesis (HA):</p><figure><img alt="Null hypothesis: regular exertion score greater than to humid exertion score." src="https://cdn-images-1.medium.com/max/351/1*aJwZb0rCba--A9fnZy7r6g.png" /></figure><h3>How to Reject the Null Hypothesis</h3><p>Given the objective is to reject the both of the aforementioned Null Hypotheses, the most common approach to doing so is to use an <em>significance test.</em> This statistical test will produce a test statistic and a p-value, from which we can use either to reject or accept the Null Hypothesis (p-value is derived from the test statistic).</p><p>Typically, the p-value (also referred to as the significance level) needs to be <strong>less than 0.05</strong> to provide statistically significant evidence against the null hypothesis.</p><p>The diagram below visualises the confidence interval, rejection zones and the p-value.</p><figure><img alt="Z-score distribution visualisation with p-values." src="https://cdn-images-1.medium.com/max/1024/1*5KhJNXD6Lb_M3VEotflEKw.png" /><figcaption>Z-score distribution visualisation with p-values.</figcaption></figure><p>For more information on statistical significance and to view the left diagram, <a href="https://www.simplypsychology.org/p-value.html#:~:text=A%20p%2Dvalue%20less%20than%20or%20equal%20to%20a%20predetermined,rather%20than%20just%20random%20chance">click here</a>. To value the diagram on the left <a href="https://pro.arcgis.com/en/pro-app/latest/tool-reference/spatial-statistics/what-is-a-z-score-what-is-a-p-value.htm">click here</a>.</p><h3>Selecting the appropriate Test Type</h3><p>There are many different types of significance tests that can be used to calculate a p-value, most of which make certain assumptions and have certain requirements.</p><p><a href="https://alod83.medium.com/?source=post_page-----8a070636bd28--------------------------------">Angelica Lo Duca</a>, wrote a great article on the decision process to decide between the available significance/hypothesis tests, which she summarised with the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wzPOcsgriY5Ur0-Ffjq38Q.png" /><figcaption><a href="https://towardsdatascience.com/hypothesis-tests-explained-8a070636bd28">To view the original diagram or for a more in depth explanation you can find Angelica’s article here.</a></figcaption></figure><h3>Are the Datasets Normally Distributed?</h3><p>Using this decision framework, the first characteristic of the data that needs to be determined is “if it is normal distributed” (essentially a symmetric bell curve). From observing the data in a histogram form, it appears both datasets roughly follow a normal distribution.</p><figure><img alt="Exertion score histogram for regular and hot temperatures." src="https://cdn-images-1.medium.com/max/758/1*rrvf3NRCC9JRSRwnh-FeUg.png" /><figcaption>Exertion score histogram for regular and hot temperatures.</figcaption></figure><figure><img alt="Exertion score histogram for regular and humid conditions." src="https://cdn-images-1.medium.com/max/758/1*tjJKTNWrxOYwrYoXooqMoQ.png" /><figcaption>Exertion score histogram for regular and humid conditions.</figcaption></figure><p>However, to be another significance test called the “Shapiro Wilk Test” can be used to reject the null hypothesis of our data <strong>not</strong> being normally distributed. Using the shapiro() method scipy.stats provides produced the following results:</p><pre>print(round(stats.shapiro(regular_temp_exertion_scores).pvalue, 4)) # 0.1306<br>print(round(stats.shapiro(hot_exertion_scores).pvalue, 4)) # 0.4763<br>print(round(stats.shapiro(regular_humidity_exertion_scores).pvalue, 4)) # 0.1492<br>print(round(stats.shapiro(humid_exertion_scores).pvalue, 4)) # 0.2161</pre><p>Meaning for all our datasets, we can reject the null hypothesis that the data is not normally distributed. Therefore, we can <strong>assume</strong> the distribution is normal (despite the fact it could still be another distribution).</p><h3>How many Sample Sets are there? Are they paired? Are they large?</h3><p>Given our data is normally distributed and we have two sample sets for each experiment (sample 1.1: hot exertion scores, sample 1.2: regular exertion scores, sample 2.1: humid exertion scores, sample 2.2: regular humidity exertion scores), there are three options. That being a Two Group T-Test, a Paired T-Test or a Z-Test.</p><p>Neither dataset will use a Paired Test as the data is not paired, as workouts are done on distinct days with distinct temperatures/humidities.</p><p>For our temperature exertion score samples (1.1 and 1.2), the number of samples is 19 for the hot set and 70 for the regular temperature set. Since the size of the hot set is less than 30, which is what is considered the minimum size for a “large” sample, a Z-Test cannot be used.</p><p>However, for the humidity exertion score scores, the sizes are 31 (regular) and 58 (humid) respectively, hence the Z-Test will be selected.</p><h3>Running the Hypothesis Tests</h3><p>Now that the Null Hypothesis for the temperature and humidity experiments have been defined and the significance tests have been selected, the experiment can be run.</p><p>To do so I will be using the statsmodels Python package which provides methods for both T-Tests and Z-Tests.</p><p>Since statsmodels is an external package, it needs to be installed in your Python environment. If you are unsure about Python environments and how to set them up you can read my article on my <a href="https://matthewgh.com/blog/python-environments-an-overview">portfolio blog here</a>.</p><p>The first step is to activate your Python environment. Since I am using <strong>Miniconda</strong> to do this I enter conda activate *env-name* or if you are using a virtual environment you can enter source project_env_name/bin/activate.</p><p>Now that the environment is selected enter pip install statsmodels to install the package.</p><p>Using the following code snippets, the T-Test for the temperature experiment and the Z-Test for the humidity experiment can be run.</p><pre>import statsmodels</pre><pre>t_statistic, p_value, _ = statsmodels.stats.weightstats.ttest_ind(<br>    regular_temp_exertion_scores,<br>    hot_exertion_scores,<br>    alternative=&quot;larger&quot;,<br>    usevar=&quot;unequal&quot;,<br>)<br>print(f&quot;Temperature Test Statistic: {round(t_statistic, 4)}&quot;)<br>print(f&quot;Temperature P-Value: {round(p_value, 4)}\\n&quot;)<br><br># Output:<br># Temperature Test Statistic: -3.0466<br># Temperature P-Value: 0.998</pre><p>The P-Value = 0.9980 &gt; 0.05, therefore we cannot reject the Null Hypothesis. Meaning that we do not significant evidence that the mean exertion score of workouts on regular days is <strong>greater than</strong> the mean of exertion score of workouts on hot days.</p><pre>t_statistic, p_value = statsmodels.stats.weightstats.ztest(<br>    humid_exertion_scores,<br>    regular_humidity_exertion_scores,<br>    alternative=&quot;larger&quot;,<br>    usevar=&quot;unequal&quot;,<br>)<br>print(f&quot;Temperature Test Statistic: {round(t_statistic, 4)}&quot;)<br>print(f&quot;Temperature P-Value: {round(p_value, 4)}\\n&quot;)<br><br># Output:<br># Temperature Test Statistic: -1.297<br># Temperature P-Value: 0.9027</pre><p>The P-Value = 0.9027 &gt; 0.05, therefore we cannot reject the Null Hypothesis. Meaning that we do not significant evidence that the mean exertion score of workouts on regular days is <strong>greater than</strong> the mean of exertion score of workouts on humid days.</p><h3>Possible Flaws in this Testing Methodology</h3><p>Now that the conclusions of the above experiments have been reached, it is important to consider that this experiment and hypothesis testing in general can have flaws. For these experiments specifically this includes:</p><ul><li>Are the sample distributions normal? Specifically, the temperature exertion score distributions as they appear to be possibly bimodal?</li><li>How are other factors impacting exertion score performance (workout type, duration etc)?</li><li>For example, in Australia (where I live) autumn has only recently started. That means since I have been performing my best this year, the summer exertion scores for this year maybe skewing the distribution.</li><li>Is the exertion score an accurate representation of workout performance?</li><li>Has an appropriate temperature and humidity threshold been used to split the sample into two groups?</li></ul><p>The last possible flaw is actually a well-known issue in significance tests called “P-Hacking”. Whereby, a scientist can misrepresent or skew results by intentionally manipulating data until they achieve a p-value that demonstrates statistical significance.</p><p>However, this wasn’t in case in this experiment as the desired hypothesis was not accepted.</p><h3>Resources</h3><p>Project GitHub Repository: <a href="https://github.com/LGXprod/environmental-workout-performance">https://github.com/LGXprod/environmental-workout-performance</a></p><p>If you found this article insightful or helpful, please consider leaving a clap and following me for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17aa9caaf396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SwiftUI Basics from a React Developer Perspective]]></title>
            <link>https://medium.com/@matthewghannoum/understanding-swiftui-basics-from-a-react-developer-perspective-9859ab758efe?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9859ab758efe</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 05:00:34 GMT</pubDate>
            <atom:updated>2024-04-10T05:00:34.596Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding SwiftUI from a React Developer Perspective</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nd9jPmv3fr9gKqom" /><figcaption>Photo by <a href="https://unsplash.com/@nhuenerfuerst?utm_source=medium&amp;utm_medium=referral">Nils Huenerfuerst</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>SwiftUI is Apple’s modern framework from developing user interfaces across there different platforms including; iOS, iPadOS, MacOS and more. This article will primarily focus on iOS development, but many of the concepts will be present across the different platforms.</p><p>Moreover, there are many similar concepts shared between SwiftUI and the popular Javascript UI framework React. Comparisons between React and SwiftUI will be made to better convey concepts to developers who already familiar with React. However, React itself is also similar to other Javascript UI frameworks such as Vue, Svelte, etc.</p><h3>Views vs. Components</h3><p>The equivalent of a React component is a called a View in SwiftUI. Much like how a component is comprised on one or more HTML elements and/or other React components. Swift views are made of one or more other Swift views. Unlike in React, there is no term to define the base, provided components (i.e. HTML elements), as the provided SwiftUI “components” are themselves referred to as views.</p><p><a href="https://mia-e.medium.com/a-comprehensive-list-of-swiftui-views-the-building-blocks-of-swift-ui-45de711c0265">Mia created a comprehensive list of the provided, SwiftUI building blocks</a>. The following is a list of HTML equivalents:</p><figure><img alt="Table of equivalent elements/views in SwiftUI and HTML." src="https://cdn-images-1.medium.com/max/766/1*7PuVDhyZtFoUaL7KYXTRwg.png" /><figcaption>Equivalent elements/views in SwiftUI and HTML.</figcaption></figure><p>In React a component instantiated within a component is referred to as a “child component”, and the component that it is contained within is the “parent component”. This terminology is used in swift as well except instead of components there are views.</p><p>Javascript UI developers will have noticed that arguably the most import element, the &lt;div&gt; was not included in the table above. This is because the way in which Javascript/HTML frameworks and SwiftUI handle UI layouts is very different, and is covered in the section: “Creating your Application Layout and Style”.</p><h3>Differences in Instantiating Views and Components</h3><p>In modern React code, a component is created by creating a <strong>Function</strong> which returns a value of type JSX.Element or React.ReactNode. Whether the React code is written in Javascript or Typescript, only the function and it’s return value(s) need to be defined, as Javascript is loosely typed and Typescript can infer the type.</p><p>To instantiate a view in SwiftUI requires a bit more work, as you need to:</p><ol><li>Import SwiftUI</li><li>Explicitly denote that your custom view uses the View protocol. <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols/">A protocol being a set of properties, methods and other requirements</a> a Struct requires to implement certain functionality.</li><li>As part of the View protocol, the body property needs to be defined and must be of type some View. The body must contain one or more views within it.</li></ol><h3>Creating your Application Layout and Style</h3><p>The way layouts are formed and styled in SwiftUI is very different to JS frameworks. The key distinction which leads to many downstream differences, is that SwiftUI uses <strong>Views</strong> to style components and layouts, while JS frameworks use CSS which is a it’s own styling language (or abstractions of CSS).</p><h3>Example: Aligning Three Coloured Boxes</h3><p>This example will highlight the difference in how you “contain” or “divide” your content and the order in which it can be represented in both HTML/CSS and SwiftUI:</p><pre>import SwiftUI<br><br>struct SquareView: View {<br>    var color: Color<br>    var width: CGFloat = 75<br>    var height: CGFloat = 75<br>    <br>    var body: some View {<br>        HStack {}.frame(width: width, height: height).background(color)<br>    }<br>}<br><br>struct ContentView: View {<br>    var body: some View {<br>        HStack {<br>            SquareView(color: .red)<br>            SquareView(color: .green)<br>            SquareView(color: .blue)<br>        }.padding(.vertical)<br>        <br>        VStack {<br>            SquareView(color: .red)<br>            SquareView(color: .green)<br>            SquareView(color: .blue)<br>        }.padding(.vertical)<br>        <br>        ZStack {<br>            SquareView(color: .red, width: 175, height: 175)<br>            SquareView(color: .green, width: 125, height: 125)<br>            SquareView(color: .blue)<br>        }.padding(.vertical)<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><pre>type SquareProps = {<br>  color: &quot;red&quot; | &quot;blue&quot; | &quot;green&quot;;<br>  width?: string;<br>  height?: string;<br>  zIndex?: number;<br>};<br><br>type SquareStyle = {<br>  backgroundColor: string;<br>  width: string;<br>  height: string;<br>  position?: &quot;absolute&quot;;<br>  zIndex?: number;<br>};<br><br>function Square({ color, width, height, zIndex }: SquareProps) {<br>  if (!width) {<br>    width = &quot;75px&quot;;<br>  }<br>  if (!height) {<br>    height = &quot;75px&quot;;<br>  }<br>  let style: SquareStyle = {<br>    backgroundColor: color,<br>    width: height,<br>    height: height,<br>  };<br>  if (zIndex) {<br>    style = { ...style, position: &quot;absolute&quot;, zIndex };<br>  }<br>  return &lt;div style={style} /&gt;;<br>}<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;div style={{ display: &quot;flex&quot;, gap: &quot;20px&quot;, padding: &quot;20px 0&quot; }}&gt;<br>        &lt;Square color=&quot;red&quot; /&gt;<br>        &lt;Square color=&quot;green&quot; /&gt;<br>        &lt;Square color=&quot;blue&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;div<br>        style={{<br>          display: &quot;flex&quot;,<br>          flexDirection: &quot;column&quot;,<br>          gap: &quot;20px&quot;,<br>          padding: &quot;20px 0&quot;,<br>        }}<br>      &gt;<br>        &lt;Square color=&quot;red&quot; /&gt;<br>        &lt;Square color=&quot;green&quot; /&gt;<br>        &lt;Square color=&quot;blue&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;div style={{ position: &quot;relative&quot; }}&gt;<br>        &lt;Square color=&quot;blue&quot; zIndex={2} /&gt;<br>        &lt;Square color=&quot;green&quot; width=&quot;150px&quot; height=&quot;150px&quot; zIndex={1} /&gt;<br>        &lt;Square color=&quot;red&quot; width=&quot;175px&quot; height=&quot;175px&quot; /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>The result of the above code snippets are:</p><figure><img alt="Code snippet outputs from React and SwiftUI." src="https://cdn-images-1.medium.com/max/960/1*K5kQNgewdTMymE9lPsazkA.jpeg" /><figcaption>Code snippet outputs from React and SwiftUI.</figcaption></figure><p>In Swift you can place your child views within a HStack to display them horizontally, VStack to display them vertically or ZStack to display them in front or behind each other. While in React, there is no component that specifically does this. Instead you combine a div which “divides” your content and use CSS styles to make your child elements/components ordered in a particular way. There are many styles you can use to replicate the same functionality, some of which can be applied to the parent component and some on the children component. For this example I opted to use the flex and flex-direction styles to display the squares either in a row or column. However, this cannot be used to replicate the functionality of the ZStack, rather the equivalent in HTML+CSS is add the position: relative style to the parent, position: absolute to the child/children you wish to elevate and the zIndex integer value which determines how far in front or behind an element is placed (e.g. an element with zIndex: 2 will be displayed in front of an element of zIndex: 1).</p><p>Finally, the last basic View you can use to contain child views is Group. Unlike the different versions of stack, Group has not default layout/styling. An example of when it would be useful to use Group is when you want to apply the same style modifier to multiple Views, <a href="https://medium.com/devtechie/group-in-swiftui-b9757fa4861c#:~:text=Group%20in%20SwiftUI%20is%20a%20type%20that%20collects%20multiple%20instances,much%20like%20VStack%20and%20HStack%20.">as DevTechie shows this example in his blog</a>:</p><pre>struct DevTechieGroupExample: View {<br>    var body: some View {<br>        VStack {<br>            Text(&quot;DevTechie Courses&quot;)<br>                .font(.largeTitle)<br>            Group {<br>                Text(&quot;SwiftUI&quot;)<br>                Text(&quot;Combine&quot;)<br>                Text(&quot;iOS Development&quot;)<br>            }.font(.body)<br>        }<br>    }<br>}</pre><p>This could be done in HTML/CSS by applying the font-size style to a div that contains text elements.</p><h3>Differences in Styling</h3><p>As shown in the previous examples, SwiftUI either uses views with “pre-applied” styling (e.g. VStack) or methods (e.g. .font() or .padding()) to style your application. While in the case of any web development framework the styles are applied to an element using CSS.</p><blockquote>⚠️ Warning: the order in which you apply style methods in SwiftUI is very important. For example, in the three coloured boxes example, if you apply the background() method before the frame() method the background colour will only be applied to the size of the view <strong>before the frame updates the size</strong>.</blockquote><p>While in most cases with CSS, the order of styles applied to a given element doesn’t change the final style of the element. Unless there are duplicate styles or in a small number of cases where certain styles effect different styles.</p><h3>Handling Application State and Logic</h3><h3>Passing Properties to Child Views</h3><p>As shown in the previous example of the square, custom properties can be added to a view so we use it in different ways.</p><p>React:</p><pre>function Square({ color, width, height, zIndex }: SquareProps) {<br>  if (!width) {<br>    width = &quot;75px&quot;;<br>  }<br><br>  if (!height) {<br>      height = &quot;75px&quot;;<br>  }<br><br>  let style: SquareStyle = {<br>    backgroundColor: color,<br>    width: height,<br>    height: height,<br>  };<br><br>  if (zIndex) {<br>    style = { ...style, position: &quot;absolute&quot;, zIndex };<br>  }<br><br>  return &lt;div style={style} /&gt;;<br>}</pre><p>SwiftUI:</p><pre>import SwiftUI<br><br>struct SquareView: View {<br>    var color: Color<br>    var width: CGFloat = 75<br>    var height: CGFloat = 75<br>    <br>    var body: some View {<br>        HStack {}.frame(width: width, height: height).background(color)<br>    }<br>}</pre><p>In React the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructured arguments</a> are defined as properties of the prop argument. While in SwiftUI they are simply properties of the custom view Struct.</p><p>However, in this example, the values of the aforementioned properties are static (i.e. defined a compile time).</p><h3>Adding State to Views and Child Views</h3><p>Both React and SwiftUI provide ways to add “state” to your component, so that a value can change when some event occurs (e.g. button press, text input, API call etc). This state can also be passed down from the parent to the child view/component.</p><p><a href="https://benmcmahen.com/swiftui-for-react-developers/">Ben McMahen shows how to do this in SwiftUI with an example of a button counter:</a></p><pre>struct IncrementButton : View {<br>    @Binding var counter: Int<br><br>    func increment () {<br>            counter += 1<br>        }<br>        var body: some View {<br>          Button(action: increment) {<br>              Text(&quot;Increment&quot;)<br>          }<br>        }<br>    }<br><br>    struct ContentView : View {<br>        @State var count = 0<br>        var body: some View {<br>            VStack(spacing: 1.0) {<br>                Text(&quot;Press the button below&quot;)<br>                IncrementButton(counter: $count)<br>        }<br>    }<br>}</pre><p>The equivalent to this in React would be:</p><pre>import { useState } from &quot;react&quot;;<br><br>function CounterButton({ increment }: { increment: () =&gt; void; }) {<br>  return (<br>    &lt;button onClick={increment}&gt;<br>      Increment<br>    &lt;/button&gt;<br>  )<br>}<br>export default function StateExample() {<br>  const [count, setCount] = useState(0);<br>  const increment = () =&gt; {<br>    setCount(count + 1);<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;CounterButton increment={increment} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Both frameworks enable you to split the view or component into seperate files for better code usability and readability.</p><h3>Best Practice for Complex State Management</h3><p>The aforementioned approach is not recommended for more complex scenarios. “Prop drilling” is a term used to describe when you are continually passing a property (usually a state or state function) through several layers of child props. This is bad as it <a href="https://blog.stackademic.com/react-anti-patterns-props-drilling-7d2670fa132c#:~:text=Prop%20drilling%20in%20React%2C%20while,in%20cleaner%2C%20more%20maintainable%20code">“can lead to increased complexity and difficulty in tracking data flow”</a> and can occur in both frameworks.</p><p>To resolve this issue, abstracting state and methods that act on stateful variables into seperate modules (functions, classes, files etc) is commonly done.</p><p>In React this is typically done by using the inbuilt React Context package or a custom state management solution such as Redux or Zustand. These solutions typically work by having a provider component that encapsulates components that need access to a state store. Moreover, they provide ways to attach custom methods which can update the state of the store.</p><p>In SwiftUI a common abstraction to achieve the same functionality utilises the Model-View-View-Model (MVVM) Architecture.</p><p>I may write an article comparing MVVM and Zustand or Context in the future. If you would like to see that article when I publish it, you can follow me on Medium! 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9859ab758efe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Two or More Key Dictionary in Python]]></title>
            <link>https://medium.com/@matthewghannoum/how-to-build-a-two-or-more-key-dictionary-in-python-9cffe0914b94?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cffe0914b94</guid>
            <category><![CDATA[dictionaries-in-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 01:39:15 GMT</pubDate>
            <atom:updated>2024-02-05T01:40:00.073Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build a Multi-Key Dictionary in Python</h3><p>Dictionaries are an incredible data structure, that can assist in making your code more approachable, consistent and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mMeP8gZtuwDt8of0" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Unfortunately, out of the box Python only provides a 1-dimensional dictionary. That being a dictionary with a single key. Technically, this can be extended to any number of keys using tuples as your key data type, but there is one potential flaw. That being, that the order of your tuple matters, meaning <strong>two keys existing in a dictionary may not be access the correct value if they are not in the correct order.</strong></p><p>In your problem solving endeavours, you may encounter problems where you would like to access a particular value, using the speed of a dictionary, but with two or more keys. Where the order of those keys is not guaranteed to be consistent.</p><p>To do this I’ve provided code snippets for two custom dictionary classes:</p><ol><li>A two dimensional dictionary → TwoKeyDict</li><li>A n (where n is any number of keys ≥ 1) dimensional dictionary → NKeyDict</li></ol><blockquote>🗒️ As mentioned previously, a key is defined as two more values in a tuple or list. <strong>The order of those values in the list does not matter.</strong> For example, (&quot;a&quot;, &quot;b&quot;) is equivalent to (&quot;b&quot;, &quot;a&quot;).</blockquote><h3>Two Key Dictionary</h3><p>The TwoKeyDict class has the following methods:</p><ol><li>get_value_by_key → returns the value stored for a given two key combination, but if there is no value for that combination it returns None.</li><li>set_key_value_pair → stores a new value or updates an existing one, for a given two key combination.</li><li>remove_key_value_pair → deletes the key-value pair using the given two key combination, if it exists in the dictionary.</li></ol><pre>class TwoKeyDict:<br>    def __init__(self):<br>        self.dictionary = {}<br><br>    def get_value_by_key(self, key1, key2):<br>        if (key1, key2) in self.dictionary:<br>            return self.dictionary[(key1, key2)]<br>        if (key2, key1) in self.dictionary:<br>            return self.dictionary[(key2, key1)]<br>        return None<br>    def set_key_value_pair(self, key1, key2, value):<br>        if (key2, key1) in self.dictionary:<br>            self.dictionary[(key2, key1)] = value<br>        else:<br>            self.dictionary[(key1, key2)] = value<br>            <br>    def remove_key_value_pair(self, key1, key2):<br>        if (key1, key2) in self.dictionary:<br>            del self.dictionary[(key1, key2)]<br>        elif (key2, key1) in self.dictionary:<br>            del self.dictionary[(key2, key1)]<br>        else:<br>            return None</pre><h3>Example Usage</h3><pre>example_dict = TwoKeyDict()<br><br>example_dict.set_key_value_pair(&quot;a&quot;, &quot;b&quot;, 1)<br>print(example_dict.get_value_by_key(&quot;a&quot;, &quot;b&quot;))  # Output: 1<br><br>example_dict.set_key_value_pair(&quot;b&quot;, &quot;a&quot;, 2)<br>print(example_dict.get_value_by_key(&quot;a&quot;, &quot;b&quot;))  # Output: 2<br><br>example_dict.set_key_value_pair(&quot;c&quot;, &quot;d&quot;, 3)<br>print(<br>    example_dict.get_value_by_key(&quot;c&quot;, &quot;d&quot;), example_dict.get_value_by_key(&quot;d&quot;, &quot;c&quot;)<br>)  # Output: 3 3<br><br>print(<br>    example_dict.get_value_by_key(&quot;a&quot;, &quot;c&quot;), example_dict.get_value_by_key(&quot;q&quot;, &quot;x&quot;)<br>)  # Output: None None<br><br>example_dict.remove_key_value_pair(&quot;a&quot;, &quot;b&quot;)<br>print(example_dict.get_value_by_key(&quot;a&quot;, &quot;b&quot;))  # Output: None</pre><h3>N Dimensional Dictionary</h3><p>The NKeyDict class has the following methods:</p><ol><li>__init__ → the constructor used to set the number of keys/dimensions (num_keys) you would like the dictionary to use for key-value storage.</li><li>get_value_by_key → returns the value stored for a given n-key combination, but if there is no value for that combination it returns None.</li><li>set_key_value_pair → stores a new value or updates an existing one, for a given n-key combination.</li><li>remove_key_value_pair → deletes the key-value pair using the given n-key combination, if it exists in the dictionary.</li></ol><blockquote>⚠️ For all of the above methods, if a key list is given which is not the length of num_keys then a error will thrown.</blockquote><pre>class NKeyDict:<br>    def __init__(self, num_keys: int):<br>        self.dictionary = {}<br>        self.num_keys = num_keys<br><br>    def get_value_by_key(self, keys: list[any]):<br>        if len(keys) != self.num_keys:<br>            raise Exception(<br>                &quot;Number of keys does not match the number of keys in the dictionary&quot;<br>            )<br>        keys.sort()<br>        return self.dictionary.get(tuple(keys), None)<br>    def set_key_value_pair(self, keys: list[any], value):<br>        if len(keys) != self.num_keys:<br>            raise Exception(<br>                &quot;Number of keys does not match the number of keys in the dictionary&quot;<br>            )<br>        keys.sort()<br>        self.dictionary[tuple(keys)] = value<br>    def remove_key_value_pair(self, keys: list[any]):<br>        if len(keys) != self.num_keys:<br>            raise Exception(<br>                &quot;Number of keys does not match the number of keys in the dictionary&quot;<br>            )<br>        keys.sort()<br>        if tuple(keys) in self.dictionary:<br>            del self.dictionary[tuple(keys)]<br>        else:<br>            return None</pre><p>A important difference in the implementation of TwoKeyDict and NKeyDict is that TwoKeyDict takes each key as seperate arguments and checks for each permutation (ordered combination) of tuples in the dictionary. While NKeyDict takes a list of keys and sorts them so that permutations of the collection of keys don’t need to be checked.</p><h3>Example Usage</h3><pre>example_3d_dict = NKeyDict(3)<br><br>example_3d_dict.set_key_value_pair([1, 2, 3], &quot;Hello World!&quot;)<br>print(<br>    example_3d_dict.get_value_by_key([1, 2, 3]),<br>    example_3d_dict.get_value_by_key([3, 2, 1]),<br>) # Output: Hello World! Hello World!<br><br>example_3d_dict.set_key_value_pair([2, 3, 1], &quot;Goodbye!&quot;)<br>print(example_3d_dict.get_value_by_key([1, 2, 3])) # Output: Goodbye!<br><br>example_3d_dict.remove_key_value_pair([1, 2, 3])<br>print(example_3d_dict.get_value_by_key([1, 2, 3])) # Output: None</pre><pre>example_3d_dict.set_key_value_pair([5, 6, 7, 8], &quot;This will cause an error!&quot;)<br># Exception: Number of keys does not match the number of keys in the dictionary</pre><h3>Conclusion</h3><p>Using the above code snippets, you can implement easily implement and utilise a multi-key dictionary in your programming tasks.</p><p>If you found this article helpful, check out my profile for other articles and follow me for more articles like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cffe0914b94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why did my Disease Classification Model Achieve 99% Accuracy?]]></title>
            <link>https://medium.com/@matthewghannoum/why-did-my-disease-classification-model-achieve-99-accuracy-4b62670d2d02?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b62670d2d02</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 04:54:09 GMT</pubDate>
            <atom:updated>2024-01-29T04:54:09.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hUlWcrV-26V7Gmyx" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Disease Classification?</h3><p>Disease classification is the process by which a patient’s symptoms (and other diagnostics such as using an ECG to detect abnormal heart rhythms) can be used to diagnose a patient with a disease.</p><p>Another way to think about it is, that given the set of symptoms (and diagnostics) of a patient, what is the likely cause of those symptoms. This is what is commonly referred to as a <strong>prognosis</strong>.</p><h3>How can this be Formulated as a ML Optimisation Object?</h3><p>Using a dataset provided on <a href="https://www.kaggle.com/datasets/kaushil268/disease-prediction-using-machine-learning/data">Kaggle</a>, we can associate a One Hot Encoded vector of symptoms and diagnostics, with a prognosis (the target class). The One Hot Encoded vector simply being a list of booleans, in which the boolean value at every index represents whether a symptom is present or not.</p><p>There are many methods and metrics used to evaluate Machine Learning models. The standard metrics being; accuracy, precision, recall (also known as sensitivity) and F1-score.</p><p>In the field of medical science and more specifically diagnostics, <strong>recall</strong> (more commonly referred to as <strong>hit rate</strong> in medicine), is a very important metric. This is because recall is a measure of how many times a person with a given disease, was correctly identified as having that disease.</p><p>In other words, it measures how well a model avoids type II errors (false-negatives). Type II errors, in most cases in medicine are far worse than type I errors (false-positives), as it means a patient may not be given the treatment for a disease. As opposed to a type I, which are more benign and likely to be fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyIFlXojbynggR7UtaqeTg.png" /><figcaption>How recall is calculated. Image source: <a href="https://blog.roboflow.com/precision-and-recall/">Precision and Recall in Machine Learning</a>.</figcaption></figure><p>Today’s CAD (Computer Aided Diagnosis) systems have been <a href="https://en.wikipedia.org/wiki/Computer-aided_diagnosis#:~:text=Today&#39;s%20CAD%20systems%20cannot%20detect,a%20False%20Positive%20(FP)">shown to achieve up to 90% recall</a>. As such, achieving above 90% recall would be considered a success.</p><h3>Necessary Assumptions</h3><p>Given the constraints of the selected dataset, the following assumptions need to made:</p><ul><li>The patient has a disease in our set of diseases.</li><li>All patients have a disease. There is no “no disease” prognosis.</li><li>The patient is only experiencing symptoms in our set of symptoms.</li><li>Making a diagnosis accurately only requires knowing if symptom(s) exist (binary exists or not) and not a metric of its extent/degree.</li></ul><h3>Exploratory Data Analysis</h3><p>The <a href="https://www.kaggle.com/datasets/kaushil268/disease-prediction-using-machine-learning/data">dataset</a> used in this project consists of 132 symptom/diagnostic fields and 1 prognosis field (the target class). There are 41 unique diseases stored in the prognosis field. The original dataset was stored in a training and testing csv, which had 4920 and 42 rows respectively. The training set had perfectly balanced target classes, with 120 rows per prognosis. While the test set had 1 row per prognosis, except for fungal infections which had 2 rows.</p><h3>How Correlated are Symptoms?</h3><p>The question of how correlated symptoms are is an important to investigate, as it could potentially impact the performance of our model. For example, the Naive Bayes classifier assumes that features are conditionally independent. Hence, if two symptoms were correlated it could imply one is dependent on another and hence violate this assumption, and cayase the classifier to perform poorly.</p><h3>Evaluating the Correlation between Boolean Variables</h3><p>There are many methods for measuring correlation between two boolean variables. While Pearson’s correlation can only be used on continuous, numeric data, other measures such as Spearman’s and Kendall’s correlation can work on ordinal variables.</p><p>While technically a boolean variable could be considered ordinal (assuming you treat True as a value greater than False), it doesn’t really suit what our symptom variables are measuring.</p><p>As such, I choose Proportion of Agreement as measure of correlation, as it is simple and effective for boolean variables.</p><p>The Proportion of Agreement is the proportion of times two variables (symptoms) share the same value, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*je1i9L9N-zIM51iWIUqvkA.png" /></figure><p>This assumes both variables have the same number of instances/samples.</p><p>The results from our initial correlation calculations, where that the overwhelming majority of symptoms were highly correlated with other symptoms, as shown by the histogram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*jGPIehcdx4ecs38H0HKGTA.png" /></figure><p>This was puzzling at first as through observation, there appeared to be many symptoms that would not be associated with many other symptoms. However, reviewing the y-data profiling report (a library that automatically generates a data analysis report), it was clear this was because the majority of values for each symptom was False (the symptom being not present, which makes sense given that there are 41 symptoms).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*-zUFyDuc4eISrT_wh7RQEA.png" /></figure><p>To get a better representation of how correlated symptom pairs were, I instead calculated the Proportion of Agreement for only positive instances of each symptom pair. Meaning that both symptoms would have to be present (both equal to True) to be counted as being in agreement.</p><p>The results were that all of the symptoms were not correlated with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*TrKm-o22Rc_DnMi-jeqhaA.png" /></figure><p>To verify this I looked at the symptoms that were most correlated (if the measure was working properly, the symptoms should be medically similar). This revealed the measure was working properly as it included symptom pairs such as fatigue and high feaver as well as vomiting and nausea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*GVex7AtoBoVodXQXArHLHw.png" /></figure><h3>Model Development</h3><h3>Data Cleaning and Preprocessing</h3><p>The dataset provided required almost no data cleaning as there were no missing values and all of the values were in the correct, consistent format. The only cleaning steps involved:</p><ul><li>Converting the 0s and 1s to boolean values: False and True (not necessary but would make more sense in interpretting models later).</li><li>Removing empty columns.</li></ul><p>The only preprocessing task that was necessary was increasing the size of the test set, as it was less than 1% of the size of the training set. I increased the test set size to 20% of the entire dataset while also ensuring each target prognosis class had the same number of rows in both the training and testing set (to ensure there were no imbalances).</p><h3>Feature Engineering</h3><p>Given the simplicity of the features in the dataset, feature engineering wasn’t necessary.</p><h3>Model Training</h3><p>The decision tree model was trained and evaluated using two methods; the first being a basic 80/20 train-test split and the second being the more conclusive stratified Kfolds validation method.</p><p>As hinted in the title, the model performed very well out of the box, so I didn’t seek to tune hyperparameters using a validation set.</p><p>The only custom parameter set was the random state (using an arbitary value), to ensure results were repeatable.</p><h3>Evaluation</h3><p>On the train-test split, the decision tree model achieved:</p><ul><li>Test accuaracy: 99.90%</li><li>Recall: 99.91%</li><li>Precision: 99.91%</li><li>F1-score: 99.90%</li></ul><p>Initially, I thought these results might have been so high because the model was being overfit on a certain portion of the data. To test this hypothesis I utilised stratified Kfolds cross validation to train and test the decision tree model on different parts of the dataset, to ensure that the model was consistent overall. Furthremore, the “stratified” version of this technique ensures there is an equal number of each target class (each type of disease/prognosis) in each training and testing set. To ensure there aren’t any imbalances in the model training and any biases in evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJDh37rxIAnjqiIncL3etg.png" /><figcaption>Diagram of how Kfolds cross validation works. Image from <a href="https://docs.ultralytics.com/guides/kfold-cross-validation/">Ultralytics</a>.</figcaption></figure><p>The number of folds I choose was 10 (arbitary rule of thumb I found through research).</p><p>The final cross validation score is the average of the test accuracies from each fold, which for the tree model was: 99.98%.</p><h3>Why did the Decision Tree Model perform so well?</h3><p>This degree of performance from a decision tree model, out of the box with no need for hyperparameter tuning or feature engineering seems to be strikingly unusual.</p><p>After revisiting the original dataset and furthering the initial analysis, it became clear that the dataset lended itself to being easily interpretable/learnable. The primary reason being, that there were no overlaps between any prognoses, meaning the feature space was quite isolated. An overlap being where a pair of prognoses have the identifical symptom vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chhJekHJ_nEddx3URi0H3w.png" /><figcaption>An example of what overlaps between classes would look like on a logistic regression. In our dataset, each side of the line would be a completely distinct colour. Image from <a href="https://towardsdatascience.com/understanding-logistic-regression-step-by-step-704a78be7e0a">Gustavo</a>.</figcaption></figure><p>Furthermore, the majority of symptom vectors for all prognoses were duplicates.</p><p>These two characteristics of the dataset made the boundaries of each target class easily seperable by the tree model. Hence leading to the great out of the box performance.</p><h3>GitHub Repository</h3><p><a href="https://github.com/LGXprod/Disease-Prediction">https://github.com/LGXprod/Disease-Prediction</a></p><h3>References</h3><ul><li><a href="https://www.kaggle.com/datasets/kaushil268/disease-prediction-using-machine-learning/data">https://www.kaggle.com/datasets/kaushil268/disease-prediction-using-machine-learning/data</a></li><li><a href="https://en.wikipedia.org/wiki/Computer-aided_diagnosis#:~:text=Today%27s%20CAD%20systems%20cannot%20detect,a%20False%20Positive%20(FP)">https://en.wikipedia.org/wiki/Computer-aided_diagnosis#:~:text=Today&#39;s CAD systems cannot detect,a False Positive (FP)</a></li><li><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10205571/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10205571/</a></li><li><a href="https://stats.stackexchange.com/questions/222924/correlation-between-two-binary-variables">https://stats.stackexchange.com/questions/222924/correlation-between-two-binary-variables</a></li><li><a href="https://en.wikipedia.org/wiki/Conditional_independence">https://en.wikipedia.org/wiki/Conditional_independence</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b62670d2d02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Basics: Everything you Need to Know for 90% of your Projects]]></title>
            <link>https://medium.com/@matthewghannoum/pandas-basics-everything-you-need-to-know-for-90-of-your-projects-972a964a1377?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/972a964a1377</guid>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 06:39:38 GMT</pubDate>
            <atom:updated>2024-01-18T06:39:38.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pandas Basics: Everything you Need to Know for 90% of Projects</h3><p>Pandas is an incredible data ingestion and processing package. Thanks to it’s simplicity and utility, it has become the de-facto choice in the Data Engineering and Data Science fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h_V-y16V8-jIrK5Q" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To get started with Pandas, ensure you have Python installed and have activated your desired environment. If you are unsure what a Python environment is or how to use them, you can quickly get up to speed by reading my article on it: <a href="https://mattgportfolio.netlify.app/blog/python-environments-an-overview/">Python Environments: An Overview</a></p><p>If you haven’t installed Pandas you can by entering the following in your terminal:</p><pre>pip install pandas</pre><p>Next I would recommend creating a Juypter Notebook (although you can use a regular python file) by using your text editor to create a file called tutorial.ipynb or by entering the following in your terminal:</p><pre>touch tutorial.ipynb</pre><p>Open tutorial.ipynb in your text editor of choice and then import the Pandas library by typing the following:</p><pre>import pandas as pd</pre><h3>Creating and Saving a Pandas DataFrame</h3><h3>Reading a CSV to a DataFrame</h3><p>A CSV is a Comma Separated Values file. It can be thought of as a simple table with rows and columns, where each column is separated by a comma and each row by a new line.</p><p>If you would like to follow along with this tutorial exactly, I have provided the example dataset I made in this repository: <a href="https://github.com/LGXprod/Fake-Social-Media-Dataset/blob/main/dataset/nodes/people.csv">Fake Social Media Dataset</a></p><p>Reading a CSV is as simple as the following (assuming example.csv is in the same directory/folder that your Jupyter Notebook is in):</p><pre>people_df = pd.read_csv(&quot;./people.csv&quot;)</pre><p>If you would like to read only certain columns (great for conserving memory if possible), you can instead run:</p><pre>people_df = pd.read_csv(&quot;./people.csv&quot;, usecols=[&quot;first_name&quot;, &quot;last_name&quot;])</pre><h3>Chunking for Large CSVs</h3><p>As you work on bigger, more complex Data Science projects, you find that your computer doesn’t have enough memory to import a CSV or set of CSVs. Or even more likely, there is not enough memory to perform an operation on one or more CSVs (for example a join on two large dataframes).</p><p>One strategy Data Scientists use is to “chunk” the CSV out, which essentially means to read the CSV piece by piece. For example, the following code loads 100 rows into the chunked_df dataframe, which is a dataframe created on each iteration of the for loop until the entire CSV has been read:</p><pre>mean_chunk_ages = []</pre><pre>for people_chunk_df in pd.read_csv(&quot;./people.csv&quot;, chunksize=100):<br>    mean_chunk_ages.append(people_chunk_df[&quot;age:int&quot;].mean())<br>    <br>print(&quot;Average age for each chunk:&quot;, mean_chunk_ages)</pre><h3>Creating a DataFrame using Data Structures</h3><p>There may be times where instead of creating a dataframe by reading a file, you would like to create it from a data structure you have in Python. The two main ways of doing so are by using lists and dictionaries as shown below.</p><h3>Creating a DataFrame from a List</h3><pre>list_df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;])<br>list_df # typing a variable name in a cell will display it&#39;s contents if in a Jupyter notebook</pre><h3>Creating a DataFrame from a Dictionary</h3><pre>dict_df = pd.DataFrame({&quot;a&quot;: [1, 2, 3], &quot;b&quot;: [4, 5, 6], &quot;c&quot;: [7, 8, 9]})<br>dict_df # typing a variable name in a cell will display it&#39;s contents if in a Jupyter notebook</pre><h3>Displaying a DataFrame</h3><p>As shown in the previous section, you can display the contents of a dataframe simply by typing it’s variable name in a cell within a Jupyter Notebook. This was demonstrated with the list_df and dict_df dataframes.</p><p>However, there may be times when you wish to display a smaller portion or specific slice of a dataframe. This can been done using the methods outlined below.</p><h3>Head and Tail Methods</h3><p>The head() method displays the first five rows of a given dataframe:</p><pre>people_df.head()</pre><p>The opposite of head() is also available via the tail() method, which returns the last five rows of a given dataframe:</p><pre>people_df.tail()</pre><h3>List Slicing</h3><p>List slicing is a syntax that Python provides out of the box, to return a certain contiguous portion of a list:</p><pre>nums = [4, 5, 6, 7, 8]<br>print(nums[1:4]) # prints: [5, 6, 7]</pre><p>List slicing can also be applied to dataframes:</p><pre>people_df[10:20] # will display rows 10 to 19</pre><blockquote>⚠️ Note that the first index is inclusive, but the last index is exclusive. That is why in the above example the last row returned is 19, not 20.</blockquote><h3>Combining DataFrame Together</h3><p>Pandas provides methods to help you combine two or more dataframes together. However, to properly utilise these methods it is important to understand how the joins work.</p><p>I recommend this article if you would like to learn about joins in more depth: <a href="https://medium.com/@rslavanyageetha/joins-in-pandas-6d95a2ba8a74">Joins in Pandas</a></p><p>However, as a quick refresher, these are the five types of joins available in pandas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*JFJnPY9VKZn1oDmv8nO_pg.png" /><figcaption>Four of the five joins available in Pandas. Image from <a href="https://medium.com/@rslavanyageetha/joins-in-pandas-6d95a2ba8a74">this article</a>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*rf_wqQD06t0hKO4SKSkD0Q.png" /><figcaption>The fifth join: the Cross Join. Image from <a href="https://medium.com/@akaivdo/pandas-data-combination-1-merge-81fbdf506c85">this article.</a></figcaption></figure><h3>Combine DataFrames using Merge</h3><p>The merge() method can be used to join two dataframes together. In the following example, two dataframes are created; people1_df and people2_df.</p><pre>people1_df = people_df[[&quot;first_name&quot;, &quot;last_name&quot;, &quot;genre&quot;]][:500] # first 500 people<br>people2_df = people_df[[&quot;first_name&quot;, &quot;last_name&quot;, &quot;genre&quot;]][500:] # last 500 people</pre><p>Then an inner join is used to return only people who have the same favourite genre:</p><pre>people1_df.merge(people2_df, how=&quot;inner&quot;, left_on=&quot;genre&quot;, right_on=&quot;genre&quot;)</pre><h3>Conditional Filtering</h3><p>Filtering a dataframe to find certain values or rows is a very common use case when using Pandas. There are multiple approaches to doing so but the simplest is to just use a conditional statement as shown below:</p><pre># displays all people with a bot score between 0.5 and 0.75<br>people_df[(people_df[&quot;bot_score&quot;] &gt;= 0.5) &amp; (people_df[&quot;bot_score&quot;] &lt;= 0.75)]<br># displays all people with the first name Mark<br>people_df[people_df[&quot;first_name&quot;] == &quot;Mark&quot;]<br># displays all people with the first name Mark or John<br>people_df[people_df[&quot;first_name&quot;].isin([&quot;Mark&quot;, &quot;John&quot;])]<br># displays all people who don&#39;t have the name Mark or John<br># the not condition is done using the ~ symbol<br>people_df[~people_df[&quot;first_name&quot;].isin([&quot;Mark&quot;, &quot;John&quot;])]</pre><blockquote>⚠️ Note that if you wish to use multiple conditions (like in the first line of code) you must wrap your conditions in parenthesis.</blockquote><h3>Looping over a DataFrame</h3><pre>genre_freq_above_age_50 = {}</pre><pre>for i, row in people_df.iterrows():<br>    if row[&quot;age:int&quot;] &gt; 50:<br>        genre = row[&quot;genre&quot;]<br>        if genre not in genre_freq_above_age_50:<br>            genre_freq_above_age_50[genre] = 0<br>        genre_freq_above_age_50[genre] += 1<br>        <br>print(genre_freq_above_age_50)</pre><h3>Field Manipulation</h3><h3>Adding a Field</h3><p>If you have a list have is the same length of your dataframe you can add it by assigning it to a new key/field (similar to dictionaries). For example, random_numbers is a list of 1000 random numbers and the people_df also has 1000 rows. As such if we wanted to add this such that row <strong>n</strong> in people_df has the random number of random_numbers[n], you could do the following:</p><pre>random_numbers = [random.randint(0, 20) for _ in range(1000)]<br>people_df[&quot;random_number&quot;] = random_numbers</pre><p>If you wished to assign a singular value to all rows of the people_df you can use the same syntax but with a single value instead of a list:</p><pre>people_df[&quot;greeting&quot;] = &quot;Hello! How are you?&quot;<br>people_df[&quot;num_warnings&quot;] = 0</pre><h3>Deleting a Field</h3><p>Deleting field(s) is simple using the drop() method:</p><pre>people_df.drop(&quot;random_number&quot;, axis=1, inplace=True) # delete a single field<br># delete two fields using a list<br>people_df.drop([&quot;:LABEL&quot;, &quot;random_number&quot;], axis=1, inplace=True)</pre><blockquote>⚠️ Note that the inplace argument is required to be set to true so that the changes from the drop() method change the original dataframe. The inplace argument is also required to be set to true when using the rename() method in the same way.</blockquote><h3>Renaming a Field</h3><p>Renaming fields is done using the rename() method which uses the key to identify the original name of the field and the value to specify what you would like to rename the field to.</p><p>In the following example I rename the birth_date:date and bot_score:float fields to birth_date and bot_score.</p><pre>people_df.rename({ &quot;birth_date:date&quot;: &quot;birth_date&quot;, &quot;bot_score:float&quot;: &quot;bot_score&quot; }, axis=1, inplace=True)</pre><h3>Modifying the Values of a Field</h3><p>You can modify each value in a field by defining a function that converts the input value from the dataframe, into a the desired output and passing that function to the apply() method.</p><p>In the example below, I wrote a function which capitalises each word in the genre field unless the word was “and”.</p><pre>def capitalize_words(text):<br>    words = []<br>    <br>    for word in text.split(&quot; &quot;):<br>        if word != &quot;and&quot;:<br>            words.append(word.capitalize())<br>        else:<br>            words.append(word)<br>            <br>    return &quot; &quot;.join(words)<br><br>people_df[&quot;genre&quot;] = people_df[&quot;genre&quot;].apply(capitalize_words)<br># one of the original values from genre: &quot;Business and entrepreneurship&quot;<br># updated value: &quot;Business and Entrepreneurship&quot;</pre><p>The apply() can also be used to create a new field from an existing field, simply by using a key that doesn’t exist in the original dataframe. For example:</p><pre>people_df[&quot;updated_genre_name&quot;] = people_df[&quot;genre&quot;].apply(capitalize_words)</pre><h3>Removing Duplicates</h3><p>The drop_duplicates method can be used to remove duplicates from a dataframe. The subset argument is used to define what set of field values need to be duplicated, to be considered a duplicate.</p><p>In the following example, only the personId:ID(Person-ID) needs to be the same to be considered a duplicate.</p><pre>existing_person = people_df.iloc[0].tolist()<br># add a person who already exists in the dataframe three times <br># at the bottom of the datafram<br>people_df.loc[len(people_df)] = existing_person<br>people_df.loc[len(people_df)] = existing_person<br>people_df.loc[len(people_df)] = existing_person<br><br>print(len(people_df)) # 1003<br>people_df.drop_duplicates(subset=[&quot;personId:ID(Person-ID)&quot;], inplace=True)<br>print(len(people_df)) # 1000</pre><blockquote>⚠️ Note that only the duplicates are removed and the original row isn’t. The original row is considered to be the one that has the lowest index (closest to the top of the table).</blockquote><h3>Saving a DataFrame to a CSV</h3><p>Finally, the last task you may like to conduct is saving your newly processed dataframe to a CSV. This can be done using the to_csv() method:</p><pre>people_df.to_csv(&quot;./updated_people.csv&quot;, index=False)</pre><p>As shown above, I would also suggest setting index to False as in most cases you don’t want your rows numbered.</p><h3>Conclusion</h3><p>In conclusion, the Pandas library is a crucial tool for anyone working with data in Python. Its wide range of functionalities allows you to easily manipulate and analyze data — from reading and writing files, creating and modifying dataframes, to conducting in-depth analysis with filtering and merging. The ease with which you can perform these tasks makes Pandas a versatile and powerful tool in any data scientist’s toolkit. With the basic understanding and skills acquired in this tutorial, you’re now ready to dive into your own data science projects using Pandas.</p><p>If I forgot any useful methods or properties you use on a regular basis, please comment below and I may add them to the article or in a new post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972a964a1377" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Import your CSV data into a Neo4j Graph Database]]></title>
            <link>https://medium.com/@matthewghannoum/import-your-csv-data-into-a-neo4j-graph-database-d019b95115b1?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d019b95115b1</guid>
            <category><![CDATA[data-import-and-export]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 05:52:45 GMT</pubDate>
            <atom:updated>2024-01-13T07:27:59.939Z</atom:updated>
            <content:encoded><![CDATA[<p>The Neo4j Admin Bulk Import tool enables you to import your CSV(s) into a Neo4j database. It works by separating nodes and edges into different tables, as well as annotating the fields of CSVs so they can be correctly interpreted by the importer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tCE06ATpjsXQIsUi" /><figcaption>Photo by <a href="https://unsplash.com/@pietrozj?utm_source=medium&amp;utm_medium=referral">Pietro Jeng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This tutorial will cover the following:</p><ol><li>How to strategically split your dataset into multiple CSVs</li><li>How to correctly annotate the fields of your CSVs</li><li>How to use the Bulk Import tool</li><li>Viewing the example dataset used in this tutorial</li></ol><h3>How to Strategically Split Your Dataset into Multiple CSVs</h3><p>There are multiple approaches you could take to importing your dataset into Neo4j. However, I would recommend splitting your dataset into nodes and edges, as well as by node type and edge type. For example, a supply chain graph may be split in the following way:</p><p>Nodes:</p><ol><li>Products.csv</li><li>Companies.csv</li><li>Carriers.csv</li><li>Customer.csv</li></ol><p>Edges:</p><ol><li>Delivers.csv (carriers → products)</li><li>Provides.csv (companies → carriers)</li><li>Receives.csv (customer → products)</li></ol><h3>How to Correctly Annotate the Fields of Your CSVs</h3><p>Now that you have split up your dataset, you should add the Neo4j annotations to the fields of your CSV tables. This is not only required for importing certain elements (like edges) but also provides some niceties such as ensuring Neo4j interprets your fields as the correct type (throwing an error if it cannot) as well as ensuring you are setting up the correct relations.</p><p>I have created an example dataset which covers most of what you will need to know about these annotations:</p><p><a href="https://github.com/LGXprod/Fake-Social-Media-Dataset">https://github.com/LGXprod/Fake-Social-Media-Dataset</a></p><h3>Node Datasets</h3><h3>Person Dataset</h3><p>Header fields of people.csv:</p><pre>personId:ID(Person-ID),first_name,last_name,birth_date:date,age:int,location,genre,bot_score:float,:LABEL</pre><p>Every person node in our dataset has a value for each of the fields above.</p><p>Each person can be uniquely identified by the personId field. The :ID annotation allows the importer to know this field is intended as an id field and the (Person-ID) annotation is the id namespace. The id namespace is not required but highly recommended when creating an id field as it allows you to enforce only specified relations (edges). This will be covered more in the edge datasets section.</p><p>String fields such as first_name and last_name do not require a data type annotation as string is the default if Neo4j can’t infer your data type.</p><p>For non-string types such as date, int and float the data type annotation isn’t required but recommended to ensure the type is inferred correctly. This can be seen with fields such as birth_date, age and bot_score.</p><p>The final field in the header is a special field called :LABEL. This field defines your “node type”, so because we are only creating people nodes in the people.csv this whole field will contain the same value: person.</p><h3>Poster Dataset</h3><p>Header fields of posters.csv:</p><pre>posterId:ID(Poster-ID),username,age:int,genres:string[],:LABEL</pre><p>Every “poster” on this social media platform has there unique set of properties to the regular people. The same syntax and recommendations for the people nodes follow here, however there is one additional data type and that is the list. This can be seen on the genres:string[] field where the genres property can contain multiple string values because of the [] syntax.</p><h3>Edge Datasets</h3><h3>Follows</h3><p>Header fields of follows.csv:</p><pre>personId:START_ID(Person-ID),personId:END_ID(Person-ID),:TYPE</pre><p>An edge in a graph is simply a connection from one node to another (node)-(node). Neo4j treats all edges as directed edges meaning the start node points to the end node: (start node) → (end node).</p><p>As such, instead of using the :ID annotation like in the node tables, we need to use the :START_ID and :END_ID annotations. Moreover, like with the node ids, we can add an ID name space. This ensures we don’t accidentally create a connection between node types we didn’t intend to. For example in the following code snippet I made an error by adding the id of a <strong>poster</strong> 32b71e1c-15ca-4a24-9005-8162a3bd2154 to the person end ID, which is supposed to be a <strong>person</strong>:</p><pre>personId:START_ID(Person-ID),personId:END_ID(Person-ID),:TYPE<br>4c419279-d0d6-4290-9563-b42db18dbe9b,aa147d2e-dae2-4818-a250-ce29120b300e,follows<br>4c419279-d0d6-4290-9563-b42db18dbe9b,32b71e1c-15ca-4a24-9005-8162a3bd2154,follows</pre><p>If we did not include the (Person-ID) ID namespace then the bulk importer would import this faulty relationship. However, with the ID namespace the bulk importer will produce an error and stop the import so that we can fix the data.</p><p>The :TYPE field is essentially the equivalent of the :LABEL field for edges. In that it defines the “type” of the edge. As can be seen with the previous code snippet each value of :TYPE will be the same.</p><h3>Subscribes</h3><p>Header fields of subscribes.csv:</p><pre>personId:START_ID(Person-ID),posterId:END_ID(Poster-ID),:TYPE</pre><p>The subscribes dataset follows the same conventions discussed in the previous section. However, it does should how nodes of different types (in this case people and poster) can have edges between them as well.</p><h3>How to use the Bulk Import tool</h3><p>Now that we have our data ready to be imported, we need to copy it into the import directory of our Neo4j database. If you followed my tutorial on <a href="https://medium.com/@matthewghannoum/simple-graph-database-setup-with-neo4j-and-docker-compose-061253593b5a">setting up a Neo4j database with Docker Compose</a> this will be in ./neo4j_db/import (assuming your shell is in the directory in which you created the docker compose file).</p><p>After you have copied the dataset directory provided earlier in this article into the import directory of your neo4j database, start your neo4j container by running:</p><pre>docker compose up -d</pre><p>Then enter the shell of the neo4j container by entering:</p><pre>docker exec -it &lt;neo4j-docker-container-name&gt; /bin/bash</pre><p>Where &lt;neo4j-docker-container-name&gt; is the name of your Neo4j container (in my aforementioned tutorial the container name is neo4j).</p><p>Once you are inside the Neo4j shell you can enter the following command to start importing the data:</p><pre>neo4j-admin database import full --overwrite-destination \\<br>--nodes=import/dataset/nodes/people.csv \\<br>--nodes=import/dataset/nodes/posters.csv \\<br>--relationships=import/dataset/edges/follows.csv \\<br>--relationships=import/dataset/edges/subscribes.csv \\<br>neo4j</pre><p>The data loading interface should appear like this:</p><figure><img alt="Loading Interface of the Neo4j Admin Bulk Import tool" src="https://cdn-images-1.medium.com/max/1024/1*4YcFpxSGuaKNiN_0BFLhBg.png" /><figcaption>Loading Interface of the Neo4j Admin Bulk Import tool</figcaption></figure><p>And once the import processes are complete it should show you this:</p><figure><img alt="Bulk Import shown as being completed" src="https://cdn-images-1.medium.com/max/646/1*2KO_2U2wnGMbcUIGnViGVw.png" /><figcaption>Bulk Import shown as being completed</figcaption></figure><p>The restart the Neo4j container by running:</p><pre>docker compose down</pre><p>Followed by:</p><pre>docker compose up -d</pre><p>To view the imported data in your database.</p><h3>Viewing the Example Dataset used in this Tutorial</h3><p>You can now view the data in this graph by going into the Neo4j browser and using the buttons in the left panel or writing your own Cypher query.</p><figure><img alt="Using the Neo4j Browser to show that the data was successfully imported" src="https://cdn-images-1.medium.com/max/1024/1*6Cs3MRMQifKIg96HI_OU-A.png" /><figcaption>Using the Neo4j Browser to show that the data was successfully imported</figcaption></figure><p>If you would like to learn about how you can write advanced queries and create advanced visualisations in Neo4j, please follow me as I will be posting an article on this topic in the near future.</p><h3>References</h3><p><a href="https://neo4j.com/docs/operations-manual/current/tutorial/neo4j-admin-import/#_id_space">Neo4j-admin import — Operations Manual</a></p><p><a href="https://neo4j.com/docs/cypher-manual/5/values-and-types/property-structural-constructed/#_property_types">Property, structural, and constructed values — Cypher Manual</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d019b95115b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Forget these Important HTML Elements]]></title>
            <link>https://medium.com/@matthewghannoum/dont-forget-these-important-html-elements-f396c47fa9b5?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f396c47fa9b5</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[accessibility]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 01:23:57 GMT</pubDate>
            <atom:updated>2024-01-13T01:23:57.757Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IVCZn7QcFxzMBbg-" /><figcaption>Photo by <a href="https://unsplash.com/@jacksonsophat?utm_source=medium&amp;utm_medium=referral">Jackson Sophat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the age of Javascript frameworks and their custom components, it has become easier than ever to build elements that function and appear exactly how you like. While only using a few of the standard HTML elements, learnt at the beginning of your journey into Web Development.</p><p>However, HTML5 provides many tags you may have forgotten, or neglected for the use of the well-known &lt;div&gt;, &lt;p&gt;, &lt;a&gt;, &lt;h1&gt;, etc.</p><p>Incorporating the following HTML elements has the potential to increase SEO, increase accessibility (e.g. by making screen readers more effective) and making your markup clearer and more readable.</p><h3>Navigation and Layout Elements</h3><p>Recently I’ve been building some simple, static websites for my portfolio. As part of that I found that I was often only utilising the &lt;div&gt; element to section off parts of my page to form a certain layout.</p><p>As I began repeating building certain parts of the page layout (nav bar, footer, information sections), and saw some examples of other peoples work, I realised I was not utilising some elements that could provide more semantic meaning to the page contents.</p><h3>Header and Footer</h3><p>Headers and footers are usually the components of a page that sandwich a page’s content. The header being a place to include an image, heading or other information to outline the purpose of the page. While, the footer, in modern website design has become a place to contain secondary page links, contact information, policies and terms and other information of that nature.</p><p>The &lt;header&gt; and &lt;footer&gt; elements can be added around the your links (or div that you use to create your component) to signify in the markup, what it is.</p><h3>Nav and Menu</h3><p>Navigation bars and menus, are also very common parts of many websites and applications. Similarly to the previous elements, &lt;nav&gt; and &lt;menu&gt; can be used to encapsulate links or &lt;div&gt; .</p><h3>Hgroup and Section</h3><p>Many websites, especially those with pages that have many snippets of short-form content, should be utilising the &lt;section&gt; element. On the other hand, &lt;hgroup&gt; has a less obvious application, but is also quite useful. The &lt;hgroup&gt; tag “<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hgroup">represents a heading and related content . It groups a single &lt;h1&gt;–&lt;h6&gt; element with one or more &lt;p&gt;”</a>. An example of where this is useful, is on the landing section of a home page, where a business would like the title of their product and their catchphrase/slogan for it beneath.</p><blockquote>⚠️ Warning: Ensure that you check that you are using the correct section component. Section with a lowercase s → &lt;section&gt; is the HTML element, while an uppercase S → &lt;Section&gt; could be a JS component that already exists in your application.</blockquote><h3>Purpose Elements</h3><p>Another category of elements I found I was under utilising are “Purpose Elements”. These elements are used to signify the importance of a section or page. The two main purpose elements I found were &lt;main&gt; and &lt;article&gt; .</p><p>The &lt;main&gt; tag is used to define the most important content stored within the body of a given page. While the &lt;article&gt; tag is more specific, in that it specifies the main piece of content on a page that could be distributed independently from the rest of the website. For example, it could be used to contain a blog post or newspaper article.</p><h3>Conclusion</h3><p>Utilising these tags in your website or web application can potentially improve SEO but also makes the markdown easier to interpret (especially when you can’t rely on CSS classes like when using TailwindCSS).</p><p>If you’d me to cover more under utilised HTML elements or have a suggestion of an element that isn’t used enough, please leave a comment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f396c47fa9b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Graph Database Setup with Neo4j and Docker Compose]]></title>
            <link>https://medium.com/@matthewghannoum/simple-graph-database-setup-with-neo4j-and-docker-compose-061253593b5a?source=rss-8de6ff69bd4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/061253593b5a</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Matthew Ghannoum]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 01:16:03 GMT</pubDate>
            <atom:updated>2024-01-13T01:16:03.061Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a graph database in Neo4j is a simple process with the help of Docker Compose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SxK3K2CnicdRzgTy.jpg" /><figcaption>Abstract Graph Visualisation: Image from <a href="https://www.lytics.com/blog/what-is-a-graph-database-the-role-of-graphs-in-data-analysis/">lytics.com</a></figcaption></figure><p>This tutorial will run you through the following steps to get your Neo4j instance up:</p><ol><li>Creating the Docker Compose Files</li><li>Adding an Environment Variables File for your Password</li><li>Running your Neo4j using your Docker Compose file</li></ol><h3>Creating the Docker Compose Files</h3><p>Create a docker-compose.yml file and copy the following snippet into it:</p><pre>services:<br>  neo4j:<br>    container_name: neo4j<br>    image: neo4j:latest<br>    ports:<br>      - 7474:7474<br>      - 7687:7687<br>    environment:<br>      - NEO4J_AUTH=neo4j/${NEO4J_PASSWORD}<br>      - NEO4J_apoc_export_file_enabled=true<br>      - NEO4J_apoc_import_file_enabled=true<br>      - NEO4J_apoc_import_file_use__neo4j__config=true<br>      - NEO4J_PLUGINS=[&quot;apoc&quot;, &quot;graph-data-science&quot;]<br>    volumes:<br>      - ./neo4j_db/data:/data<br>      - ./neo4j_db/logs:/logs<br>      - ./neo4j_db/import:/var/lib/neo4j/import<br>      - ./neo4j_db/plugins:/plugins</pre><p>Note the APOC (Awesome Procedures on Cypher) and Graph Data Science plugins are not required to run Neo4j. However, they are quite useful and I have used them in most of my own Neo4j projects so I included them here.</p><p>If you do not wish to have the Graph Data Science plugin, delete it from the NEO4J_PLUGINS list and if you wish to remove the APOC plugin delete every line that includes the word APOC. Note that the APOC plugin is required to run the Graph Data Science plugin.</p><h3>Creating a Docker Compose Override for your Memory Configuration</h3><p>Next create a file called docker-compose.override.yml. If you are unfamiliar with this override file that’s ok. It is simply a way to be able to modify your original docker-compose.yml file with certain parameters when you run it.</p><p>This is particularly useful when you would like a certain part of your configuration to be different, on different systems you may run your container on.</p><p>For example in the case of Neo4j, you may wish to set your memory limit to a different value on your laptop than on your desktop or production server.</p><p>Copy the following into the docker-compose.override.yml:</p><pre>services:<br>  neo4j:<br>    environment:<br>      - NEO4J_server_memory_heap_initial__size=6G<br>      - NEO4J_server_memory_heap_max__size=6G</pre><p>If you are using git for version control I would recommend adding the docker-compose.override.yml file to your .gitignore file and creating a file called docker-compose.override.example.yml. From which you can copy and paste the example and rename it to docker-compose.override.yml.</p><p>This serves enables you to commit the parameters in the configuration you would like to change, but not the values of those parameters. This in turn avoids overriding different memory limit values from different machines.</p><h3>Check System and Docker Memory Constraints</h3><p>But how do you know what the NEO4J_server_memory_heap_initial__size and NEO4J_server_memory_heap_max__size variables should be set to?</p><p>Firstly, I’d recommend just setting them to the same value of whatever you pick.</p><p>Secondly, I suggest checking your memory limit in the Docker Desktop app and if you are using WSL2 (Windows Subsystem for Linux) in WSL2.</p><p>You can check the memory limit in Docker Desktop by clicking the settings icon in the top right and then clicking on the resources tab. As you can see mine is current set to 7.90 GB. If you would like to change your memory limit for free to do so, just remember what you set it to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQspxAMSUpy5piAugeX21A.png" /><figcaption>Resources section of the Docker Desktop app on MacOS.</figcaption></figure><p>If you like to view your memory limit in WSL2 and possibly change it, I’d recommend following this tutorial:</p><p><a href="https://www.youtube.com/watch?v=h-jNlXN6qhI&amp;ab_channel=JoeFreeman">WSL2 Memory Sizing — Increasing or decreasing the memory available to WSL2</a></p><p>Now that you know the memory limit you have for Docker, you can set the heap memory size to any value under that limit you would like.</p><p>I would recommend testing out some different memory sizes to ensure you can run the container stably.</p><h3>Adding an Environment Variables File for your Password</h3><p>Environment variable files are used to store secrets for your application(s). For this tutorial, the only secret we have is the password of the Neo4j user.</p><blockquote>⚠️ Note that the open source, community version of Neo4j only supports the one “Neo4j” user.</blockquote><p>Create a file called .env and copy the following into it:</p><pre>NEO4J_PASSWORD=&lt;your password&gt;</pre><p>Then replace &lt;your password&gt; with the password you would like to use.</p><p>Again, you can use the strategy of creating a .env.example and gitignoring .env like we did with the docker compose override, if you are using git.</p><blockquote>⚠️ Even if you do not create a .env. <strong>Please add .env to .gitignore if you are using git.</strong> So your password is not committed to your code repository.</blockquote><h3>Running your Neo4j using your Docker Compose file</h3><p>Finally, you can run the Neo4j docker container by entering the following command:</p><pre>docker compose up -d</pre><p>Please ensure your shell is in the same directory in which you created your docker-compose.yml file.</p><p>Now you can access the Neo4j browser by going to http://localhost:7474 and entering your username and password.</p><p>If you would like to learn <strong>how to import your own custom CSV dataset</strong> into Neo4j and <strong>how to query it using Cypher</strong>, please check out my profile and if you appreciate the content click the follow button. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=061253593b5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>