text:
Calculus 1 : How to find acceleration

Example Questions

Example Question #51 : How To Find Acceleration

The velocity of an object is given by the equation . What is the acceleration of the object at time ?

None of these.

Explanation:

The acceleration of the object can be found by differentiating the velocity equation of the object. To do this we can use the product rule where if

.

We must also use the power rule where if

.

Rewriting the velocity equation to , we can apply these rules to the velocity equation along with the knowledge that the derivative of  is  giving us,

.

To find the acceleration at  we now substitute the value of  for  in the acceleration equation.

Example Question #52 : How To Find Acceleration

The velocity of an object is given by the equation . What is the initial acceleration of the object?

None of these.

None of these.

Explanation:

The initial acceleration of the object can be found by differentiating the object's velocity equation  and solving for .

To differentiate the velocity equation, we can use the quotient rule where if

.

Additionally, to find the derivative of the equation we must use the power rule where if

.

Applying these rules with the knowledge that the derivative of  is , we can find the acceleration equation.

The acceleration of the object is the value of the acceleration equation when .

Therefore the initial acceleration of the object is undefined.

Example Question #53 : How To Find Acceleration

The jerk of an object is . What is the acceleration equation of the object if the acceleration is  at time ?

Explanation:

The acceleration equation can be found by integrating the jerk equation .

The integral of  is .

Therefore the acceleration equation is,

.

We can solve for the value of  by using the acceleration given to us at .

Therefore, .

The acceleration equation is then,

.

Example Question #54 : How To Find Acceleration

The position of an object is given by the equation . What is the initial acceleration of the object?

Explanation:

The acceleration of the object can be found by differentiating the position equation  twice.

To differentiate this equation we can use the chain rule where if

.

Therefore the first derivative of the position equation, the velocity equation, is

.

Differentiating the equation a second time yields the acceleration equation.

The initial acceleration of the object is the acceleration of the object at time .

Example Question #55 : How To Find Acceleration

The velocity equation of an object is . What is the acceleration equation of the object?

Explanation:

The acceleration equation of the object is the derivative of the velocity equation. To differentiate the velocity equation we can use the power rule where

.

Rewriting the velocity we obtain

.

Applying the power rule to the velocity equation gives us

.

Therefore, the acceleration equation is

.

Example Question #56 : How To Find Acceleration

The position of an object is given by the equation . What is the equation of acceleration of this object?

Explanation:

The equation of acceleration can be found by differentiating the position equation twice. To differentiate the position equation we can use the power rule and the chain rule where if

and where if

Applying these two rule to the position equation, we can find the velocity equation

To find the acceleration equation we must differentiate the velocity equation. To do this we must use the product rule for the third term in the velocity equation. The product rule is where if

Using this rule we can differentiate the velocity equation

Example Question #57 : How To Find Acceleration

The position of a boat is defined by the equation . What is the boat's acceleration at

Explanation:

The acceleration  is defined as the second derivative of its position , or .

Use the power rule to differentiate the position function twice.

Since  and .

Plugging in

Example Question #58 : How To Find Acceleration

The position of a car is defined by the equation . What is the car's acceleration at ?

Explanation:

The acceleration  is defined as the second derivative of its position , or .

Use the power rule to differentiate.

Since  and .

Swapping in .

Example Question #59 : How To Find Acceleration

The position of a particle is defined by the equation . What is the particle's acceleration at ?

Explanation:

The acceleration  is defined as the second derivative of its position , or .

Use the power rule to differentiate.

Since  and .

Swapping in .

Example Question #60 : How To Find Acceleration

The position of an object is given by the equation . What is the acceleration of the object when ?


text:
# Kiva Editor's Assistant / report / progress.tex

 david_walker bcc8036 2011-10-11   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 \title{Kiva Editor's Assistant\\Progress Report} \author{ David Walker \\ david.walker64@gmail.com } \date{\today} \documentclass[12pt]{article} \newcommand{\tkn}[2]{ \ensuremath{\langle\!} #1 #2 \ensuremath{\!\rangle} } \begin{document} \maketitle \begin{abstract} The Kiva Editor's Assistant (KEA) provides automated support for microfinance charity Kiva.org's volunteer editors, whose job is to clean up English-language loan descriptions that are generally written by non-native English speakers. KEA iteratively applies rules to its input; these rules perform not only surface structure tasks (such as tokenizing, tagging, determining sentence boundaries, applying regular expression search/replace operations, and expanding ISO currency abbreviations) but also deep structure analysis to do things like correcting pluralization of phrases. The user is presented with the edited result and a report of the changes made. This paper describes the current status of the project and its implementation goals. \end{abstract} \section{Introduction} The Kiva Editor's Assistant (KEA) uses TnT and PET's "cheap" parser loaded with the ERG with the goal of providing automated support for microfinance charity Kiva.org's volunteer editors, whose task is to clean up English-language loan descriptions that are generally written by non-native English speakers. KEA uses multiple passes to tokenize input and apply rules that do things ranging from simple regular expression search/replace operations, to expanding (only the first occurence of) ISO currency abbreviations, to correcting pluralization of phrases like "is a 20 years old farmer" while being aware that a phrase like "is a farmer who is 20 years old" should be left untouched, which is handled by consulting the ERG parse tree. \section{Rules} KEA uses a rule-based approach to processing text. Rules are grouped in phases and by priority; all the rules of a given phase are run in priority order until the first pass which produces no changes to the text occurs, at which time the next phase is invoked. When the last phase no longer produces changes to the text, KEA converts its tokens into output text and delivers that along with a report of the changes made to the original text. The following sections describe the rules in priority order. \subsection{Initial Phase} \subsubsection{Splitting at Spaces} KEA initially creates one token that encompasses the entire input, then subdivides that token. The first subdivision is performed by splitting the input text at spaces, resulting in one token for every space-delimited stretch of characters. Each token records the beginning and ending offset into the original text that it represents, and this indexing information is preserved when splitting (or, later, merging) tokens. \subsubsection{Splitting at Newlines} Every run of one or more newline characters is converted into a single paragraph delimiter token. In addition to providing a hard paragraph break, these tokens are also used to provide a clue to the sentence boundary detection rule. \subsubsection{Splitting at Dots} A common error in the source text is a lack of spaces after sentence-final punctuation, leading to sentences of the form One sentence.And another.'' This rule splits periods into separate tokens, unless they are part of a URL, an abbreviation, or a decimal number. The preceding example, after whitespace split, would result in these tokens: \tkn{One}{0:3} \tkn{sentence.And}{4:16} \tkn{another.}{17:25} After splitting at dots, the resulting tokens are: \tkn{One}{0:3} \tkn{sentence}{4:12} \tkn{.}{12:13} \tkn{And}{13:16} \tkn{another}{17:24} \tkn{.}{24:25} \subsubsection{Converting Decimal Delimiters} Nearly all loans use American-style delimiters for decimal numbers, e.g., 12,345.67''. A very small number of loans use European-style delimiters, e.g. 12.345,67''. For consistency, this rule converts European-style decimal numbers into American-style. \subsubsection{Splitting at Other Punctuation} This rule splits tokens at punctuation other than dots. It is constructed to avoid splitting tokens at numeric punctuation (thousands and decimal delimiters), apostrophes used as contractions and possessive markers (but not as quotes), and asterisks that appear at the start of words (these occur in loans as footnote markers). This rule also avoids splitting hyphenated words; with the way the token lattice is currently constructed, PET will fail to parse separate tokens like 47'' year'' -'' old'' but will succeed with a sequence like 47'' year-old''. \subsubsection{Alphanumeric Split} This rule splits one token into two for a number of cases, illustrated in table \ref{tab:alpha_split}: \begin{table}[h] \begin{center} \begin{tabular}{|l|l|} input & output \\ \hline 10am & 10 am \\ 10.00am & 10.00 am \\ 10:00am & 10:00 am \\ 10:00a.m. & 10:00 a.m. \\ 500foo & 500 foo \\ bar200 & bar 200 \\ ksh.1000 & ksh. 1000 \\ 1,200. & 1,200 . \\ 1200. & 1200 . \\ \end{tabular} \caption{Alphanumeric token splitting.} \label{tab:alpha_split} \end{center} \end{table} \subsubsection{Regular Expression Search and Replace } The user must have the opportunity to review every (non-whitespace) change that KEA has made to the original text. This requirement has an impact on the regular expression search and replace (regex) rules: it would be convenient to have the regex rules operate on the original all-encompassing token before any whitespace split occurs, but doing so would render these changes internal to that single token, which has the disadvantage that textual changes would have to be reconstructed by performing a diff operation between the original and the generated output. Maintaining a link between individual tokens and the indexes of the original text they were initialized from not only makes generating a change report a simpler task but also makes for much easier debugging of the system, as tracking the changes to tokens as the result of successive rule applications is straightforward. For example, consider the sentence Pat joined in the year 2009.'' This is tokenized as: \tkn{Pat}{0:3} \tkn{joined}{4:10} \tkn{in}{11:13} \tkn{the}{14:17} \tkn{year}{18:22} \tkn{2009}{23:27} \tkn{.}{27:28} and is changed by a regex rule to: \tkn{Pat}{0:3} \tkn{joined}{4:10} \tkn{in}{11:13} \tkn{2009}{23:27} \tkn{.}{27:28} The regex rule processor uses dynamic programming to compute the Levenshtein distance at the token level between the source and target strings, which allows it to perform the minimal number of insertions, deletions, and edits to the source tokens to transform them so they represent the target strings. \subsubsection{Spelling Single Digits} As a purely stylistic measure, single digits are spelled out, unless they indicate a percentage (7\%), are part of a list [e.g. 1) 2) 3)], or indicate an amount of currency (\$7). Items for further work include recognizing when single digits are part of an address, or occur in a list that contains multi-digit numbers. A frequent example of the latter is a list of children's ages, such as Pat has 3 children aged 4, 8, and 12.'' In this case the 3'' should be spelled out, but the 4'' and 8'' should not. \subsubsection{Delimiting Currency} \label{sec:delim_currency} Currency amounts larger than four digits are delimited with commas separating thousands. Identifying a number as being a currency amount requires recognizing currency symbols like \$", ISO abbreviations such as PHP'' (Philippine Peso), and local currency terms, such as /='' (a Ugandan abbreviation for shilling). \subsubsection{Concatenating Numbers} \label{sec:concat_num} This is the first of the rules that merges tokens. It searches for consecutive numeric tokens that either have spaces where thousands separators should be, or spaces in addition to thousands separators. \subsubsection{Currency Abbreviation Placement} This rule swaps the position of an ISO currency abbreviation and a following number, unless the abbreviation is also preceded by a number. For example, \tkn{PHP}{0:3} \tkn{1000}{4:8} becomes: \tkn{1000}{0:3} \tkn{PHP}{4:8} \subsubsection{ISO Currency Abbreviation expansion} The initial occurence of an ISO currency abbreviation is spelled out. For example, one 5000 KES loan and another 7000 KES loan'' becomes one 5000 Kenyan Shilling (KES) loan and another 7000 KES loan''. \subsection{POS Phase Rules} Rules in this phase depend on the TnT part-of-speech tagger having supplied POS tags to all tokens. Before processing any of the rules in this phase, KEA writes the text of each token to its own line in a temporary file, then invokes TnT on it, using the WSJ PTB tag set. Early experimentation showed that providing PET with only the highest-priority tag for each token led to parse failures, so KEA launches TnT as a child process with command-line parameters that request not just the highest-probability tag but all tags with at least one hundredth that probability for each token. \subsubsection{Sentence Boundary Detection} This rule looks for a POS tag indicating sentence-final punctuation, as well as terminating sentences when a hard newline is found. The latter is of course generally \emph{not} a reliable indicator of a sentence boundary, but in Kiva loan description text, it is quite reliable. \subsection{Parsed Phase Rules} These rules expect that a parse can at least be attempted, which is why this phase must follow the part of speech tagging phase. For performance reasons, sentences are only parsed on demand. KEA uses PET (specifically the binary cheap'') as an XML-RPC server; if the server isn't detected, KEA will launch it as a daemon. KEA uses PET Input Chart (PIC) input mode, which requires an XML document\footnote{See http://moin.delph-in.net/PetInputChart}. To request the parse of a sentence, KEA converts a sequence of tokens to an XML file using the document type definition pic.dtd from the Heart of Gold\footnote{See http://moin.delph-in.net/HeartofgoldTop} and supplies that to PET. Currently only the w, surface, and pos elements are used; see \ref{fig:pic} for an example. A high priority work item is to either extend the KEA code to create a richer token lattice, or to outsource that job to Heart of Gold's TnTpiXML tokenizer, since some test inputs fail to parse in a reasonable time using the current simplistic token lattice, but are manageable using a lattice created by TnTpiXML. In either case, there is another opportunity to improve the lattice that is unique to this application. Every loan description contains the name of at least one borrower; these names are available in an HTML table on the Kiva editing web page. A future work item, then, is to extract the HTML table contents and use those to mark the names in the token lattice as named entities. As an example, see the handling of the name Kim Novak'' at http://moin.delph-in.net/PetInputChart. \subsubsection{Age Expression} The first (and currently only) parse phase rule searches sentences for expressions like x years old'', then examines the parse provided by PET to determine if the pluralization and hyphenation needs to be corrected. Currrently it considers eleven cases. The first three cases are considered correct usages and are not changed: \begin{enumerate} \item Pat is 47 years old. \item Pat is a 47-year-old farmer. \item {Pat is 1 year old.} \end{enumerate} \flushleft{These cases have the correct pluralization, but lack one or more hyphens:} \begin{enumerate} \setcounter{enumi}{3} \item Pat is a 47 year old farmer. \item Pat is a 47 year old lady who is a farmer. \item Pat is a 47-year old farmer. \item Pat is a 47 year-old farmer. \end{enumerate} The remaining cases all have incorrect pluralization and, except for the last, which are missing one or more hyphens: \begin{enumerate} \setcounter{enumi}{7} \item Pat is a 47 years old farmer. \label{it:years} \item Pat is a 47-years old farmer. \item Pat is a 47 years-old farmer. \item Pat is a 47-years-old farmer. \end{enumerate} Consider case \ref{it:years}. Having determined that the sentence contains the sequence years old'', KEA requests a parse tree (figure \ref{fig:farmer}). Seeing that the grandparent of the \tkn{years}{12:17} token is $\tt plur\_noun\_orule$ and that its great-grandparent's sibling is $\tt npadv$, which satisfy the criteria for case \ref{it:years}, KEA changes the tokens \tkn{47}{9:11} \tkn{years}{12:17} \tkn{old}{18:21} to \tkn{47-year-old}{9:11}. \begin{figure} \centering \begin{verbatim} Pat is a 47 years old farmer . \end{verbatim} \caption{Pet Input Chart for Pat is a 47 years old farmer.''} \label{fig:pic} \end{figure} \begin{figure}[H] \begin{verbatim} root_informal subjh proper_np sing_noun_irule pat hcomp be_c_is npadv_mnp adjh_s_xp a_one_adj nadj_rr measure_np generic_card_ne <47 9:11> plur_noun_orule year_n1 npadv proper_np adjn old_a1 noun_n_cmpnd farmer_n1 sing_noun_irule generic_date_ne <. 28:29> \end{verbatim} \caption{Parse tree for Pat is a 47 years old farmer.''} \label{fig:farmer} \end{figure} \section{Examples} For example, given the initial tokens: \tkn{10}{0:2} \tkn{000}{3:6} \tkn{PHP}{7:10} the concatenation rule will alter them (notice the conservation of the indexes to the original text ranging from 0:6): \tkn{10000}{0:6} \tkn{PHP}{7:10} then the currency delimiting rule will fire, producing: \tkn{10,000}{0:6} \tkn{PHP}{7:10} \begin{table}[h] \begin{center} \begin{tabular}{|l|l|} input & output \\ \hline 10 000 & 10000 \\ \end{tabular} \caption{Concatenating numeric tokens.} \label{tab:accrete} \end{center} \end{table} \section{Future Work} - improve token lattice with Heart of Gold - pluralizing currency names - user-friendly GUI - support for other O/Ss \bibliographystyle{abbrv} \bibliography{main} \end{document}

format: plain


text:
git has seen such a huge adoption over the past few years, so it’s no wonder that there have emerged a number of suggested workflows for it. What git lacks in user-friendliness, it certainly makes up for in flexibility, and it’s this flexibility that has resulted in this wide range of possible use cases.

I’ve spent a while working with git myself, and during that time I’ve seen a few workflows. It’s obvious that different workflows apply for different situations—the recommendations for working within the git source itself are based on the fact that multiple versions need to be maintained, and thus there is a “graduation” system where changes are first merged into the oldest branch requiring support, and then gradually merged upwards to later branches, until a commit finally makes it onto the master branch.

This flow doesn’t really apply to most, and it’s not entirely unreasonable to say that a lot of the features of git are unnecessary for the typical developer. That’s the wonder of git, though: you can customize it to suit your needs.

# Workflow

At Causes, we use git in a perhaps unconventional—but simple—way. Whenever starting on a task, a new branch is created to encapsulate all the changes as a part of that task (you might have heard of this referred to as a “topic” or “feature” branch). As you work on it, the canonical source (origin/master) will be updated by other developers, and so we rebase that feature branch on top of origin/master often so any conflicts can be addressed earlier rather than later (this is in contrast to the merge option, where you use a merge commit to address any conflicts, dealing with them only at that point in time). After commits are approved via our code review tool Gerrit, the commits are cherry-picked serially onto origin/master.

Conceptually, this means our commit history is perfectly linear, as any chunk of work is simply a series of commits that is appended to the history when it is merged onto master. There are no “bubbles” or branches of any kind in the output of git log --graph.

Experts might find this to be a great injustice, as you lose information about where branches started and when they were merged back in, but we’ve found this to not be a significant loss of information. We believe the true value of a repository history lies in well-written commit messages. We also believe that long-lived topic branches are to be avoided, as we want to aim to always push something to master at the end of every day.

# Topic Branch Dependency

A situation that can sometimes arise is when you are working on a topic branch that builds on top of another topic branch which has not yet been merged onto origin/master (due to pending code review, for example).

In order to continue being productive, you want to continue working on feature-2, but it’s likely that you’ll have to make some changes to feature-1 after feedback from code review, or you’ll have to rebase feature-1 onto a new master after fetching origin/master, or both.

This requires you to rebase each branch serially in order to preserve the references of each branch. To see why, consider what would happen if you were to just rebase feature-2 onto an updated master using git rebase feature-2 --onto master (notice in the figure below that the colours of the commits are modified to emphasize that their hashes have changed from the rebase):

Notice that the commit feature-1 is pointing to is no longer the predecessor of feature-2, which during the rebase had its parents updated to the same commits as feature-1 but with different hashes due to the rebase. To fix this, you would need to manually set feature-1 to point to the new commit (git checkout feature-1 && git reset --hard feature-2~2).

Alternatively, you could avoid this problem by rebasing each branch in serial, starting from master:

# Managing Large Dependency Chains

This becomes annoying in the case where you have very large dependency chains, as you have to traverse the chain up to master and then recursively rebase each branch onto its rebased parent in serial.

Although this is a relatively rare occurrence, I was intrigued by the idea of automating this task. I call it a recursive rebase, and I use it regularly as part of my workflow. It’s powered by the following recursive script:

In a nutshell, the script starts on the current branch, and recursively traverses the current branch’s tracking (i.e. remote) branch until it finds a tracking branch whose remote is actually a remote repository (e.g. origin instead of ., which is used to represent the local repository).

I’ve set the alias git rrb to execute this script, completely automating this process for me. There’s probably some edge cases I’ve missed, but after having used it for a while it’s worked without any surprises. It may be over-engineered, but it’s pretty darn cool.

Image


text:
## appleduardo Group Title what is the integral of e^(senx) 4cosx dx ? how can i solve it? one year ago one year ago

1. appleduardo

$\int\limits_{}^{}e ^{sen x} 4\cos x dx$

2. geerky42

sen? You mean sec?

3. satellite73

try $$u=\sin(x), du=\cos(x)dx$$ and you get it in one step

4. appleduardo

i got $[e^{sen x} +c] [4 sen x + c]$ is that correct?

5. appleduardo

i meant "sin":

6. tkhunny

$$\int e^{\sin(x)}\cdot 4\cos(x)\;dx$$ Following satellite73 suggestion u = sin(x) du = cos(x)dx This gives $$\int e^{u}\cdot 4\;du = 4\cdot e^{u} + C$$ Substitute back to where we started. $$4\cdot e^{\sin(x)} + C$$ Be careful, consistent, and confident.

7. appleduardo

thank you so much! but what happened with cos ?

8. tkhunny

It's all in there with the nature of the substitution. See the definition of du.

9. appleduardo

so in this case cos represents the derivative for sin in the formula , right?

10. tkhunny

That is where it came from. You can't just substitute a function. The nature of dx changes when you do that. Is English your first language? The answer to this question might help other folks understand where "sen(x)" came from.

11. appleduardo

haha yeah, uhmm but right now im studying in a spanish-speaking country, so sometimes (unconsciously) isay or write spanish :/ . thank you so!

12. tkhunny

No worries - as long as you don't mind freaking people out when you accidentally write the spanish versions of things. Good work!


text:
# (a) Suppose each single character stored in a computer uses eight bits. Then cach character is represented by a different sequence of eight 0's and l's called a bit pattern. How many different bit patterns are there? (That is, how many different characters could be represented?) (b) How many bit patterns are palindromes (the same backwards as forwards)? (c) How many different bit patterns have an even number of 1's?

(a) Suppose each single character stored in a computer uses eight bits. Then cach character is represented by a different sequence of eight 0's and l's called a bit pattern. How many different bit patterns are there? (That is, how many different characters could be represented?)
(b) How many bit patterns are palindromes (the same backwards as forwards)?
(c) How many different bit patterns have an even number of 1's?
You can still ask an expert for help

## Want to know more about Discrete math?

• Questions are typically answered in as fast as 30 minutes

Solve your problem for the price of one coffee

• Math expert for every subject
• Pay only if we can solve it

Quenchingof
Step 1
a) is relatively straight forward. For the first bit, there are 2 possibilities: 1 and 0. For the first two, the possibilities are 11, 10, 01, and 00. 4 in total. You will find that as you continue this trend, the number of combinations equals ${2}^{n}$ where n is the length of the character.
Step 2
b) is similar. A palindrome is the same forwards as backwards. Therefore the last 4 numbers equal the first 4 in reverse order. Now there are only 4 digits to work with. Use the same system in a) as here, just with 4 instead of 8.
Step 3
c) is a bit tricky. For that one, you simply reduce the power by 1. So with an 8 bit binary string with only even amounts of 1s, you would result with ${2}^{n-1}$ possibilities. In this case, ${2}^{7}$.


text:
# PHP Objects, Patterns, and Practice- P4

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
79
lượt xem
7

## PHP Objects, Patterns, and Practice- P4

Mô tả tài liệu

PHP Objects, Patterns, and Practice- P4: This book takes you beyond the PHP basics to the enterprise development practices used by professional programmers. Updated for PHP 5.3 with new sections on closures, namespaces, and continuous integration, this edition will teach you about object features such as abstract classes, reflection, interfaces, and error handling. You’ll also discover object tools to help you learn more about your classes, objects, and methods.

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: PHP Objects, Patterns, and Practice- P4

1. CHAPTER 7 ■ WHAT ARE DESIGN PATTERNS? WHY USE THEM? PHP and Design Patterns There is little in this chapter that is specific to PHP, which is characteristic of our topic to some extent. Many patterns apply to many object-capable languages with few or no implementation issues. This is not always the case, of course. Some enterprise patterns work well in languages in which an application process continues to run between server requests. PHP does not work that way. A new script execution is kicked off for every request. This means that some patterns need to be treated with more care. Front Controller, for example, often requires some serious initialization time. This is fine when the initialization takes place once at application startup but more of an issue when it must take place for every request. That is not to say that we can’t use the pattern; I have deployed it with very good results in the past. We must simply ensure that we take account of PHP-related issues when we discuss the pattern. PHP forms the context for all the patterns that this book examines. I referred to object-capable languages earlier in this section. You can code in PHP without defining any classes at all (although with PEAR’s continuing development you will probably manipulate objects to some extent). Although this book focuses almost entirely on object-oriented solutions to programming problems, it is not a broadside in an advocacy war. Patterns and PHP can be a powerful mix, and they form the core of this book; they can, however, coexist quite happily with more traditional approaches. PEAR is an excellent testament to this. PEAR packages use design patterns elegantly. They tend to be object-oriented in nature. This makes them more, not less, useful in procedural projects. Because PEAR packages are self-enclosed and hide their complexity behind clean interfaces, they are easy to stitch into any kind of project. Summary In this chapter, I introduced design patterns, showed you their structure (using the Gang of Four form), and suggested some reasons why you might want to use design patterns in your scripts. It is important to remember that design patterns are not snap-on solutions that can be combined like components to build a project. They are suggested approaches to common problems. These solutions 129
2. CHAPTER 7 ■ WHAT ARE DESIGN PATTERNS? WHY USE THEM? 130
3. CHAPTER 8 ■■■ Some Pattern Principles Although design patterns simply describe solutions to problems, they tend to emphasize solutions that promote reusability and flexibility. To achieve this, they manifest some key object-oriented design principles. We will encounter some of them in this chapter and in more detail throughout the rest of the book. This chapter will cover • Composition: How to use object aggregation to achieve greater flexibility than you could with inheritance alone • Decoupling: How to reduce dependency between elements in a system • The power of the interface: Patterns and polymorphism • Pattern categories: The types of pattern that this book will cover The Pattern Revelation I first started working with objects in the Java language. As you might expect, it took a while before some concepts clicked. When it did happen, though, it happened very fast, almost with the force of revelation. The elegance of inheritance and encapsulation bowled me over. I could sense that this was a different way of defining and building systems. I got polymorphism, working with a type and switching implementations at runtime. All the books on my desk at the time focused on language features and the very many APIs available to the Java programmer. Beyond a brief definition of polymorphism, there was little attempt to examine design strategies. Language features alone do not engender object-oriented design. Although my projects fulfilled their functional requirements, the kind of design that inheritance, encapsulation, and polymorphism had seemed to offer continued to elude me. My inheritance hierarchies grew wider and deeper as I attempted to build new classes for every eventuality. The structure of my systems made it hard to convey messages from one tier to another without giving intermediate classes too much awareness of their surroundings, binding them into the application and making them unusable in new contexts. It wasn’t until I discovered Design Patterns, otherwise known as the Gang of Four book, that I realized I had missed an entire design dimension. By that time, I had already discovered some of the core patterns for myself, but others contributed to a new way of thinking. I discovered that I had overprivileged inheritance in my designs, trying to build too much functionality into my classes. But where else can functionality go in an object-oriented system? I found the answer in composition. Software components can be defined at runtime by combining objects in flexible relationships. The Gang of Four boiled this down into a principle: “favor composition 131
4. CHAPTER 8 ■ SOME PATTERN PRINCIPLES over inheritance.” The patterns described ways in which objects could be combined at runtime to achieve a level of flexibility impossible in an inheritance tree alone. Composition and Inheritance Inheritance is a powerful way of designing for changing circumstances or contexts. It can limit flexibility, however, especially when classes take on multiple responsibilities. The Problem As you know, child classes inherit the methods and properties of their parents (as long as they are protected or public elements). You can use this fact to design child classes that provide specialized functionality. Figure 8–1 presents a simple example using the UML. Figure 8–1. A parent class and two child classes The abstract Lesson class in Figure 8–1 models a lesson in a college. It defines abstract cost() and chargeType() methods. The diagram shows two implementing classes, FixedPriceLesson and TimedPriceLesson, which provide distinct charging mechanisms for lessons. Using this inheritance scheme, I can switch between lesson implementations. Client code will know only that it is dealing with a Lesson object, so the details of cost will be transparent. What happens, though, if I introduce a new set of specializations? I need to handle lectures and seminars. Because these organize enrollment and lesson notes in different ways, they require separate classes. So now I have two forces that operate upon my design. I need to handle pricing strategies and separate lectures and seminars. Figure 8–2 shows a brute-force solution. 132
5. CHAPTER 8 ■ SOME PATTERN PRINCIPLES Figure 8–2. A poor inheritance structure Figure 8–2 shows a hierarchy that is clearly faulty. I can no longer use the inheritance tree to manage my pricing mechanisms without duplicating great swathes of functionality. The pricing strategies are mirrored across the Lecture and Seminar class families. At this stage, I might consider using conditional statements in the Lesson super class, removing those unfortunate duplications. Essentially, I remove the pricing logic from the inheritance tree altogether, moving it up into the super class. This is the reverse of the usual refactoring where you replace a conditional with polymorphism. Here is an amended Lesson class: abstract class Lesson { protected $duration; const FIXED = 1; const TIMED = 2; private$costtype; function __construct( $duration,$costtype=1 ) { $this->duration =$duration; $this->costtype =$costtype; } function cost() { switch ( $this->costtype ) { CASE self::TIMED : return (5 *$this->duration); break; CASE self::FIXED : return 30; break; default: $this->costtype = self::FIXED; return 30; } } 133 6. CHAPTER 8 ■ SOME PATTERN PRINCIPLES function chargeType() { switch ($this->costtype ) { CASE self::TIMED : return "hourly rate"; break; CASE self::FIXED : return "fixed rate"; break; default: $this->costtype = self::FIXED; return "fixed rate"; } } // more lesson methods... } class Lecture extends Lesson { // Lecture-specific implementations ... } class Seminar extends Lesson { // Seminar-specific implementations ... } Here's how I might work with these classes:$lecture = new Lecture( 5, Lesson::FIXED ); print "{$lecture->cost()} ({$lecture->chargeType()})\n"; $seminar= new Seminar( 3, Lesson::TIMED ); print "{$seminar->cost()} ({$seminar->chargeType()})\n"; And here's the output: 30 (fixed rate) 15 (hourly rate) You can see the new class diagram in Figure 8–3. 134 7. CHAPTER 8 ■ SOME PATTERN PRINCIPLES Figure 8–3. Inheritance hierarchy improved by removing cost calculations from subclasses I have made the class structure much more manageable but at a cost. Using conditionals in this code is a retrograde step. Usually, you would try to replace a conditional statement with polymorphism. Here, I have done the opposite. As you can see, this has forced me to duplicate the conditional statement across the chargeType() and cost() methods. I seem doomed to duplicate code. Using Composition I can use the Strategy pattern to compose my way out of trouble. Strategy is used to move a set of algorithms into a separate type. By moving cost calculations, I can simplify the Lesson type. You can see this in Figure 8–4. Figure 8–4. Moving algorithms into a separate type I create an abstract class, CostStrategy, which defines the abstract methods cost() and chargeType(). The cost() method requires an instance of Lesson, which it will use to generate cost data. I provide two implementations for CostStrategy. Lesson objects work only with the CostStrategy type, not a specific implementation, so I can add new cost algorithms at any time by subclassing CostStrategy. This would require no changes at all to any Lesson classes. Here’s a simplified version of the new Lesson class illustrated in Figure 8–4: 135 8. CHAPTER 8 ■ SOME PATTERN PRINCIPLES abstract class Lesson { private$duration; private $costStrategy; function __construct($duration, CostStrategy $strategy ) {$this->duration = $duration;$this->costStrategy = $strategy; } function cost() { return$this->costStrategy->cost( $this ); } function chargeType() { return$this->costStrategy->chargeType( ); } function getDuration() { return $this->duration; } // more lesson methods... } class Lecture extends Lesson { // Lecture-specific implementations ... } class Seminar extends Lesson { // Seminar-specific implementations ... } The Lesson class requires a CostStrategy object, which it stores as a property. The Lesson::cost() method simply invokes CostStrategy::cost(). Equally, Lesson::chargeType() invokes CostStrategy::chargeType(). This explicit invocation of another object’s method in order to fulfill a request is known as delegation. In my example, the CostStrategy object is the delegate of Lesson. The Lesson class washes its hands of responsibility for cost calculations and passes on the task to a CostStrategy implementation. Here, it is caught in the act of delegation: function cost() { return$this->costStrategy->cost( $this ); } Here is the CostStrategy class, together with its implementing children: abstract class CostStrategy { abstract function cost( Lesson$lesson ); abstract function chargeType(); } class TimedCostStrategy extends CostStrategy { function cost( Lesson $lesson ) { return ($lesson->getDuration() * 5 ); } function chargeType() { 136
9. CHAPTER 8 ■ SOME PATTERN PRINCIPLES return "hourly rate"; } } class FixedCostStrategy extends CostStrategy { function cost( Lesson $lesson ) { return 30; } function chargeType() { return "fixed rate"; } } I can change the way that any Lesson object calculates cost by passing it a different CostStrategy object at runtime. This approach then makes for highly flexible code. Rather than building functionality into my code structures statically, I can combine and recombine objects dynamically.$lessons[] = new Seminar( 4, new TimedCostStrategy() ); $lessons[] = new Lecture( 4, new FixedCostStrategy() ); foreach ($lessons as $lesson ) { print "lesson charge {$lesson->cost()}. "; print "Charge type: {$lesson->chargeType()}\n"; } lesson charge 20. Charge type: hourly rate lesson charge 30. Charge type: fixed rate As you can see, one effect of this structure is that I have focused the responsibilities of my classes. CostStrategy objects are responsible solely for calculating cost, and Lesson objects manage lesson data. So, composition can make your code more flexible, because objects can be combined to handle tasks dynamically in many more ways than you can anticipate in an inheritance hierarchy alone. There can be a penalty with regard to readability, though. Because composition tends to result in more types, with relationships that aren’t fixed with the same predictability as they are in inheritance relationships, it can be slightly harder to digest the relationships in a system. Decoupling You saw in Chapter 6 that it makes sense to build independent components. A system with highly interdependent classes can be hard to maintain. A change in one location can require a cascade of related changes across the system. The Problem Reusability is one of the key objectives of object-oriented design, and tight coupling is its enemy. You can diagnose tight coupling when you see that a change to one component of a system necessitates many changes elsewhere. You shouldy aspire to create independent components so that you can make changes without a domino effect of unintended consequences. When you alter a component, the extent 137 10. CHAPTER 8 ■ SOME PATTERN PRINCIPLES to which it is independent is related to the likelihood that your changes will cause other parts of your system to fail. You saw an example of tight coupling in Figure 8–2. Because the costing logic was mirrored across the Lecture and Seminar types, a change to TimedPriceLecture would necessitate a parallel change to the same logic in TimedPriceSeminar. By updating one class and not the other, I would break my system— without any warning from the PHP engine. My first solution, using a conditional statement, produced a similar dependency between the cost() and chargeType() methods. By applying the Strategy pattern, I distilled my costing algorithms into the CostStrategy type, locating them behind a common interface and implementing each only once. Coupling of another sort can occur when many classes in a system are embedded explicitly into a platform or environment. Let’s say that you are building a system that works with a MySQL database, for example. You might use functions such as mysql_connect() and mysql_query() to speak to the database server. Should you be required to deploy the system on a server that does not support MySQL, you could convert your entire project to use SQLite. You would be forced to make changes throughout your code, though, and face the prospect of maintaining two parallel versions of your application. The problem here is not the system’s dependency on an external platform. Such a dependency is inevitable. You need to work with code that speaks to a database. The problem comes when such code is scattered throughout a project. Talking to databases is not the primary responsibility of most classes in a system, so the best strategy is to extract such code and group it together behind a common interface. In this way, you promote the independence of your classes. At the same time, by concentrating your gateway code in one place, you make it much easier to switch to a new platform without disturbing your wider system. This process, the hiding of implementation behind a clean interface, is known as encapsulation. PEAR solves this problem with the PEAR::MDB2 package (which has superceded PEAR::DB). This provides a single point of access for multiple databases. More recently the bundled PDO extension has brought this model into the PHP language itself. The MDB2 class provides a static method called connect() that accepts a Data Source Name (DSN) string. According to the makeup of this string, it returns a particular implementation of a class called MDB2_Driver_Common. So for the string "mysql://", the connect() method returns a MDB2_Driver_mysql object, while for a string that starts with "sqlite://", it would return an MDB2_Driver_sqlite object. You can see the class structure in Figure 8–5. Figure 8–5. The PEAR::MDB2 package decouples client code from database objects. The PEAR::MDB2 package, then, lets you decouple your application code from the specifics of your database platform . As long as you use uncontroversial SQL, you should be able to run a single system with MySQL, SQLite, MSSQL, and others without changing a line of code (apart from the DSN, of course, which is the single point at which the database context must be configured). In fact, the PEAR::MDB2 package can also help manage different SQL dialects to some extent—one reason you might still choose to use it, despite the speed and convenience of PDO. 138 11. CHAPTER 8 ■ SOME PATTERN PRINCIPLES Loosening Your Coupling To handle database code flexibly, you should decouple the application logic from the specifics of the database platform it uses. You will see lots of opportunities for this kind of component separation of components in your own projects. Imagine for example that the Lesson system must incorporate a registration component to add new lessons to the system. As part of the registration procedure, an administrator should be notified when a lesson is added. The system's users can't agree whether this notification should be sent by mail, or by text message. In fact, they're so argumentative, that you suspect they might want to switch to a new mode of communication in the future. What's more, they want to be notified of all sorts of things. So that a change to the notification mode in one place, will mean a similar alteration in many other places. If you've hardcoded calls to a Mailer class, or a Texter class, then your system is tightly coupled to a particular notification mode. Just as it would be tightly coupled to a database platform by the use of a specialized database API. Here is some code that hides the implementation details of a notifier from the system that uses it. class RegistrationMgr { function register( Lesson$lesson ) { // do something with this Lesson // now tell someone $notifier = Notifier::getNotifier();$notifier->inform( "new lesson: cost ({$lesson->cost()})" ); } } abstract class Notifier { static function getNotifier() { // acquire concrete class according to // configuration or other logic if ( rand(1,2) == 1 ) { return new MailNotifier(); } else { 139 12. CHAPTER 8 ■ SOME PATTERN PRINCIPLES return new TextNotifier(); } } abstract function inform($message ); } class MailNotifier extends Notifier { function inform( $message ) { print "MAIL notification: {$message}\n"; } } class TextNotifier extends Notifier { function inform( $message ) { print "TEXT notification: {$message}\n"; } } I create RegistrationMgr, a sample client for my Notifier classes. The Notifier class is abstract, but it does implement a static method: getNotifier() which fetches a concrete Notifier object (TextNotifier or MailNotifier). In a real project, the choice of Notifier would be determined by a flexible mechanism, such as a configuration file. Here, I cheat and make the choice randomly. MailNotifier and TextNotifier do nothing more than print out the message they are passed along with an identifier to show which one has been called. Notice how the knowledge of which concrete Notifier should be used has been focused in the Notifier::getNotifier() method. I could send notifier messages from a hundred different parts of my system, and a change in Notifier would only have to be made in that one method. Here is some code that calls the RegistrationMgr, $lessons1 = new Seminar( 4, new TimedCostStrategy() );$lessons2 = new Lecture( 4, new FixedCostStrategy() ); $mgr = new RegistrationMgr(); 140 13. CHAPTER 8 ■ SOME PATTERN PRINCIPLES$mgr->register( $lessons1 );$mgr->register( $lessons2 ); and the output from a typical run TEXT notification: new lesson: cost (20) MAIL notification: new lesson: cost (30) Figure 8–6 shows these classes. Figure 8–6. The Notifier class separates client code from Notifier implementations. Notice how similar the structure in Figure 8–6 is to that formed by the MDB2 components shown in Figure 8–5 Code to an Interface, Not to an Implementation This principle is one of the all-pervading themes of this book. You saw in Chapter 6 (and in the last section) that you can hide different implementations behind the common interface defined in a superclass. Client code can then require an object of the superclass’s type rather than that of an implementing class, unconcerned by the specific implementation it is actually getting. Parallel conditional statements, like the ones I built into Lesson::cost() and Lesson::chargeType(), are a common signal that polymorphism is needed. They make code hard to maintain, because a change in one conditional expression necessitates a change in its twins. Conditional statements are occasionally said to implement a “simulated inheritance.” By placing the cost algorithms in separate classes that implement CostStrategy, I remove duplication. I also make it much easier should I need to add new cost strategies in the future. From the perspective of client code, it is often a good idea to require abstract or general types in your methods’ parameters. By requiring more specific types, you could limit the flexibility of your code at runtime. Having said that, of course, the level of generality you choose in your argument hints is a matter of judgment. Make your choice too general, and your method may become less safe. If you require the specific functionality of a subtype, then accepting a differently equipped sibling into a method could be risky. Still, make your choice of argument hint too restricted, and you lose the benefits of polymorphism. Take a look at this altered extract from the Lesson class: 141 14. CHAPTER 8 ■ SOME PATTERN PRINCIPLES function __construct($duration, FixedPriceStrategy $strategy ) {$this->duration = $duration;$this->costStrategy = $strategy; } There are two issues arising from the design decision in this example. First, the Lesson object is now tied to a specific cost strategy, which closes down my ability to compose dynamic components. Second, the explicit reference to the FixedPriceStrategy class forces me to maintain that particular implementation. By requiring a common interface, I can combine a Lesson object with any CostStrategy implementation: function __construct($duration, CostStrategy $strategy ) {$this->duration = $duration;$this->costStrategy = $strategy; } I have, in other words, decoupled my Lesson class from the specifics of cost calculation. All that matters is the interface and the guarantee that the provided object will honor it. Of course, coding to an interface can often simply defer the question of how to instantiate your objects. When I say that a Lesson object can be combined with any CostStrategy interface at runtime, I beg the question, “But where does the CostStrategy object come from?” When you create an abstract super class, there is always the issue as to how its children should be instantiated. Which child do you choose and according to which condition? This subject forms a category of its own in the Gang of Four pattern catalog, and I will examine it further in the next chapter. The Concept That Varies It’s easy to interpret a design decision once it has been made, but how do you decide where to start? The Gang of Four recommend that you “encapsulate the concept that varies.” In terms of my lesson example, the varying concept is the cost algorithm. Not only is the cost calculation one of two possible strategies in the example, but it is obviously a candidate for expansion: special offers, overseas student rates, introductory discounts, all sorts of possibilities present themselves. I quickly established that subclassing for this variation was inappropriate, and I resorted to a conditional statement. By bringing my variation into the same class, I underlined its suitability for encapsulation. The Gang of Four recommend that you actively seek varying elements in your classes and assess their suitability for encapsulation in a new type. Each alternative in a suspect conditional may be extracted to form a class extending a common abstract parent. This new type can then be used by the class or classes from which it was extracted. This has the effect of • Focusing responsibility • Promoting flexibility through composition • Making inheritance hierarchies more compact and focused • Reducing duplication So how do you spot variation? One sign is the misuse of inheritance. This might include inheritance deployed according to multiple forces at one time (lecture/seminar, fixed/timed cost). It might also include subclassing on an algorithm where the algorithm is incidental to the core responsibility of the type. The other sign of variation suitable for encapsulation is, of course, a conditional expression. 142 15. CHAPTER 8 ■ SOME PATTERN PRINCIPLES Patternitis One problem for which there is no pattern is the unnecessary or inappropriate use of patterns. This has earned patterns a bad name in some quarters. Because pattern solutions are neat, it is tempting to apply them wherever you see a fit, whether they truly fulfill a need or not. The eXtreme Programming (XP) methodology offers a couple of principles that might apply here. The first is “You aren’t going to need it” (often abbreviated to YAGNI). This is generally applied to application features, but it also makes sense for patterns. When I build large environments in PHP, I tend to split my application into layers, separating application logic from presentation and persistence layers. I use all sorts of core and enterprise patterns in conjunction with one another. When I am asked to build a feedback form for a small business web site, however, I may simply use procedural code in a single page script. I do not need enormous amounts of flexibility, I won’t be building on the initial release. I don’t need to use patterns that address problems in larger systems. Instead, I apply the second XP principle: “Do the simplest thing that works.” When you work with a pattern catalog, the structure and process of the solution are what stick in the mind, consolidated by the code example. Before applying a pattern, though, pay close attention to the problem, or “when to use it,” section, and read up on the pattern’s consequences. In some contexts, the cure may be worse than the disease. The Patterns This book is not a pattern catalog. Nevertheless, in the coming chapters, I will introduce a few of the key patterns in use at the moment, providing PHP implementations and discussing them in the broad context of PHP programming. The patterns described will be drawn from key catalogs including Design Patterns, Patterns of Enterprise Application Architecture by Martin Fowler (Addison-Wesley, 2003) and Core J2EE Patterns by Alur et al. (Prentice Hall PTR, 2001). I use the Gang of Four’s categorization as a starting point, dividing patterns as follows. Patterns for Generating Objects These patterns are concerned with the instantiation of objects. This is an important category given the principle “code to an interface.” If you are working with abstract parent classes in your design, then you must develop strategies for instantiating objects from concrete subclasses. It is these objects that will be passed around your system. Patterns for Organizing Objects and Classes These patterns help you to organize the compositional relationships of your objects. More simply, these patterns show how you combine objects and classes. Task-Oriented Patterns These patterns describe the mechanisms by which classes and objects cooperate to achieve objectives. 143 16. CHAPTER 8 ■ SOME PATTERN PRINCIPLES Enterprise Patterns I look at some patterns that describe typical Internet programming problems and solutions. Drawn largely from Patterns of Enterprise Application Architecture and Core J2EE Patterns, the patterns deal with presentation, and application logic. Database Patterns An examination of patterns that help with storing and retrieving data and with mapping objects to and from databases. Summary In this chapter, I examined some of the principles that underpin many design patterns. I looked at the use of composition to enable object combination and recombination at runtime, resulting in more flexible structures than would be available using inheritance alone. I introduced you to decoupling, the practice of extracting software components from their context to make them more generally applicable. I reviewed the importance of interface as a means of decoupling clients from the details of implementation. In the coming chapters, I will examine some design patterns in detail. 144 17. CHAPTER 9 ■■■ Generating Objects Creating objects is a messy business. So many object-oriented designs deal with nice, clean abstract classes, taking advantage of the impressive flexibility afforded by polymorphism (the switching of concrete implementations at runtime). To achieve this flexibility though, I must devise strategies for object generation. This is the topic I will look at here. This chapter will cover • The Singleton pattern: A special class that generates one and only one object instance • The Factory Method pattern: Building an inheritance hierarchy of creator classes • The Abstract Factory pattern: Grouping the creation of functionally related products • The Prototype pattern: Using clone to generate objects Problems and Solutions in Generating Objects Object creation can be a weak point in object-oriented design. In the previous chapter, you saw the principle “Code to an interface, not to an implementation.” To this end, you are encouraged to work with abstract supertypes in your classes. This makes code more flexible, allowing you to use objects instantiated from different concrete subclasses at runtime. This has the side effect that object instantiation is deferred. Here’s a class that accepts a name string and instantiates a particular object: abstract class Employee { protected$name; function __construct( $name ) {$this->name = $name; } abstract function fire(); } class Minion extends Employee { function fire() { print "{$this->name}: I'll clear my desk\n"; } } 145
18. CHAPTER 9 ■ GENERATING OBJECTS class NastyBoss { private $employees = array(); function addEmployee($employeeName ) { $this->employees[] = new Minion($employeeName ); } function projectFails() { if ( count( $this->employees ) > 0 ) {$emp = array_pop( $this->employees );$emp->fire(); } } } $boss = new NastyBoss();$boss->addEmployee( "harry" ); $boss->addEmployee( "bob" );$boss->addEmployee( "mary" ); $boss->projectFails(); // output: // mary: I'll clear my desk As you can see, I define an abstract base class: Employee, with a downtrodden implementation: Minion. Given a name string, the NastyBoss::addEmployee() method instantiates a new Minion object. Whenever a NastyBoss object runs into trouble (via the NastyBoss::projectFails() method), it looks for a Minion to fire. By instantiating a Minion object directly in the NastyBoss class, we limit flexibility. If a NastyBoss object could work with any instance of the Employee type, we could make our code amenable to variation at runtime as we add more Employee specializations. You should find the polymorphism in Figure 9-1 familiar. Figure 9-1. Working with an abstract type enables polymorphism. 146 19. CHAPTER 9 ■ GENERATING OBJECTS If the NastyBoss class does not instantiate a Minion object, where does it come from? Authors often duck out of this problem by constraining an argument type in a method declaration and then conveniently omitting to show the instantiation in anything other than a test context. class NastyBoss { private$employees = array(); function addEmployee( Employee $employee ) {$this->employees[] = $employee; } function projectFails() { if ( count($this->employees ) ) { $emp = array_pop($this->employees ); $emp->fire(); } } } // new Employee class... class CluedUp extends Employee { function fire() { print "{$this->name}: I'll call my lawyer\n"; } } $boss = new NastyBoss();$boss->addEmployee( new Minion( "harry" ) ); $boss->addEmployee( new CluedUp( "bob" ) );$boss->addEmployee( new Minion( "mary" ) ); $boss->projectFails();$boss->projectFails(); $boss->projectFails(); // output: // mary: I'll clear my desk // bob: I'll call my lawyer // harry: I'll clear my desk Although this version of the NastyBoss class works with the Employee type, and therefore benefits from polymorphism, I still haven’t defined a strategy for object creation. Instantiating objects is a dirty business, but it has to be done. This chapter is about classes and objects that work with concrete classes so that the rest of your classes do not have to. If there is a principle to be found here, it is “delegate object instantiation.” I did this implicitly in the previous example by demanding that an Employee object is passed to the NastyBoss::addEmployee() method. I could, however, equally delegate to a separate class or method that takes responsibility for generating Employee objects. Here I add a static method to the Employee class that implements a strategy for object creation: abstract class Employee { protected$name; private static $types = array( 'minion', 'cluedup', 'wellconnected' ); static function recruit($name ) { $num = rand( 1, count( self::$types ) )-1; 147
20. CHAPTER 9 ■ GENERATING OBJECTS $class = self::$types[$num]; return new$class( $name ); } function __construct($name ) { $this->name =$name; } abstract function fire(); } // new Employee class... class WellConnected extends Employee { function fire() { print "{$this->name}: I'll call my dad\n"; } } As you can see, this takes a name string and uses it to instantiate a particular Employee subtype at random. I can now delegate the details of instantiation to the Employee class’s recruit() method:$boss = new NastyBoss(); $boss->addEmployee( Employee::recruit( "harry" ) );$boss->addEmployee( Employee::recruit( "bob" ) ); $boss->addEmployee( Employee::recruit( "mary" ) ); You saw a simple example of such a class in Chapter 4. I placed a static method in the ShopProduct class called getInstance(). getInstance() is responsible for generating the correct ShopProduct subclass based on a database query. The ShopProduct class, therefore, has a dual role. It defines the ShopProduct type, but it also acts as a factory for concrete ShopProduct objects. ■Note I use the term “factory” frequently in this chapter. A factory is a class or method with responsibility for generating objects. // class ShopProduct public static function getInstance($id, PDO $dbh ) {$query = "select * from products where id = ?"; $stmt =$dbh->prepare( $query ); if ( !$stmt->execute( array( $id ) ) ) {$error=$dbh->errorInfo(); die( "failed: ".$error[1] ); } $row =$stmt->fetch( ); if ( empty( $row ) ) { return null; } if ($row['type'] == "book" ) { 148


text:
# CFNS seminar

## "Era of Jet-SubStructure and its utility in high energy collisions"

#### Presented by Raghav Kunnawalkam Elayavalli, Wayne State University

Thursday, August 6, 2020, 4:00 pm — https://bluejeans.com/494177937

Jets, originating from hard scatterings of quarks/gluons (partons), have been established as a very powerful tool of study in high energy colliders. Measurements utilizing jets have been performed at nearly all major collider experiments as probes of the standard model (and BSM), spin, polarization, fundamental QCD and also played an important role in studies of the Quark-Gluon Plasma (QGP) via parton energy loss or jet quenching. Since jet evolution in vacuum is intimately dependent on both the momentum and angular scales, disentangling these scales via jet substructure (JSS) tools can lead to a more differential study of the parton shower. In essence, understanding parton evolution and JSS in vacuum is a necessary prerequisite for qualitatively describing how jets are quenched in the QGP, which in turn leads to extracting the QGP microscopic properties via jet-tomography. In this talk, I will introduce JSS and present recent measurements from the STAR collaboration of JSS observables in p-p, p+Au and Au-Au collisions at $\sqrt{s_{NN}} = 200$ GeV. These results are aimed at describing the vacuum parton shower and study the impact of cold and hot nuclear matter effects differentially with jet topology. I will also discuss an important application JSS whereby we isolated a special selection of jets in heavy ion collisions who's energy loss mechanism can then be further studied in a differential fashion. I will conclude the talk by contextualizing these measurements and briefly discuss some ongoing work related to upcoming heavy ion runs at RHIC and at the recently approved EIC, where JSS can contribute towards studies of quantum entanglement and hadronization within jets in a clean environment.

Hosted by: Jinlong Zhang

15852  |  INT/EXT  |  Events Calendar


text:
# Thread: Inverse Function of Natural Logs

1. ## Inverse Function of Natural Logs

Hi everyone... I've been working on this problem for about a week and I just can't seem to get it. I got the rest of the problems in my homework done but I cant get this one.

A function f (x) is given.
f
(x) = ln(ln(ln 8x))

Find the inverse function of f.
f -1 (x) =

I don't know where to go from here? Any help would be great. Thank you so much!

(PS, I know x = e^y if that helps at all! I dont know where to go now though)

2. Hi ZBomber

Of course it helps a lot to know x = e^y.

$y = ln(ln(ln 8x))$

The inverse is :
$x= ln(ln(ln 8y))$ , now isolate y

$e^x=ln(ln 8y)$

$ln(8y) = ....$ , if you confuse, just let e^x = a

3. It's all based on the fact that $e^{ln(whatever)}=whatever$

y=ln(ln(ln(8x))), the inverse is the reflection: x=ln(ln(ln(8y))), and solve for y...by applying $e^{?}$ to both sides

$e^x=e^{ln(ln(ln(8y)))}$

$e^x={ln(ln(8y))}$

$e^{e^x}=e^{ln(ln(8y))}$

$e^{e^x}={ln(8y)}$

$e^{e^{e^x}}=e^{ln(8y)}$

$e^{e^{e^x}}=8y$, then.....

$y={1\over8}e^{e^{e^x}}$ and therefore $f^{-1}(x)={1\over8}e^{e^{e^x}}$

4. Thank you both so much!

Strangely, I was headed towards the right answer, but I thought it looked way too complicated to be correct so I stopped before I got to the end. I guess I was wrong in that regard.

Again, thank you both!


text:
• Solar Kinetic Energy and Cross Helicity Spectra(1804.10321)

April 27, 2018 astro-ph.SR
The relation between magnetic and velocity fields in the solar atmosphere is a topic that can now be addressed quantitatively at the statistical level. Here we analyze kinetic energy and cross helicity spectra along with magnetic energy and helicity spectra in two solar active regions using vector magnetograms and Dopplergrams of NOAA~11158 and 12266. Within these active regions, we find similar slopes for kinetic and magnetic energy spectra at intermediate wavenumbers, where the contribution from the granulation velocity has been removed. At wavenumbers around $0.3\Mm^{-1}$, the magnetic helicity is found to be close to its maximal value. The cross helicity spectra are found to be within about 10\% of the maximum possible value. We also develop a two-scale method for cross helicity spectra, which allows us to take the cancellation from the bipolarity of active regions into account. In the quiet Sun, by comparison, the cross helicity spectrum is found to be small.
• Intermittency spectra of current helicity in solar active regions(1802.02323)

Feb. 7, 2018 astro-ph.SR
We intend to analyse the intermittency spectra of current helicity in solar active regions. We made a pixel-by-pixel comparison of current helicity maps derived from three different instruments, namely by Helioseismic and Magnetc Imager on board the Solar Dynamics Observatory (SDO/HMI), Spectro-Polarimeter on board the Hinode, and Solar Magnetic Field Telescope at the Huairou Solar Observing Station, China (HSOS/SMFT). The comparison showed an excellent correlation between the maps derived from the spaceborne instruments and moderate correlation between the maps derived from SDO/HMI and HSOS/SMFT vector magnetograms. The results suggest that the obtained maps characterize real spatial distribution of current helicity over an active region. To analyse the multifractality and intermittency of current helicity, we traditionally use the high-order structure function and flatness function approach. The slope of a flatness function within some range of scales - the flatness exponent - is a measure of the degree of intermittency. We used SDO/HMI vector magnetograms to calculate the flatness exponent variations of current helicity of three active regions: NOAA 11158, 12494, and 12673. The flatness exponents were determined within the scale range of 2-10 Mm. All three regions exhibited emergence of a new magnetic flux during the observational interval. Interestingly, the flatness exponent increased rapidly 12-20 hours before the emergence of a new flux and restored its previous value by the beginning of the emergence. We suppose that this behaviour can be explained by subphotospheric fragmentation or distortion of the existed current system by emerging magnetic flux. During the imperturbable development of active region, the flatness exponent of current helicity remains relatively low and the intermittency range shifts toward higher values up to 20-40 Mm.
• Evolution of Relative Magnetic Helicity: New Boundary Conditions for the Vector Potential(1712.09219)

Dec. 26, 2017 astro-ph.SR
We recently proposed a method to calculate the relative magnetic helicity in a finite volume for a given magnetic field which however required the flux to be balanced separately on all the sides of the considered volume. In order to allow finite magnetic fluxes through the boundaries, a Coulomb gauge is constructed that allows for global magnetic flux balance. We tested and verified our method in a theoretical fore-free magnetic field model. We apply the new method to the former calculation data and found a difference of less than 1.2\%. We also applied our method to the magnetic field above active region NOAA 11429 obtained by a new photospheric-data-driven MHD model code GOEMHD3. We analyzed the magnetic helicity evolution in the solar corona using our new method. It was found that the normalized magnetic helicityis equal to -0.038 when fast magnetic reconnection is triggered. This value is comparable to the previous value (-0.029) in the MHD simulations when magnetic reconnection happened and the observed normalized magnetic helicity (-0.036) from the eruption of newly emerging active regions. We found that only 8\% of the accumulated magnetic helicity is dissipated after it is injected through the bottom boundary. This is in accordance with the Woltjer conjecture. Only 2\% of magnetic helicity injected from the bottom boundary escapes through the corona. This is consistent with the observation of magnetic clouds, which could take away magnetic helicity into the interplanetary space, in the case considered here, several halo CMEs and two X-class solar flares origin from this active region.
• Photospheric Magnetic Free Energy Density of Solar Active Regions(1608.07805)

Dec. 8, 2016 astro-ph.SR
We present the photospheric energy density of magnetic fields in two solar active regions inferred from observational vector magnetograms, and compare it with the possible different defined energy parameters of magnetic fields in the photosphere. We analyze the magnetic fields in active region NOAA 6580-6619-6659 and 11158. It is noticed that the quantity 1/4pi Bn.Bp is an important energy parameter that reflects the contribution of magnetic shear on the difference between the potential magnetic field (Bp) and non-potential one (Bn), and also the contribution to the free magnetic energy near the magnetic neutral lines in the active regions. It is found that the photospheric mean magnetic energy density changes obviously before the powerful solar flares in the active region NOAA 11158, it is consistent with the change of magnetic fields in the lower atmosphere with flares.
• Evolution of Magnetic Helicity and Energy Spectra of Solar Active Regions(1503.00846)

Feb. 22, 2016 astro-ph.SR
We adopt an isotropic representation of the Fourier-transformed two-point correlation tensor of the magnetic field to estimate the magnetic energy and helicity spectra as well as current helicity spectra of two individual active regions (NOAA 11158 and NOAA 11515) and the change of the spectral indices during their development as well as during the solar cycle. The departure of the spectral indices of magnetic energy and current helicity from 5/3 are analyzed, and it is found that it is lower than the spectral index of the magnetic energy spectrum. Furthermore, the fractional magnetic helicity tends to increase when the scale of the energy-carrying magnetic structures increases. The magnetic helicity of NOAA 11515 violates the expected hemispheric sign rule, which is interpreted as an effect of enhanced field strengths at scales larger than 30-60Mm with opposite signs of helicity. This is consistent with the general cycle dependence, which shows that around the solar maximum the magnetic energy and helicity spectra are steeper, emphasizing the large-scale field.
• A solar eruption driven by rapid sunspot rotation(1402.6043)

Feb. 25, 2014 astro-ph.SR
We present the observation of a major solar eruption that is associated with fast sunspot rotation. The event includes a sigmoidal filament eruption, a coronal mass ejection, and a GOES X2.1 flare from NOAA active region 11283. The filament and some overlying arcades were partially rooted in a sunspot. The sunspot rotated at $\sim$10$^\circ$ per hour rate during a period of 6 hours prior to the eruption. In this period, the filament was found to rise gradually along with the sunspot rotation. Based on the HMI observation, for an area along the polarity inversion line underneath the filament, we found gradual pre-eruption decreases of both the mean strength of the photospheric horizontal field ($B_h$) and the mean inclination angle between the vector magnetic field and the local radial (or vertical) direction. These observations are consistent with the pre-eruption gradual rising of the filament-associated magnetic structure. In addition, according to the Non-Linear Force-Free-Field reconstruction of the coronal magnetic field, a pre-eruption magnetic flux rope structure is found to be in alignment with the filament, and a considerable amount of magnetic energy was transported to the corona during the period of sunspot rotation. Our study provides evidences that in this event sunspot rotation plays an important role in twisting, energizing, and destabilizing the coronal filament-flux rope system, and led to the eruption. We also propose that the pre-event evolution of $B_h$ may be used to discern the driving mechanism of eruptions.
• Magnetic Nonpotentiality in Photospheric Active Regions as a Predictor of Solar Flares(1308.1181)

Aug. 6, 2013 astro-ph.SR
Based on several magnetic nonpotentiality parameters obtained from the vector photospheric active region magnetograms obtained with the Solar Magnetic Field Telescope at the Huairou Solar Observing Station over two solar cycles, a machine learning model has been constructed to predict the occurrence of flares in the corresponding active region within a certain time window. The Support Vector Classifier, a widely used general classifier, is applied to build and test the prediction models. Several classical verification measures are adopted to assess the quality of the predictions. We investigate different flare levels within various time windows, and thus it is possible to estimate the rough classes and erupting times of flares for particular active regions. Several combinations of predictors have been tested in the experiments. The True Skill Statistics are higher than 0.36 in 97% of cases and the Heidke Skill Scores range from 0.23 to 0.48. The predictors derived from longitudinal magnetic fields do perform well, however they are less sensitive in predicting large flares. Employing the nonpotentiality predictors from vector fields improves the performance of predicting large flares of magnitude $\geq$M5.0 and $\geq$X1.0.
• Method of Relative Magnetic Helicity Computation II: Boundary Conditions for the Vector Potentials(1304.3526)

April 12, 2013 astro-ph.SR
We have proposed a method to calculate the relative magnetic helicity in a finite volume as given the magnetic field in the former paper (Yang et al. {\it Solar Physics}, {\bf 283}, 369, 2013). This method requires that the magnetic flux to be balanced on all the side boundaries of the considered volume. In this paper, we propose a scheme to obtain the vector potentials at the boundaries to remove the above restriction. We also used a theoretical model (Low and Lou, {\it Astrophys. J.} {\bf 352}, 343, 1990) to test our scheme.
• Analysis on Correlations between Subsurface Kinetic Helicity and Photospheric Current Helicity in Active Regions(1211.2278)

Nov. 10, 2012 astro-ph.SR
An investigation on correlations between photospheric current helicity and subsur- face kinetic helicity is carried out by analyzing vector magnetograms and subsurface velocities for two rapidly developing active regions. The vector magnetograms are from the SDO/HMI (Solar Dynamics Observatory / Helioseismic and Magnetic Im- ager) observed Stokes parameters, and the subsurface velocity is from time-distance data-analysis pipeline using HMI Dopplergrams. Over a span of several days, the evo- lution of the weighted current helicity shows a tendency similar to that of the weighted subsurface kinetic helicity, attaining a correlation coefficient above 0.60 for both ac- tive regions. Additionally, there seems to be a phase lag between the evolutions of the unweighted current and subsurface kinetic helicities for one of the active regions. The good correlation between these two helicities indicate that there is some intrinsic con- nection between the interior dynamics and photospheric magnetic twistedness inside active regions, which may help to interpret the well-known hemispheric preponder- ance of current-helicity distribution.
• A Statistical Study on Photospheric Magnetic Nonpotentiality of Active Regions and Its Relationship with Flares during Solar Cycles 22-23(1206.2006)

June 10, 2012 astro-ph.SR
A statistical study is carried out on the photospheric magnetic nonpotentiality in solar active regions and its relationship with associated flares. We select 2173 photospheric vector magnetograms from 1106 active regions observed by the Solar Magnetic Field Telescope at Huairou Solar Observing Station, National Astronomical Observatories of China, in the period of 1988-2008, which covers most of the 22nd and 23rd solar cycles. We have computed the mean planar magnetic shear angle (\bar{\Delta\phi}), mean shear angle of the vector magnetic field (\bar{\Delta\psi}), mean absolute vertical current density (\bar{|J_{z}|}), mean absolute current helicity density (\bar{|h_{c}|}), absolute twist parameter (|\alpha_{av}|), mean free magnetic energy density (\bar{\rho_{free}}), effective distance of the longitudinal magnetic field (d_{E}), and modified effective distance (d_{Em}) of each photospheric vector magnetogram. Parameters \bar{|h_{c}|}, \bar{\rho_{free}}, and d_{Em} show higher correlation with the evolution of the solar cycle. The Pearson linear correlation coefficients between these three parameters and the yearly mean sunspot number are all larger than 0.59. Parameters \bar{\Delta\phi}, \bar{\Delta\psi}, \bar{|J_{z}|}, |\alpha_{av}|, and d_{E} show only weak correlations with the solar cycle, though the nonpotentiality and the complexity of active regions are greater in the activity maximum periods than in the minimum periods. All of the eight parameters show positive correlations with the flare productivity of active regions, and the combination of different nonpotentiality parameters may be effective in predicting the flaring probability of active regions.
• Large Scale Soft X-ray Loops And Their Magnetic Chirality In Both Hemispheres(1007.2793)

July 16, 2010 astro-ph.SR
The magnetic chirality in solar atmosphere has been studied based on the soft X-ray and magnetic field observations. It is found that some of large-scale twisted soft X-ray loop systems occur for several months in the solar atmosphere, before the disappearance of the corresponding background large-scale magnetic field. It provides the observational evidence of the helicity of the large-scale magnetic field in the solar atmosphere and the reverse one relative to the helicity rule in both hemispheres with solar cycles. The transfer of the magnetic helicity from the subatmosphere is consistent with the formation of large-scale twisted soft X-ray loops in the both solar hemispheres.
• New dynamo pattern revealed by solar helical magnetic fields(0911.5713)

Nov. 30, 2009 astro-ph.SR
Previously unobservable mirror asymmetry of the solar magnetic field -- a key ingredient of the dynamo mechanism which is believed to drive the 11-year activity cycle -- has now been measured. This was achieved through systematic monitoring of solar active regions carried out for more than 20 years at observatories in Mees, Huairou, and Mitaka. In this paper we report on detailed analysis of vector magnetic field data, obtained at Huairou Solar Observing Station in China. Electric current helicity (the product of current and magnetic field component in the same direction) was estimated from the data and a latitude-time plot of solar helicity during the last two solar cycles has been produced. We find that like sunspots helicity patterns propagate equatorwards but unlike sunspot polarity helicity in each solar hemisphere does not change sign from cycle to cycle - confirming the theory. There are, however, two significant time-latitudinal domains in each cycle when the sign does briefly invert. Our findings shed new light on stellar and planetary dynamos and has yet to be included in the theory.


text:
# Matt Groh

## Coup D'oeil Cravate

### Inspiration

Sometimes what you're looking for is right in front of you. The Coup D'oeil Cravate concept is a tie with LEDs stiched inside, which are programmed to produce a hidden message through a Saccade-based display. This idea springs from the Missing Objects aesthetics of absence and conversations with Joost Bonsen. Here's a video showing a Saccade-based display.

And here's the boss wearing a bolo tie. The big idea is a Saccade-display bolo tie. But, we'll go for the standard tie to start. And, we'll make this project tractable and de-risk the binary nature of electronics components through a spiral development process starting with something small and relatively easy and incrementally increasing the complexity.

### Charlieplexing

Charlieplexing is a technique for driving a multiplexed display with relatively few pins. For the purposes of the Coup D'oeil Cravate How to Make project, Charlieplexing allows us to control lots of LEDs with minimal microcontroller pins. Specifically, $$n$$ pins can drive $$n(n-1)$$ LEDs. I will be using the ATTiny44 microcontroller, which has 14 pins with 9 available for LEDs once the other 5 have been routed to the power and ISP programmer. With 9 available pins on the ATTiny44 , we can drive up to 72 LEDs. As an intermediary goal for the final project, I'll drive 20 LEDs with 5 pins.

### Electronics

#### Step 1: Designing a Double-Sided One Dimensional Charlieplexed Circuit Board

Isaac Newton once wrote, "If I have seen further it is by standing on the shoulders of giants." My design starts with Neil's charlieplexing example from the output devices week.

I rearranged the 2d array of LEDs into a single 1d array. I also added copper traces from the rest of the pins to vias and additional resistors that would enable the next development cycle with additional LEDs. Otherwise, I kept the board design the same. Here's a picture of the bottom of the board.

And here's a picture of the top of the board. The traces on the left would technically be below the previous image, but I ended up not using them because I only used 5 pins.

My goal would be to build a flexible circuit board, but this development cycle I wanted to mount the circuit on an acrylic block to make it more sturdy. The larger rectangle is the backing for the circuit and the rectangle with holes is meant to be the top layer. The acrylic turned out to be too thick for the vias in the workshop, so I ditched the holy rectangle. The .pdf below is the cut file for the acrylic on the laser cutter.

Here's the cut file for the copper on acetate.

And, here's the cut file for the vinyl, which goes on top of the bottom layer to prevent the bottom traces from touching the top traces.

#### Step 2: Laser Cutting and Vinyl Cutting

The key to the laser cutter is focus and air and a little bit of design. Save you design files as a .pdf and open them up on Corel Draw. Then, you'll want to set the Corel Draw program to the dimensions of the laser cutter. You'll need to focus the laser (this is essentially zero-ing the z-axis), and you can start printing. I printed on acrylic, and I chose the following settings: 100 power (that's the max) and 1.6 speed (that's nearly the slowest). Also, make sure to check the box that says air, which will circulate the air and avoid flames. Here's a pic and a video of the laser cutter in prcoess.

The trick to the vinyl cutter is material and sharpness. On the sharpness side, you just want to make sure the blade doesn't have gunk on it. On the material side, it's about your inputs. When I put copper on vinyl, I could never get cuts that didn't mess up the copper traces. When I put copper on acetate, it just worked. The settings that I used were 80 for force and 20 for speed. These same setting work when just cutting vinyl.

#### Step 4: Programming the LED Array

In order to program the LED array, you'll want to connect a programmer like the AVRISP-2 to the ISP and an FTDI header to the ground and VCC pins of the power component. Note: the programmer will fail if the board is not powered.

mkdir code && cd code
make
make program-avrisp2

Then, if it programs correctly, you should see:

avr-objcopy -O ihex hello.array.44.2.out hello.array.44.2.c.hex;\
avr-size --mcu=attiny44 --format=avr hello.array.44.2.out
AVR Memory Usage
----------------
Device: attiny44

Program:     366 bytes (8.9% Full)

Data:          1 bytes (0.4% Full)
(.data + .bss + .noinit)

avrdude -p t44 -P usb -c avrisp2 -U flash:w:hello.array.44.2.c.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9207 (probably t44)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: input file hello.array.44.2.c.hex auto detected as Intel Hex
avrdude: writing flash (366 bytes):

Writing | ################################################## | 100% 0.16s

avrdude: 366 bytes of flash written
avrdude: verifying flash memory against hello.array.44.2.c.hex:
avrdude: load data flash data from input file hello.array.44.2.c.hex:
avrdude: input file hello.array.44.2.c.hex auto detected as Intel Hex
avrdude: input file hello.array.44.2.c.hex contains 366 bytes

Reading | ################################################## | 100% 0.16s

avrdude: verifying ...
avrdude: 366 bytes of flash verified

avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

avrdude done.  Thank you.

### Step 5: Embroidery and Sewing

The final step is sewing a tie together and embroidering the Miss.o logo.

The "Brother" sewing machine has a software design cool called PE Design Center. Tom Lutz wrote an awesome how-to on using the embroidery software, which I followed to produce this .ps file to plug into the "Brother." Then, it's just setting up the sewing machine and having a go.

### The Process

It appears that I boiled this Coupe D'oeil Cravate project down to 5 steps. Admittedly, the design and building process were less linear and more chaotic. One of my favorite artists, Mari Andrew, visualizes this process perfectly.

Of course, you're reading this with my hindsight vision. Trust me. What it looked like while I was building this is the squiggle on the left. Pretty neat how a project can be a microcosm of life!

Here's a small gallery of images showing designs and attempts along the way. Also, we're supposed to say the cost of materials. The only thing I purchases was a black tie for \$10 that I ended up not using.