text:
\documentclass[11pt, a4paper]{article} % setsfont size and layout

%% required packages %%
\usepackage{mystyle}
\usepackage[margin=2.5cm]{geometry} % margins

%% Here the main part of the document begins %%

\begin{document}

%% Header on first page with course information etc. %%
\begin{tabular}{p{14.5cm}}
	{\large \textbf{ECO 102: Topics in Economics}} \\
	Ecole Polytechnique, Spring 2022  \\
	\textit{Professors}: Geoffroy Barrows, Benoit Schmutz \\
	\textit{Teaching Assistants}: Arnault Chatelain, Maddalena Conte \\
	\hline
	\\
\end{tabular}

\begin{center}
	{\Large \textbf{TD4: Instrumental Variables}}
	\vspace{2mm}

\end{center}

\vspace{0.4cm}

Today, we will follow \citet{albouy2012colonial}'s critic of \citet{acemoglu2001colonial}' Instrumental Variable (IV). As usual, download the folder TD4.zip, type your answers directly in the Tex script and your Stata commands in a do file.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section*{Exercise}

\begin{enumerate}
    \item A refresher on IVs:
        \begin{enumerate}
            \item What is an Instrumental Variable? Why do we use them?
            \item In the case of \citet{acemoglu2001colonial}, can you recall what they study, what variable they use as an IV and why?
            \item What are the two conditions that should be met when using an IV?
        \end{enumerate}
    \item Go to Moodle and download the dataset ajrcomment.dta. Let us start with a short comment on the use of log in economics.
        \begin{enumerate}
            \item In both papers the authors use log GDP per capita in 1995. Create a variable gdp that contains the GDP per capita in 1995. (We are referring to the natural logarithm here).
            \item Create a scatter plot of mortality rates (y-axis) against GDP per capita in 1995 (x-axis). Do the same with log mortality rate and log GDP. Compare the two. What do you observe?
            \item What is the benefit of using log values in tables?
        \end{enumerate}
    \item Let us now reproduce the results of \citet{acemoglu2001colonial}.
        \begin{enumerate}
            \item Write down the two equations you will use in your 2 Stage Least Square (2SLS) regression (include a single control for Latitude).
            \item Run the first stage equation. Does the instrument seem valid?
            \item Using the command \textbf{predict}, generate a variable riskhat containing the fitted values of this first stage.
            \item Run the second stage regression. Comment on the results. Are the standard errors correct here?
            \item Run the IV regression using the \textbf{ivregress} command this time. Compare with your previous results.
        \end{enumerate}
    \item We can now turn to \citet{albouy2012colonial}'s critic. Albouy's first critic concerns \citet{acemoglu2001colonial}' standard errors.
    \begin{enumerate}
        \item Albouy notices that our authors make conjectures about mortality rates for some countries. Notably, using mortality rate for some countries they extrapolate the mortality rate of neighbouring countries - in fact they even reuse the same rates sometimes. This violates one of the basic assumptions of OLS regression. Which one?
        \item To make up for this, it is possible to cluster data, that is to consider that different groups of data (say continents) are independent but the observations composing them (countries here) are not. Albouy also suggest to run an regression robust to heteroskedasticity. Do you know what this is? Can you give an example of what it corresponds to?
        \item Rerun the first stage equation with standard errors (SE) that are robust (\textit{i.e.} allowing for heteroskedasticity) and clustered at the mortality rate level. How does it change?
    \end{enumerate}
    \item Albouy's second critic concern the validity of the data for some countries. Not only is the data for some countries simply extrapolated from neighbouring countries but also all data sources are not comparable, some rates concerning soldiers living in barracks, some concerning soldiers during campaign and some concerning forced labor.
    \begin{enumerate}
        \item Retaining only countries for which the mortality rate is not extrapolated and including dummies for data sources (campaign and slave variables) and continents rerun a 2SLS regression. Comment on the first stage. What value do you find for the expropriation risk coefficient?
        \item Compute the GDP ratio of Mexico on the US. Now using the previous coefficient what would be the new value of this ratio were Mexico to have the same property right  as the US? Comment on the result.
    \end{enumerate}
\end{enumerate}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\bibliographystyle{apalike}
\bibliography{references}

\end{document}


text:
<% set footnote_lut = dict() %>
<% set footnotes = namespace(i=1) %>
<%- from 'reporting/tex/fragments/macros.tex' import create_evidence_linklist with context -%>
<%- from 'reporting/tex/fragments/evidence.tex' import create_evidence with context -%>
<%- from 'reporting/tex/fragments/place.tex' import create_place with context -%>
<%- from 'reporting/tex/fragments/religion.tex' import create_religion with context -%>
<%- from 'reporting/tex/fragments/person.tex' import create_person with context -%>
<%- from 'reporting/tex/fragments/timeline.tex' import create_timeline with context -%>
<%- from 'reporting/tex/fragments/metadata.tex' import creation_metadata, filter_description with context -%>

\documentclass[fontsize=10pt,toc=chapterentrywithdots]{scrreprt}
\usepackage{scrtime}
\usepackage{scrlayer-scrpage}
\usepackage[margin=1in]{geometry}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{csquotes}
\PassOptionsToPackage{hyphens}{url}\usepackage[hidelinks]{hyperref}
\usepackage{graphicx}
\usepackage{float}
\usepackage{lastpage}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\usepackage{array}
\usepackage{longtable}
\usepackage{amssymb}

\usepackage{fontspec}
\newfontfamily{\defaultfont}{FreeSerif}
\newfontfamily\syriacfont[Script=Syriac]{Estrangelo Talada}
\newfontfamily\arabicfont[Script=Arabic]{Noto Naskh Arabic}
\newfontfamily\hebrewfont[Script=Hebrew]{FreeSerif}
\setmainfont{FreeSerif}
\setsansfont{FreeSans}
\setmonofont{FreeMono}

\usepackage{polyglossia}
\setmainlanguage{english}
\setotherlanguages{arabic,armenian,coptic,georgian,greek,hebrew,hindi,kurdish,latin,macedonian,persian,russian,sanskrit,syriac,turkish,urdu}

\setlength\parindent{0pt}
\setlength\parsep{7pt}

\begin{document}

\title{Report \texttt{\href{<<report_url|texsafe>>}{<<report_id|texsafe>>}}}
\subtitle{\textsc{Damast} \texttt{<<server_version|texsafe>>}}
\date{<<metadata.current_time>>}
\author{Provisioned by \texttt{<<metadata.current_user>>}}
\publishers{Generated with \textsc{Damast} \\ \small{\url{https://github.com/UniStuttgart-VISUS/damast}}}

\maketitle

\automark*{chapter}
\pagestyle{scrheadings}
\setkomafont{pageheadfoot}{\scriptsize}
\ofoot*{\texttt{\href{<<report_url|texsafe>>}{<<report_id|texsafe>>}}}
\cfoot*{}
\ifoot*{\textsc{Damast} \texttt{<<server_version|texsafe>>}}
\ohead*{Page \thepage{} of \pageref{LastPage}}
\chead*{}
\ihead*{\textsc{\rightmark}}

\tableofcontents

<% if dbversiondata %>
\clearpage
\chapter*{Version Disclaimer}
\label{chapter:version-disclaimer}
\addcontentsline{toc}{chapter}{\nameref{chapter:version-disclaimer}}
\markboth{Version Disclaimer}{Version Disclaimer}

The instance of \textsc{Damast} this report was generated on has \emph{report eviction} turned on.
That means that the contents of reports that have not been accessed for a while are deleted to save storage space.
The reports in question can still be accessed, but will be re-created on demand from the database.
On systems with report eviction, the assumption is that there are no major changes to the underlying data in the database, to ensure that the report content overall does not change.
However, in some cases smaller updates to the data might still happen.
This report was originally created with a different version of the underlying data, but was evicted and now re-created with a newer version.
Some changes to its contents might be present.

This is the chronological history to the data in this \textsc{Damast} instance.
The last entry is the version of the database this report was created with.
The version the report was originally created with is marked with an arrow:

\begin{center}
\renewcommand{\arraystretch}{1.3}
\footnotesize
\begin{longtable}{@{}p{1cm}p{1.5cm}p{6cm}p{5.8cm}@{}}
  \textbf{Version} & \textbf{Date} & \textbf{URL} & \textbf{Description} \\
  \hline
  \endhead
    <% for ver in dbversiondata.versions %>
      <%- if ver.version == dbversiondata.original_version -%>
      $\blacktriangleright$
      <%- endif -%>
      \hfill << ver.version >>
      &
      << ver.date >>
      &
      <%- if ver.url -%>
      \scriptsize{\url{<< ver.url | texsafe >>}}
      <%- else -%>
      ---
      <%- endif -%>
      &
      << ver.description >>
      \\
    <% endfor %>
\end{longtable}
\end{center}
<% endif %>

\chapter{Query Description}
\label{sec:filters}

<< creation_metadata(metadata) >>

<< filter_description(filter_desc) >>

This report contains:
\textbf{<< evidences | length >>} distinct pieces of evidence,
\textbf{<< places | length >>} distinct places,
\textbf{<< religions | length >>} distinct religions,
<% if persons|length %>
\textbf{<< persons | length >>} distinct persons,
<% endif %>
based on \textbf{<< sources | length >>} distinct sources.

\clearpage
\chapter{Pieces of Evidence}
\label{sec:evidences}

<% for evidence in evidences %>
  << create_evidence(evidence) >>
<% endfor %>

\clearpage
\chapter{Places}
\label{sec:places}

\begin{figure}[H]
  \includegraphics[width=\textwidth]{map.pdf}
  \caption{Made with Natural Earth (\url{https://www.naturalearthdata.com/}).}
\end{figure}

<% for place in places %>
<< create_place(place) >>
<% endfor %>

\clearpage
\chapter{Religions}
\label{sec:religions}

<% for religion in religions %>
  << create_religion(religion) >>
<% endfor %>

<% if persons|length %>
\clearpage
\chapter{Persons}
\label{sec:persons}

<% for person in persons %>
  << create_person(person) >>
<% endfor %>
<% endif %>

\clearpage
\chapter{Timeline}
\label{sec:timeline}

<< create_timeline(time_data) >>

<% if sources %>
\clearpage
\chapter{Sources}
\label{sec:sources}

\begin{description}
    <% for i, source in sources %>
  \item[\textsc{<< source.short | texsafe >>}]
      \hypertarget{source<<source.id>>}{<< source.name | texsafe >>
        \emph{<< source.source_type | texsafe >>}}

      << create_evidence_linklist(source_evidence[source.id], before='', middle=' based on this source: ', after='') >>
    <% endfor %>
\end{description}
<% endif %>

\clearpage
\chapter*{How to Cite}
\ihead*{\textsc{How to Cite}}
\label{sec:how-to-cite}
\addcontentsline{toc}{chapter}{\nameref{sec:how-to-cite}}

We suggest to cite this report in the following way:

\begingroup
\small
\begin{quote}
  Damast report \texttt{<< report_id >>},
  based on data by Ralph Barczok and Bernd A. Vest, and the visualization of
  \emph{Damast --- A Research System to Analyze Multi-Religious Constellations in the Islamicate World,}
  edited by Dorothea Weltecke, Steffen Koch, Ralph Barczok, Max Franke, Florian Jäckel, and Bernd A. Vest.
  April 2022.
  Created << metadata.current_time_short >>.
  \url{<< report_url >>}, data deposited at DaRUS:
  \url{https://doi.org/10.18419/darus-2318}.
\end{quote}
\endgroup

\clearpage
\chapter*{License}
\label{sec:license}
\ihead*{\textsc{License}}
\addcontentsline{toc}{chapter}{\nameref{sec:license}}

\begingroup
\small
\begin{verbatim}
<% include "reporting/license.txt" %>
\end{verbatim}
\endgroup

\end{document}

ext: tex

max_stars_repo_name: UniStuttgart-VISUS/damast

max_issues_repo_name: UniStuttgart-VISUS/damast

max_forks_repo_name: UniStuttgart-VISUS/damast


text: \section{Examples of rings}

max_stars_repo_name: adamdboult/nodeHomePage

max_issues_repo_name: adamdboult/nodeHomePage

max_forks_repo_name: adamdboult/nodeHomePage


text:
\chapter{Finding the Maximum Subarray Sum}
The objective of this challenge is to find the maximum value of the sum of
elements in a subarray of a given array. If all integers are negative, said
maximum value is the sum of a subarray equivalent to the `empty set', which is
zero.

\section{Cubic Brute Force Algorithm}
\imb[6][15]{\alg/maxsubarray.cpp}
This algorithm utilises three loops and a function of constant time in the
innermost loop. Therefore, the time complexity analysis goes:
\[ T(n)=\sum_{i=1}^n\sum_{j=i}^n\sum_{k=i}^j1=O\left(n^3\right) \]
Obviously this method is quite wasteful in both memory and timekeeping. The
following two algorithms are substantial progessions from this algorithm:
\newpage

\section{Quadratic Brute Force Algorithm}
\imb[18][27]{\alg/maxsubarray.cpp}
This algorithm utilises two loops and a function of constant time in the
innermost loop. Therefore, the time complexity analysis goes:
\[ T(n)=\sum_{i=1}^n\sum_{j=i}^n1=O\left(n^2\right) \]

\section{Divide and Conquer}
\imb[30][49]{\alg/maxsubarray.cpp}
This algorithm utilises a divisive recursion and selection controls of constant
time within each recursion. Therefore, the time complexity analysis goes:
\[ T(n)=2T\left(\frac{n}{2}\right)+n=2^kT\left(\frac{n}{2^k}\right)+nk,~
\therefore T(n)=2^{\log_2n}T(1)+n\log_2n=n\log_2n+\varepsilon n=O(n\log n) \]
\newpage
While these two algorithms are quite effective compared to Cubic Brute Force,
this last algorithm manages to provide the fastest solution possible:

\section{Kadane's Algorithm: A Linear, Incremental Solution}
\imb[52][59]{\alg/maxsubarray.cpp}
This algorithm utilises one loop and a function of constant time in the loop.
Therefore, the time complexity analysis goes: \[ T(n)=\sum_{i=1}^n1=O(n) \]

Since, essentially, the challenge requires a system to read each data at least
once, the $O(n)$ function above is obviously the best solution.

max_stars_repo_name: thekpaul/Programming-Methodology

max_issues_repo_name: thekpaul/Programming-Methodology

max_forks_repo_name: thekpaul/Programming-Methodology


text:
\documentclass[11pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{hyperref}
\usepackage[margin=1in]{geometry}
\setlength{\parindent}{0pc}
\setlength{\parskip}{6pt}

\begin{document}

\section*{STAT157 Syllabus: Spring 2022}

Forecasting has been used to predict elections, climate change, and the spread of COVID-19. Poor forecasts led to the 2008 financial crisis. In our daily lives, good forecasting ability can help us plan our work, be on time to events, and make informed career decisions. This practically-oriented class will provide you with tools to make good forecasts.

{\bf Instructors:} Jacob Steinhardt, Yan Zhang, and Danny Hernandez\\ {\bf GSIs:} Frances Ding, Jean-Stanislas Denain, and Collin Burns\\
\\
{\bf Drop policy (IMPORTANT):} Since there is a waitlist for the class, all students who do not turn in Homework 1 will be automatically dropped from the roster.

\subsubsection*{Lecture}

MWF11-12, in 3108 Etcheverry Hall

Zoom link for first 2 weeks of class is \href{https://berkeley.zoom.us/j/93592932586?pwd=Y1hBNEp4OGVqWHMvOXZKcmd1L0d6QT09}{here}.

This class will be heavily disussion-based. Monday and Wednesday lectures will be a combination of traditional lecture and group activities,
while Friday will be student-led small group discussions with instructors helping to facilitate. {\bf Participation in Friday discussions}
will count towards the grade (we'll provide make-up activities for students who need to skip due to COVID-19 exposure).

There will be no official lab / discussion block, but some homework will involve programming and we will have GSIs available during the lab slot to help students debug.

\subsubsection*{Homework}

There will be weekly homework assignments as well as weekly forecasting exercises.

\subsubsection*{Grades}

Instead of exams, there will be a final project. Students in Stat260 will be expected to do a more substantial project. %
%
Grades will be based on a combination of:
\begin{itemize}
\item Discussion participation (15\%)
\item Forecasting Performance (20\%)
\item Homework (35\%)
\item Final project (30\%)
\end{itemize}

There will also be extra credit opportunities later in the semester.

\subsubsection*{Staff Contact}

To reach course staff, you can email \url{forecasting-class-staff@lists.berkeley.edu}. If possible, please avoid emailing professors or GSIs directly!

\end{document}


text:
\documentclass{article}
\usepackage{graphicx}

\author{Michael Fulton and David Josephs}
\date{April 29, 2015}
\title{Writeup For Assignment 2: BST, AVL, and Splay Trees}

\begin{document}
	\maketitle

	\section*{Status of Code}
		The implementation of Binary Search Trees is complete.  Insertion, searching, and removal all work as expected.  The implementation of AVL Trees still has several issues related to rotations,
		including an error where during a rotation, part of the tree is copied and remains linked to by some elements, but forgotten by others.  There is also an issue which causes search to fail due to
		some pointers being misdirected (potentially related to the first issue).  Splay Trees are also implemented fully, but have some errors involving removal of a node with two children.

		This current state of the code means that the following answers and plots are based on the actual performance of BST (the plot is the actual performance of splay trees), and the expected performance of
		AVL trees and Splay trees (except for the plot, which has actual data from AVL trees);

	\section*{Analysis and Plot}
		\begin{enumerate}
			\item False. The worst case performance is O(N), but since the height of BST's average around O(log N), its operations average at O(log N).
			\item True. This should be the case, as all tree operations are a function of their height, and the AVL balancing (when working properly), should limit tree height to O(log N).
			\item True. This should be the case due to the nature of the average height of a splay tree, which comes out around O(log N).
		\end{enumerate}

		This following plot contains actual data from BST and Splay Tree implementations, and theoretical data from AVL trees.
		\clearpage

		\includegraphics[scale = 0.7]{plot.png}

\end{document}


text:
    \filetitle{fisher}{Approximate Fisher information matrix in frequency domain}{model/fisher}

	\paragraph{Syntax}\label{syntax}

\begin{verbatim}
[F,FF,Delta,Freq] = fisher(M,NPer,List,...)
\end{verbatim}

\paragraph{Input arguments}\label{input-arguments}

\begin{itemize}
\item
  \texttt{M} {[} model {]} - Solved model object.
\item
  \texttt{NPer} {[} numeric {]} - Length of the hypothetical range for
  which the Fisher information will be computed.
\item
  \texttt{List} {[} cellstr {]} - List of parameters with respect to
  which the likelihood function will be differentiated.
\end{itemize}

\paragraph{Output arguments}\label{output-arguments}

\begin{itemize}
\item
  \texttt{F} {[} numeric {]} - Approximation of the Fisher information
  matrix.
\item
  \texttt{FF} {[} numeric {]} - Contributions of individual frequencies
  to the total Fisher information matrix.
\item
  \texttt{Delta} {[} numeric {]} - Kronecker delta by which the
  contributions in \texttt{Fi} need to be multiplied to sum up to
  \texttt{F}.
\item
  \texttt{Freq} {[} numeric {]} - Vector of frequencies at which the
  Fisher information matrix is evaluated.
\end{itemize}

\paragraph{Options}\label{options}

\begin{itemize}
\item
  \texttt{'chkSstate='} {[} \texttt{true} \textbar{}
  \emph{\texttt{false}} \textbar{} cell {]} - Check steady state in each
  iteration; works only in non-linear models.
\item
  \texttt{'deviation='} {[} \emph{\texttt{true}} \textbar{}
  \texttt{false} {]} - Exclude the steady state effect at zero
  frequency.
\item
  \texttt{'exclude='} {[} char \textbar{} cellstr \textbar{}
  \emph{empty} {]} - List of measurement variables that will be excluded
  from the likelihood function.
\item
  \texttt{'percent='} {[} \texttt{true} \textbar{} \emph{\texttt{false}}
  {]} - Report the overall Fisher matrix \texttt{F} as Hessian w.r.t.
  the log of variables; the interpretation for this is that the Fisher
  matrix describes the changes in the log-likelihood function in reponse
  to percent, not absolute, changes in parameters.
\item
  \texttt{'progress='} {[} \texttt{true} \textbar{}
  \emph{\texttt{false}} {]} - Display progress bar in the command
  window.
\item
  \texttt{'refresh='} {[} \emph{\texttt{true}} \textbar{} \texttt{false}
  {]} - Refresh dynamic links in each differentiation step.
\item
  \texttt{'solve='} {[} \emph{\texttt{true}} \textbar{} \texttt{false}
  \textbar{} cellstr {]} - Re-compute solution in each differentiation
  step; you can specify a cell array with options for the \texttt{solve}
  function.
\item
  \texttt{'sstate='} {[} \texttt{true} \textbar{} \emph{\texttt{false}}
  \textbar{} cell {]} - Re-compute steady state in each differentiation
  step; if the model is non-linear, you can pass in a cell array with
  opt used in the \texttt{sstate} function.
\end{itemize}

\paragraph{Description}\label{description}

\paragraph{Example}\label{example}

max_stars_repo_name: OGResearch/IRIS-Toolbox-For-Octave

max_issues_repo_name: OGResearch/IRIS-Toolbox-For-Octave

max_forks_repo_name: OGResearch/IRIS-Toolbox-For-Octave


text:
\section{Process API}

\paragraph{Execution Model --- Assembler (simplified)}
\begin{itemize}
  \item \textbf{Principle}: OS interacts directly with compiled programs
  \begin{itemize}
    \item switch between processes/threads \( \leadsto \) \emph{save}/\emph{restore} state
    \item deal with/pass on \emph{signals}/\emph{exceptions}
    \item receive \emph{requests} from applications
  \end{itemize}
  \item \textbf{Instructions}:
  \begin{itemize}
    \item \code{mov}: Copy referenced data from second operand to first operand
    \item \code{add}/\code{sub}/\code{mul}/\code{div}: Add,\dots from second operand to first operand
    \item \code{inc}/\code{dec}: increment/decrement register/memory location
    \item \code{shl}/\code{shr}: shift first operand left/right by amount given by second operand
    \item \code{and}/\code{or}/\code{xor}: calculate bitwise and,\dots of two operands storing result in first
    \item \code{not}: bitwise negate operand
  \end{itemize}
\end{itemize}

\paragraph{Execution Model --- Stack (x86)}
\begin{itemize}
  \item \textbf{stack pointer} (SP): holds address of stack top (growing downwards)
  \item \textbf{stack frames}: larger stack chunks
  \item \textbf{base pointer} (BP): used to organize stack frames
\end{itemize}

\begin{figure}[h]\centering\label{Stack}\includegraphics[width=0.2\textwidth]{Stack}\end{figure}

\paragraph{Execution Model --- jump/branch/call commands (x86)}
\begin{itemize}
  \item \code{jmp}: continue execution at operand address
  \item \code{j\$condition}: jump depending on PSW content
  \begin{itemize}
    \item \emph{true} \( \leadsto \) jump
    \item \emph{false} \( \leadsto \) continue
    \item examples: \code{je} (jump equal), \code{jz} (jump zero)
  \end{itemize}
  \item \code{call}: push function to stack and jump to it
  \item \code{return}: return from function (jump to return address)
\end{itemize}

\paragraph{Execution Model --- Application Binary Interface (ABI)}
\begin{itemize}
  \item \textbf{Idea}: standardizes binary interface between programs, modules, OS:
  \begin{itemize}
    \item executable/object file layout
    \item calling conventions
    \item alignment rules
  \end{itemize}
  \item \textbf{calling conventions}: standardize exact way function calls are implemented
  \begin{itemize}
    \item[$ \leadsto $] interoperability between compilers
  \end{itemize}
\end{itemize}

\paragraph{Execution Model --- calling conventions (x86)}
\begin{itemize}
  \item function call --- \textbf{caller}:
  \begin{enumerate}
    \item save local scope state
    \item set up parameters where function can find them
    \item transfer control flow
  \end{enumerate}
  \item function call --- \textbf{called function}:
  \begin{enumerate}
    \item set up new local scope (local variables)
    \item perform duty
    \item put return value where caller can find it
    \item jump back to caller (IP)
  \end{enumerate}
\end{itemize}

\paragraph{Passing parameters to the system}
\begin{itemize}
  \item parameters are passed through \textbf{system calls}
  \item call number + specific parameters must be passed
  \item parameters can be transferred through
  \begin{itemize}
    \item \textbf{CPU registers} (\textasciitilde 6)
    \item \textbf{Main Memory} (heap/stack -- more parameters, data types)
  \end{itemize}
  \item ABI specifies how to pass parameters
  \item \textbf{return code} needs to be returned to application
  \begin{itemize}
    \item \emph{negative}: error code
    \item \emph{positive + 0}: success
    \item usually returned via A+D registers
  \end{itemize}
\end{itemize}

\paragraph{System call handler}
\begin{itemize}
  \item implements the actual service called through a syscall:
  \begin{enumerate}
    \item saves tainted registers
    \item reads passed parameters
    \item sanitizes/checks parameters
    \item checks if caller has enough permissions to perform the requested action
    \item performs requested action in behalf of the caller
    \item returns to caller with success/error code
  \end{enumerate}
\end{itemize}

\paragraph{Process API --- creation}
\begin{itemize}
  \item process creation events:
  \begin{enumerate}
    \item system initialization
    \item process creation syscall
    \item user requests process creation
    \item batch job-initiation
  \end{enumerate}
  \item events map to two mechanisms:
  \begin{enumerate}
    \item Kernel spawns initial user space process on boot (Linux: \code{init})
    \item User space processes can spawn other processes (within their quota)
  \end{enumerate}
\end{itemize}

\paragraph{Process API --- creation (POSIX)}
\begin{itemize}
  \item \code{PID}: identifies process
  \item \code{pid = fork()}: duplicates current process:
  \begin{itemize}
    \item returns \code{0} to new child
    \item returns new \code{PID} to parent
    \item[$ \leadsto $] child and parent independent after \code{fork}
  \end{itemize}
  \item \code{exec(name)}: replaces own memory based on executable file
  \begin{itemize}
    \item \code{name} specifies binary executable file
  \end{itemize}
  \item \code{exit(status)}: terminates process, returns \code{status}
  \item \code{pid = waitpid(pid, \&status)}: wait for child termination
  \begin{itemize}
    \item \code{pid}: process to wait for
    \item \code{status}: points to data structure that returns information about the process (e.g., exit status)
    \item passed \code{pid} is returned on success, \code{-1} otherwise
  \end{itemize}
  \item \textbf{process tree}: processes create child processes, which create child processes, \dots
  \begin{itemize}
    \item parent and child execute concurrently
    \item parent waits for child to terminate (collecting the exit state)
  \end{itemize}
\end{itemize}

\paragraph{Daemons}
\begin{itemize}
  \item[=] program designed to run in the background
  \item detached from parent process after creation, reattached to process tree root (\code{init})
\end{itemize}

\paragraph{Process States}
\begin{itemize}
  \item \textbf{blocking}: process does nothing but wait \\*
    - usually happens on syscalls (OS doesn't run process until event happens)
\end{itemize}

\begin{figure}[h]\centering\label{ProcessState}\includegraphics[width=0.4\textwidth]{ProcessState}\end{figure}

\paragraph{Process Termination}
\begin{itemize}
  \item different termination events:
  \begin{enumerate}
    \item normal exit (voluntary) \\*
      - \code{return 0} at end of \code{main} \\*
      - \code{exit(0)}
    \item error exit (voluntary) \\*
      - \code{return x} (\code{x} \( \neq 0 \)) at end of \code{main} \\*
      - \code{exit(x)} (\code{x} \( \neq 0 \)) \\*
      - \code{abort()}
    \item fatal error (involuntary) \\*
      - OS kills process after exception \\*
      - process exceeds allowed resources
    \item killed by another process (involuntary) \\*
      - another process sends kill signal (only as parent process or administrator)
  \end{enumerate}
\end{itemize}

\paragraph{Exit Status}
\begin{itemize}
  \item voluntary exit: process returns exit status (integer)
  \item resources not completely freed after process terminates
    \( \leadsto \) \textbf{Zombie} or \textbf{process stub} (contains exit status until collected via \code{waitpid})
  \item \textbf{Orphans}: Processes without parents
  \begin{itemize}
    \item usually adopted by \code{init}
    \item some systems kill all children when parent is killed
  \end{itemize}
  \item exit status on involuntary exit:
  \begin{itemize}
    \item Bits \code{0-6}: signal number that killed process (\code{0} on normal exit)
    \item Bit \code{7}: set if process was killed by signal
    \item Bits \code{8-15}: \code{0} if killed by signal (exit status on normal exit)
  \end{itemize}
\end{itemize}

max_stars_repo_name: Jintzo/OS

max_issues_repo_name: Jintzo/OS

max_forks_repo_name: Jintzo/OS


text:
\section{User Guide}

The nominal set-up for the ephemeris converter is done as follows:

\begin{itemize}
\item[-]     \texttt{sNavObject = simple\_nav.SimpleNav()}: Construct simple nav
\item[-]     \texttt{sNavObject.walkBounds = sim\_model.DoubleVector(errorBounds)}: add desired error bounds for the position, attitude....
\item[-]     \texttt{sNavObject.PMatrix = sim\_model.DoubleVector(pMatrix)}: Add the matrix of standard deviation values
\item[-]    \texttt{sNavObject.crossTrans = True}
\item[-]    \texttt{sNavObject.crossAtt = False}
\end{itemize}


text:
\documentclass[../PHYS306Notes.tex]{subfiles}

\begin{document}
\subsection{Worksheet - Double Pendulum}
\begin{center}
    \includegraphics[scale=0.5]{Lecture-11/w11-img1.png}
\end{center}
\begin{p}
Find the potential energy of the double pendulum.
\end{p}
\begin{s}
The height of the first mass is given by $L_1(1-\cos\phi_1)$, and the height of the second mass is given by $L_1(1-\cos\phi_1) + L_2(1-\cos\phi_2)$ by trigonometry (the second mass is just the height of the first + the relative height from the first mass). Hence the total potential energy is given by:
\[U = U_1 + U_2 = m_1gL_1(1-\cos\phi_1) + m_2gL_1(1-\cos\phi_1) + m_2gL_2(1-\cos\phi_2)\]
\end{s}

\begin{p}
Write the kinetic energy in terms of $\dot{\phi}^2_1$ and $\dot{\phi}^2_2$
\end{p}
\begin{s}
The first mass is easy; it is just $T_1 = \frac{1}{2}m_1L^2\dot{\phi}_1^2$. The second term is slightly harder as the position vector is given by the sum of the vector from the fixed point to $m_1$ plus the vector from $m_1$ to $m_1$. Expanding this out, this yields total kinetic energy:
\[T = \frac{m_1}{2}L_1\dot{\phi}_1^2 + \frac{m_2}{2}\left(L_1^2\dot{\phi}_1^2 + L_2^2\dot{\phi}_2^2 + 2L_1L_2\dot{\phi}_1\dot{\phi}_2\cos(\phi_1 - \phi_2)\right)\]
Note the cross term we get at the end.
\end{s}

\begin{p}
Write the kinetic and potential energies in the simplifying case where the angles $\phi_i$ and their derivatives $\dot{\phi}_i$ are small.Find the two equations of motion in this case.
\end{p}
\begin{s}
Time for the small angle approximation! In the limit of small angles, $\cos\phi \approx 1 - \frac{\phi^2}{2}$ and so the potential energy reduces to:
\[U = \frac{m_1 + m_2}gL_1\phi_1^2 + \frac{m_2}{2}gL_2\phi^2_2\]
For the kinetic term, the only cosine that shows up is the last term. We do have to be slightly careful here as expanding this out, we already get terms that are nonlinear (e.g. $(\phi_1 - \phi_2)^2$). We only want terms of order 2 and lower in our expression, (e.g. $\phi^2, \phi\dot{\phi}, \dot{\phi}^2$) so in our expansion of $\cos(\phi_1 - \phi_2)$ we only keep the highest order term (e.g. just $1$)! Thus the kinetic energy reduces to:
\[T = \frac{m_1 + m_2}{2}L_1^2\dot{\phi}_1^2 + m_2L_1L_2\dot{\phi}_1\dot{\phi}_2 + \frac{m_2}{2}L_2^2\dot{\phi}_2^2\]
\end{s}

\begin{p}
From the two linearized equations of motion for the double pendulum, find the corresponding matrices $\MM$ and $\KK$.
\end{p}
\begin{s}
The EL equations yield:
\[(m_1 + m_2)L_1^2\ddot{\phi}_1 + m_2L_1L_2\ddot{\phi}_2 = -(m_1 + m_2)gL_1\phi_1\]
\[m_2L_1L_2\ddot{\phi}_1 + m_2L_2^2\ddot{\phi}_2 = -m_2gL_2\phi_2\]
Which we can see are (fortunately) linear from our small angle simplification above. We can write these equations in matrix form:
\[\MM\ddot{\bm{\phi}} = -\KK\bm{\phi}\]
Writing out these matrices, we have:
\[\MM = \m{
(m_1 + m_2)L_1^2 & m_2L_1L_2
\\ m_2L_1L_2 & m_2L_2^2}\]
\[\KK = \m{(m_1 + m_2)gL_1 & 0
\\ 0 & m_2gL_2}\]

\end{s}

\begin{p}
What are the eigenfrequencies and eigenvectors (the normal modes) when $m_1 = m_2 = m$ and $l_1 = l_2 = l$?
\end{p}
\begin{s}
In the case that all the masses and lengths are the same, we may write these matrices as:
\[\MM = mL^2\m{2 & 1 \\ 1 & 1}\]
\[\KK = mL^2\m{2\omega_0^2 & 0 \\ 0 & \omega_0^2}\]
Where we introduce $\omega_0 = \sqrt{\frac{g}{l}}$. Exactly as we did last day, we make an Ansatz:
\[\v{z} = \v{a}\exp(i\omega t)\]
This generates a characteristic equation for the eigenvalues:
\[\det(\KK - \omega^2\MM) = 0\]
Expanding this out, we have:
\[\det(mL^2\m{2(\omega_0^2 -\omega^2) & -\omega^2 \\ -\omega^2 & (\omega_0^2 - \omega^2)}) = 0\]
Which yields the equation:
\[2(\omega_0^2 - \omega^2)^2 - \omega^4 = \omega^4 - 4\omega_0^2\omega^2 + 2\omega_0^4 = 0\]
This is a quadratic equation in $\omega^2$, which has roots:
\[\omega_{1/2}^2 = 2\omega_0^2 \pm\sqrt{\frac{16\omega_0^2 - 8\omega_0^2}{4}} = \omega_0^2\left(2\pm \sqrt{2}\right)\]
Now solving for the normal modes (e.g. the eigenvectors), we get solutions:
\[\phi_I(t) = A\m{1 \\ \sqrt{2}}\cos(\omega_1 t - \delta)\]
\[\phi_II(t) = A\m{1 \\ -\sqrt{2}}\cos(\omega_2 t - \delta)\]
We see that this is similar to the results of last day (one mode with the two masses in phase, one mode with the two masses out of phase), but with a difference that the lower mass has a greater amplitude.
\newline\textit{Remark:} After linearization, the problem solving method reduces to what we saw last day; without linearization, the double pendulum system is chaotic! Perhaps to be revisited at the end of this class. But for small deviations from local minima in the potential, this method is generally feasible.
\end{s}
\end{document}