text:
#### Heavyarms2050

The Practice Exam I was given contains answer, but getting the answer is the hard part.

1. A rotating wheel requires 3.00 s to rotate 37 revolutions. At the end of 3.00 s the angular velocity will be 98.0 rad/s. What is the constant angular acceleration? (1 rev = 2pi rad)

Im using the formula delta(theta) = (omega)(time) + 1/2at^2
delta(theta)= (37*2pi)
1/2at^2= 1/2a(3sec)^2
I plug everything in, but i get -13.7rad/s^2. Am I just lucky I came close to negative answer or did i so something wrong?

2. A meter stick can be balanced at the 49.7-cm mark when balanced on a fulcrum (pivot). When a 50.0-gram mass is attached at the 10.0-cm mark, the fulcrum must be moved to the 39.2-cm mark for balance. What is the mass of the meter stick in grams?

Ans: 139 gm

Yea, I'm clueless

3. Two spheres of equal volume 100 cm3 contain an inert gas at 0°C and 1.00 atm pressure. They are joined by a small tube of negligible volume, allowing the gas to flow between the spheres. What common pressure will exist in the two spheres if one is raised to 100°C while the other is kept at 0° C? Assume an ideal gas.

Ans: 1.16 atm

I try every way possible to manipulate Pv=nRT, but I can't get the answer

4.A 5.00–g bullet moving with an initial speed of 400 m/s is fired horizontally along the positive x-axis, passing completely through a 1.00-kg block, which initially is at rest on a frictionless horizontal surface at x = 0.00 cm. The block is connected to a spring having a force constant of 900 N/m. If the block moves 5.00 cm to the right (x = 5.00 cm) along the positive x-axis after impact, what is the speed of the bullet when it emerges from the block?

Ans:100 m/s

From the formual (KE+PEg+PEs)i = (KE+PEg+PEs)f
I'm got the formula: 1/2mv^2 = 1/2mv^2 + 1/2Kx^2
I don't know what I am doing wrong.

I just solved this

5. A thin spherical shell of mass 0.400 kg and diameter 0.200 m is filled with alcohol (rho = 806 kg/m3). It is released from rest at the bottom of a tank of water (rho = 1000 kg/m3). What is the acceleration of the alcohol spherical shell as it starts to rise to the surface?

Ans:1.06 m/s^2

Yea, another clueless one

Thank you, for whoever helps me on this

Last edited:

#### Bobak

2. A meter stick can be balanced at the 49.7-cm mark when balanced on a fulcrum (pivot). When a 50.0-gram mass is attached at the 10.0-cm mark, the fulcrum must be moved to the 39.2-cm mark for balance. What is the mass of the meter stick in grams?

Ans: 139 gm

Yea, I'm clueless

I will help you with this question for now. Are you familiar with the principle of moments ?

If the meter stick is balanced at the 49.7cm mark, what does that tell you about the position of the centre of mass?

A good clear diagram always helps with a question like this, I have attached one.

first find the distance of the 10g block form the pivot.

39.2cm - 10cm = 29.2cm

and you need to find the distance of the centre of mass of the rules form the pivot.

49.7cm - 39.2cm = 10.5cm

using the principle of moment the anticlockwise moment causes by the mass is equal to the clockwise moment cause my the centre of mass about the pivot.

$$\displaystyle 29.2cm \times 50 g = 10.5cm \times M$$

solve the equation for M, you should get 139 grams.

Bobak

#### Attachments

• 1 KB Views: 8
Last edited:
Heavyarms2050

#### Heavyarms2050

$$\displaystyle 29.2cm \times 10 g = 10.5cm \times M$$

there was typo in your formula, it was suppose to be 50g not 10g. Thx a million though.

This is actually getting urgent now, but can you guys/anybody PLEASE help me on these 4 problems by Monday.

#### Bobak

5. A thin spherical shell of mass 0.400 kg and diameter 0.200 m is filled with alcohol (rho = 806 kg/m3). It is released from rest at the bottom of a tank of water (rho = 1000 kg/m3). What is the acceleration of the alcohol spherical shell as it starts to rise to the surface?

Ans:1.06 m/s^2

Yea, another clueless one

I believe you have to use archimedes principle for this question. Do you know what it is?

I will quote it for you.

When a body is wholly or partly immersed in a fluid it experiences and upward force equal to the weight of the fluid displaced.

Firstly we must calculate the weight of the displaced water which. will be the volume of the sphere multiplied by the density of the water.

$$\displaystyle Upthrust = 1000 Kg /m^3 \times \frac{4}{3} \pi (0.1)^3 m^3 \times 9.81 m/s^2$$

now you must draw a free body force diagram

note the mass of the sphere is $$\displaystyle 806 Kg /m^3 \times \frac{4}{3} \pi (0.1)^3 m^3 + 0.4 Kg$$ this is the mass of the volume of the alcohol plus the mass of the shell

so the net force is $$\displaystyle Upthrust - Weight$$

using Newton's second law

$$\displaystyle Mass \times Acceleration = Upthrust - Weight$$
$$\displaystyle ma= 1000 Kg /m^3 \times \frac{4}{3} \pi (0.1)^3 m^3 \times 9.81 m/s^2 - m \times 9.81 N$$

so $$\displaystyle a= \frac{1000 Kg /m^3 \times \frac{4}{3} \pi (0.1)^3 m^3 \times 9.81 m/s^2}{ 806 Kg /m^3 \times \frac{4}{3} \pi (0.1)^3 m^3 + 0.4 Kg } - 9.81 m/s^2$$

giving $$\displaystyle a= 1.07195 m/s^2$$
or $$\displaystyle a= 1.06 m/s^2$$ quoting to 3 significant figures.

I hope that helps

Bobak

#### Attachments

• 7 KB Views: 19
Last edited:

#### Heavyarms2050

$$\displaystyle a= \frac{1000 Kg /m^3 \times \frac{4}{3} \pi (0.1)^3 m^3 \times 9.81 m/s^2}{ 806 Kg /m^3 \times \frac{4}{3} \pi (0.1)^3 m^3 + 0.4 Kg } - 9.81 m/s^2$$

I'm not getting the answer using the formula you have given me for the 2nd

Last edited:

#### topsquark

Forum Staff
2. A meter stick can be balanced at the 49.7-cm mark when balanced on a fulcrum (pivot). When a 50.0-gram mass is attached at the 10.0-cm mark, the fulcrum must be moved to the 39.2-cm mark for balance. What is the mass of the meter stick in grams?

Ans: 139 gm
You neglected to mention that you are using $$\displaystyle g = 10 m/s^2$$. As most of the world does not use this (unrealistic) assumption you should always mention it when asking for help.

We know that the meter stick is balanced at the 49.7 cm mark, so this is the location of the CM.

I am going to take the sum of the torques about the 39.2 cm mark and call a CCW torque positive.

$$\displaystyle \sum \tau = (0.0500~kg)(0.292~m) - Mg(0.105~m) = 0$$
where M is the mass of the meter stick.

Solve for M.

-Dan


text:
# Fill between /draw curves & lines tikz

First of all I want to thank you if you read my post.

So I use the package tikz of LaTeX I want to fill a specific area. I searched alot and found some solutions with fill between and addplot but for different reasons I want to keep the \draw command.

Here's my code:

\documentclass[10pt,aps,prb,twocolumn, nofootinbib]{revtex4-1}
\usepackage{tikz}
\usetikzlibrary{patterns}
\usepackage{amssymb,amsmath}
\usepackage{subfig}
\usepackage{graphicx}
\usepackage{color}
\usepackage{hyperref}
\usepackage{listings}
\hypersetup{
bookmarks=true,         % show bookmarks bar?
unicode=false,          % non-Latin characters in Acrobat’s bookmarks
pdftoolbar=true,        % show Acrobat’s toolbar?
pdffitwindow=false,     % window fit to page when opened
pdfstartview={FitH},    % fits the width of the page to the window
pdfauthor={Kevin Multani},     % author
citecolor=red,        % color of links to bibliography
}
\graphicspath{{figures/}}
\newcommand{\ut}{\ensuremath{\frac{\partial u}{\partial t}}}
\newcommand{\uxx}{\ensuremath{\frac{\partial^2 u}{\partial x^2}}}
\newcommand{\Qt}{\ensuremath{\frac{dQ}{dt}} }
\newcommand{\fixme}{{\bf **FIXME**}}
\renewcommand{\labelitemi}{$\vcenter{\hbox{\tiny$\bullet$}}$}
\begin{document}
\begin{tikzpicture}[scale=1.2]
%vertical & horizontal axis
\draw[->](0,0) --(6,0) node [right] {$\mu$};
\draw[->](0,0) --(0,4) node [left] {$\gamma(\mu)$};
\coordinate [label={[black] below:0}] (S) at (0,0);
\coordinate [label={[black] below:1}] (S) at (5.6,0);
\coordinate [label={[black] left:1}] (S) at (0,3.7);

% Lines & Curves
\draw [thick, blue](0,0) -- (4,0);
\draw[dashed](5.6,0)--(5.6,4);

\draw [thick, blue] plot [smooth, tension=1] coordinates { (4,0) (5,1) (5.3,3) };
\draw[dashed](0,4)--(5.6,4);
\draw[dashed](5.6,0)--(5.6,4);
\coordinate [label={left:$\gamma=\mu$}] (S) at (5.1,3);

%title
\node[align=center,font=\bfseries, yshift=2em] (title)
at (current bounding box.north)
{Summary of the Signaling Model};
\end{tikzpicture}
\end{document}

Which yields the following result:

I want to fill the area above left the blue curve with some west lines. Unfortunally reading the documentation on clip & fill did not give me a good result (some spaces were missing).

Again thank you if you have any solutions

  \fill[color=brown!20, opacity=0.3]

format: plain


text:
syncopation & accordionlike France, but no dog poopmore quotes

# piet mondrian: beautiful

EMBO Practical Course: Bioinformatics and Genome Analysis, 5–17 June 2017.

# visualization + design

The 2017 Pi Day art imagines the digits of Pi as a star catalogue with constellations of extinct animals and plants. The work is featured in the article Pi in the Sky at the Scientific American SA Visual blog.

# $\pi$ Day 2016 Art Posters

2017 $\pi$ day
2016 $\pi$ approximation day
2016 $\pi$ day
2015 $\pi$ day
2014 $\pi$ approx day
2014 $\pi$ day
2013 $\pi$ day
Circular $\pi$ art

On March 14th celebrate $\pi$ Day. Hug $\pi$—find a way to do it.

For those who favour $\tau=2\pi$ will have to postpone celebrations until July 26th. That's what you get for thinking that $\pi$ is wrong.

If you're not into details, you may opt to party on July 22nd, which is $\pi$ approximation day ($\pi$ ≈ 22/7). It's 20% more accurate that the official $\pi$ day!

Finally, if you believe that $\pi = 3$, you should read why $\pi$ is not equal to 3.

All art posters are available for purchase.
I take custom requests.

This year's $\pi$ day art collection celebrates not only the digit but also one of the fundamental forces in nature: gravity.

In February of 2016, for the first time, gravitational waves were detected at the Laser Interferometer Gravitational-Wave Observatory (LIGO).

The signal in the detector was sonified—a process by which any data can be encoded into sound to provide hints at patterns and structure that we might otherwise miss—and we finally heard what two black holes sound like. A buzz and chirp.

The art is featured in the Gravity of Pi article on the Scientific American SA Visual blog.

## this year's theme music

All the art was processed while listening to Roses by Coeur de Pirate, a brilliant female French-Canadian songwriter, who sounds like a mix of Patricia Kaas and Lhasa. The lyrics Oublie-moi (Forget me) are fitting with this year's theme of gravity.

Mais laisse-moi tomber, laisse-nous tomber
Laisse la nuit trembler en moi
Laisse-moi tomber, laisse nous tomber
Cette fois

But let me fall, let us fall
Let the night tremble in me
Let me fall, let us fall
This time

## The Einstein-$\pi$ connection

The number $\pi$ appears in the fundamental equation of general relativity, which relates gravity (left side) to energy and momentum (right side).

$R_{\mu \nu} - \tfrac{1}{2} Rg_{\mu\nu} = 8 \pi G T_{\mu \nu}$

The reason why $\pi$ appears has to do with the need to include the surface area of the sphere, $4 \pi r^2$ in the mathematics. This is very nicely described in Sean Carrol's article Einstein and $\pi$.

## The gravity of $\pi$

Let's make the digits of $\pi$ into masses, throw them into space, and watch gravity make them collide and orbit each other. Read about the details of the simulation and look at the posters.

The first 14 digits of $\pi$ generate various orbits as the digits are assigned mass and subject to gravity. (BUY ARTWORK)

As the number of digits is increased, more elaborate patterns arise. Here is one simulation using 100 digits.

Things can get a little crazy with mor digits. Here, 153 digits are used. (BUY ARTWORK)

How about 1000 digits? In this simulation the masses are similar and they all collide within the circle.

The first 1000 digits of $\pi$ collapse into a single mass. (BUY ARTWORK)
The first 3 digits of $\pi$ collapse into a single mass. 49 times. (BUY ARTWORK)

VIEW ALL

# Tabular Data

Tue 11-04-2017
Tabulating the number of objects in categories of interest dates back to the earliest records of commerce and population censuses.

After 30 columns, this is our first one without a single figure. Sometimes a table is all you need.

In this column, we discuss nominal categorical data, in which data points are assigned to categories in which there is no implied order. We introduce one-way and two-way tables and the $\chi^2$ and Fisher's exact tests.

Altman, N. & Krzywinski, M. (2017) Points of Significance: Tabular data. Nature Methods 14:329–330.

# Happy 2017 $\pi$ Day—Star Charts, Creatures Once Living and a Poem

Tue 14-03-2017

on a brim of echo,

capsized chamber
drawn into our constellation, and cooling.
—Paolo Marcazzan

Celebrate $\pi$ Day (March 14th) with star chart of the digits. The charts draw 40,000 stars generated from the first 12 million digits.

12,000,000 digits of $\pi$ interpreted as a star catalogue. (details)

The 80 constellations are extinct animals and plants. Here you'll find old friends and new stories. Read about how Desmodus is always trying to escape or how Megalodon terrorizes the poor Tecopa! Most constellations have a story.

Find friends and stories among the 80 constellations of extinct animals and plants. Oh look, a Dodo guardings his eggs! (details)

This year I collaborate with Paolo Marcazzan, a Canadian poet, who contributes a poem, Of Black Body, about space and things we might find and lose there.

Check out art from previous years: 2013 $\pi$ Day and 2014 $\pi$ Day, 2015 $\pi$ Day and and 2016 $\pi$ Day.

# Data in New Dimensions: convergence of art, genomics and bioinformatics

Tue 07-03-2017

Art is science in love.
— E.F. Weisslitz

A behind-the-scenes look at the making of our stereoscopic images which were at display at the AGBT 2017 Conference in February. The art is a creative collaboration with Becton Dickinson and The Linus Group.

Its creation began with the concept of differences and my writeup of the creative and design process focuses on storytelling and how concept of differences is incorporated into the art.

Oh, and this might be a good time to pick up some red-blue 3D glasses.

A stereoscopic image and its interpretive panel of single-cell transcriptomes of blood cells: diseased versus healthy control.

# Interpreting P values

Thu 02-03-2017
A P value measures a sample’s compatibility with a hypothesis, not the truth of the hypothesis.

This month we continue our discussion about $P$ values and focus on the fact that $P$ value is a probability statement about the observed sample in the context of a hypothesis, not about the hypothesis being tested.

Nature Methods Points of Significance column: Interpreting P values. (read)

Given that we are always interested in making inferences about hypotheses, we discuss how $P$ values can be used to do this by way of the Benjamin-Berger bound, $\bar{B}$ on the Bayes factor, $B$.

Heuristics such as these are valuable in helping to interpret $P$ values, though we stress that $P$ values vary from sample to sample and hence many sources of evidence need to be examined before drawing scientific conclusions.

Altman, N. & Krzywinski, M. (2017) Points of Significance: Interpreting P values. Nature Methods 14:213–214.

Krzywinski, M. & Altman, N. (2017) Points of significance: P values and the search for significance. Nature Methods 14:3–4.

Krzywinski, M. & Altman, N. (2013) Points of significance: Significance, P values and t–tests. Nature Methods 10:1041–1042.

# Snellen Charts—Typography to Really Look at

Sat 18-02-2017

Another collection of typographical posters. These ones really ask you to look.

Snellen charts designed using physical constants, Braille and elemental abundances in the universe and human body.

The charts show a variety of interesting symbols and operators found in science and math. The design is in the style of a Snellen chart and typset with the Rockwell font.

# Essentials of Data Visualization—8-part video series

Fri 17-02-2017

In collaboration with the Phil Poronnik and Kim Bell-Anderson at the University of Sydney, I'm delighted to share with you our 8-part video series project about thinking about drawing data and communicating science.

Essentials of Data Visualization: Thinking about drawing data and communicating science.

We've created 8 videos, each focusing on a different essential idea in data visualization: encoding, shapes, color, uncertainty, design, drawing missing or unobserved data, labels and process.

The videos were designed as teaching materials. Each video comes with a slide deck and exercises.


text:
## Interesting paper! Code is coming soon: http://spcl.inf.ethz.ch/Research/Performance/LogGraph/ The method can reduce the size needed to store the input graph by 35% compared to the adjacency array format, while not making computations slower. Several compression frameworks are suggested in the paper. All of them use fixed length compression codes contrarily the WebGraph framework. One of the compression frameworks leads to a space of $\sum_{v\in V} \log(\widehat{N_v})\cdot d_v+\log(\log(\widehat{N_v}))$ bits (cf. section 3.2, $\widehat{N_v}$ is the maximum ID of the neighbors of node $v$) as it uses $\log(\widehat{N_v})$ bits to store the $d_v$ neighbors of each node $v$ and $\log(\log(\widehat{N_v}))$ bits to store the length of the codes used for each node $v$. Note that an additional cost is needed in order to have a direct access to the neighbors of each node (this is done using succinct bit vectors (it seems to lead to a total number of bits close to $n\cdot \log(m)$)). The nodes can be renumbered such that the number of bits is minimized. ### Approaches the compression ratio of WebGraph I read that the suggested compression method "approaches the compression ratio of the established WebGraph compression library". What does it mean exactly? The Webgraph compression library can compress web graphs using less than 2 bits per link. The suggested compression framework seems to be far from that compression ratio. So I think that what is meant is that on graphs other than web graphs the suggested method approaches the compression ratio of the Webgraph library. Am I correct? ### Java VS C++ I read "We use the WebGraph original tuned Java implementation for gathering the data on compression ratios but, as Log(Graph) is developed in C++, we use a proof-of-a-concept C++ implementation of WG schemes for a fair C++ based performance analysis.". I do not understand. This is because the original Java implementation is slower than a C++ implementation? Which C++ implementation was used for WG? ### Cost function in section 3.6 The quantity to minimize should be $\sum_{v\in V} \log(\widehat{N_v})\cdot d_v$ (cf. section 3.2, $\widehat{N_v}$ is the maximum ID of the neighbors of node $v$), that is intuitively minimizing $\widehat{N_v}$ for nodes with high $d_v$. It is not clear to me why this other counter-intuitive objective is used: $\sum_{v\in V} \widehat{N_v}\cdot \frac{1}{d_v}$. ### Webgraph decompression impacts running time I agree that referencing nodes can impact the running time (especially if there are chains of references). However, it is possible to use the WebGraph framework without using referencing, that is only using gap encoding with variable length instantaneous codes. I think that doing that does not impact significantly the running time, does it? ### Typos and minors - Section 4.2.: "There are exactly $Q$ bit vectors of length with n ones and the storage lower bound is $Q$ bits." -> the storage lower bound is $\log(Q)$ bits.
##Great paper! The method uses random projections of the column vector of the matrix $S=(\alpha_0 I+\alpha_1 A+\alpha_2 A^2+...+\alpha_q A^q)$. It is shown that such a random projection is a heuristics to minimize a relevant cost function (equation (2)) with some guarantees (Theorem 1). As only the products of vectors $R$ with this matrix is needed, explicitly forming the (potentially dense) matrix $S$ is avoided: only the vectors $A^p\cdot R$ are computed. The running time is $O(n\cdot d^2+ m\cdot q\cdot d)$ ($m$ number of edges, $n$ number of nodes, $d$ dimensions of embedding and $q$ order of the embedding). The operations involved are very simple leading to a very fast practical algorithm. It is shown in the experiments that these simple ideas lead to the most scalable embedding method and that the method is still accurate for some machine learning tasks such as classification, link prediction, and network reconstruction. The executable in MATLAB is publicly available here: https://github.com/ZW-ZHANG/RandNE An alternative open source implementation in C is available here: https://github.com/maxdan94/RandNE ### Concerns regarding Theorem 3 "Theorem 3. The time complexity of Algorithm 3 is linear with respect to the number of changed nodes and the number of changed edges respectively." In the proof, the running time proven is in $O(M'\cdot R(q))$ (where $M'$ is the number of new or disappeared edges), the "$R(q)$" is the $q$-step neighborhood of an edge. We can have $R(q)=O(N)$ for some graphs especially in real-world graphs where the average distance between two nodes is very small (say less than 4) https://research.fb.com/three-and-a-half-degrees-of-separation/. The theorem is thus not correct without stating further assumptions. In addition, in the experiments, the running time of the suggested algorithm for dynamic graphs (Algorithm 3) is not compared to the static algorithm (Algorithm 1) re-run from scratch after each update. It is not clear to me if the gain in time is significant. ### I do not understand 5, C, 1 "Network Reconstruction: The experimental setting is similar to moderate-scale networks (Section V-B2), i.e. we rank pairs of nodes according to their inner product similarities and reconstruct the network. We report the AUC scores in Table V." There are approximately $\approx 10^{16}$ such pairs of nodes. This number of pairs of nodes is too large, I do not understand how the pairs can be ranked and the AUC computed. ### Parametters tuning The method needs many parameters: $d$, $q$, $a_0$, $a_1$, ..., $a_q$. Whyle $d$ and $q$ can be arbitrary fixed to say $d=128$ and $q=3$ (as done in the paper). It is not clear what default values would fit for the $a_k$'s. In the paper, the $a_k$'s are found using grid search. Note that the range of values and the steps are not specified in addition the optimal values are not given. This hurts reproducibility. What if grid search is not possible (e.g. no train set)? Which default value would make sense? ### Grid search and unfair comparison In the experiments, the suggested embedding is shown to lead to better results for some tasks (such as network reconstruction, classification and link prediction) compared to other embedding methods. However, the suggested method has parameters ($a_0$, $a_1$, $a_2$ and $a_3$ since $q$ is set to $3$). These parameters are tuned using grid search, while some of the parameters of the other methods seem to be kept to default. This may not be a very fair comparison. ### Real billion-scale networks? I read "We also report the exact running time in Table VII. It shows that RandNE can learn all the node embeddings of WeChat within 7 hours with 16 normal servers, which is promising for real billion-scale networks." I do not understand what is meant. WeChat has 250M nodes and 4.8G edges. The number of edges is thus in the order of billions. "Real billion-scale networks" means more than 1G nodes and not edges? Another graph with 1G edges is available here: http://snap.stanford.edu/data/com-Friendster.html In addition, contrary to WeChat, nodes have some labels that could be used to test the relevance of the embedding. Graphs with billion nodes are available here: http://law.di.unimi.it/datasets.php Unfortunately, they are directed... Another one is here: https://sparse.tamu.edu/Sybrandt/MOLIERE_2016 undirected, but weighted. A twitter graph with 25G edges can be obtained upon request: https://hal.inria.fr/hal-00948889/en/ ###Typos and minors: - "as an theoretical guarantee" - "an one-vs-all logistic regression" - This relevant WWW2018 paper is not cited and the associated method is not used for comparisons: https://papers-gamma.link/paper/48


text:
# Wikipedia: Philosophy!

As many geeks may know most pages (95% i think) on wikipedia eventually lead to Philosophy like this:

Click on the first non-italic or in parentheses link that is to another normal article: (i.e. not File: or Special:, but things like Wikipedia: are OK) and repeat on that one until you hit philosophy.

The script must:

• Take a first page as input
• Print the name of each article it gets to
• And print how many articles it took to get to Philosophy, and if it didn't say so.

You start with 1000 points, and lose one for each character in the code, Bonus points for:

Detecting looping articles and stopping: +50

Detecting looping articles and requesting if the user should go to the next link on the article: +170

Allowing for a default on the former check as a command-line arg or similar: +140

Highest score wins.

• +1, great challenge! This parenthesis detection is hard :P – Doorknob Jan 16 '14 at 22:38
• I get the feeling this could use some better definition, but I'm not sure exactly how so just yet. – Iszi Jan 16 '14 at 22:39
• Lose one point for each character typed. Hmm. Great, I got it, I'll just copy-paste the characters! No points lost! – Justin Jan 16 '14 at 22:52
• Please don't change the rules after answers have already been posted; that's quite rude and generally frowned upon in the community here... – Doorknob Jan 16 '14 at 23:10
• xefer.com/wikipedia – Charlie Jan 17 '14 at 13:29

# Ruby, 1000 - 303299337 - 50373 - 170382 - 170 - 140 379 - 170 - 140 chars = 697701713797928 931

I'm sure there are many improvements to be made.

(This requires Nokogiri)

require'open-uri'
require'nokogiri'
x="/wiki/"+gets.chomp
r=[n=i=0]
until x=~/\/Philosophy/
d=Nokogiri.HTML open"http://en.wikipedia.org#{x}"
x=d.css('p a').select{|a|t=a.xpath('preceding::text()').map(&:text)*'';t.count('(')==t.count(')')&&a.attr('href')=~/^.wiki[^:]+$/}[i].attr'href' i=0 puts r.index(x)?"#{$><<'i=';i=($*[0]||gets).to_i;''}": r.push(x)[-1][6..-1] n+=1 end p n  Example run: c:\a\ruby>wikipedia_crawl_philosophy Latin (note: this is my input) Classical_antiquity History Umbrella_term Terminology Word Linguistics Science Knowledge Fact Proof_(truth) Argument Logic Reasoning Consciousness Quality_(philosophy) Property_(philosophy) Modern_philosophy Philosophy 18  Sample one where I had to go to a different link c:\a\ruby>wikipedia_crawl_philosophy Snow Precipitation_(meteorology) Meteorology Atmospheric_physics Synoptic_scale_meteorology i=2 // I put the 0-indexed number of the link I wanted to go to (so, the third link) Weather Atmosphere Gas State_of_matter#The_four_fundamental_states Physics Natural_science Sciences Knowledge Fact Proof_(truth) Argument Logic Reasoning Consciousness Quality_(philosophy) Property_(philosophy) Modern_philosophy Philosophy 25  Tricks I used: • I used the selector p a to only get non-italic links, because all links in the actual article that are not italics are always in paragraph elements in Wikipedia. • hmmm... maybe i should disallow any but librarys that come with the language... – AlphaModder Jan 16 '14 at 23:07 • @user1825860 It's not actually a library that comes with the language; it's a gem. I edited my answer. But really, you want to take this already hard challenge and force us to not use HTML parsing libraries too? :P – Doorknob Jan 16 '14 at 23:08 • i'm not disallowing it but you lose points :P – AlphaModder Jan 16 '14 at 23:10 • You should reread the first post and edit accordingly :P – AlphaModder Jan 16 '14 at 23:10 • @user1825860 Please don't change the rules after answers have already been posted; that's quite rude... – Doorknob Jan 16 '14 at 23:11 "BASH" – (If not mistaken: 1000 - 397 + 170 + 140 = 913 points) "BASH" – (If not mistaken: 1000 - 386 + 170 + 140 = 924 points) # "BASH" – (If not mistaken: 1000 - 381 + 170 + 140 = 929 points) BASH is in quotes on purpose as this is a mix of tools used in *nix shells but wrapped in a bash script. ## Edit 1: • Removed http:// as curl defaults to this. • Changed href= match on anchors to f= as  does not have any other normal attributes ending in f. (It is a possibility of custom tags. Have not seen any so far.) • Set exit message on not found to !Phil instead of NoPhil. This one is a bit quirky as One could also say e.g. !, 0, N, !P or similar. • Quirk two: -s on curl could be removed to reduce by three more bytes, but that would yield a messy output. Not sure if that is an issue. • Updated help on this page. Using quirks, code would end up at 379 bytes, 931 points. I could also implement @plannapus usage of matching (hopefully) navigation box by adding (p|ul).*?<(\1) adding six bytes (subtracting six points). ## Edit 2: Using ${#c[@]} to print degrees of separation instead of $i counter. Using quirks, code would end up at 374 bytes, 936 points. I summon Cthulhu and go for a regexp + bash/shell/*nix solution. Stolen: Implemented: • Detect loop and ask if next link should be taken. • Optionally select next link on duplicate as option. Requirements: • bash v.? • grep with -P (PCRE) support. • sed • curl • cut Usage: script PATH [OPTIONS] Print separation of article from PATH'' to Philosophy'' on Wikipedia. Degrees of separation, if found, is printed as last line. If not found last line yields !Phil''. PATH Absolute path to starting article, e.g: /wiki/Word OPTIONS y Automatically select next link if already visited. n (Or other) Quit if next link already visited. BUGS 1. On previous visit; "next link" is not checked. Thus if next link has already been visited we get eternal loop. Not sure if this disqualify +170 points. 2. Sure there are.  Inline code. Copy to file. chmod +x filename. Run by ./script /wiki/… from bash shell. u=($1);c=($1);while ! [[ "$u" =~ /Philosophy$]];do echo "$u";u=($(curl -s "en.wikipedia.org$u"|tr '\n' ' '|grep -Po '
.*?
'|sed 's/>[^<]*([^)]*)//g'|grep -o ']*f="/wiki/[^":]*"'|cut -d\" -f2));for x in "${c[@]}";do if [ "$x" = "$u" ];then [$2 ] &&s=$2||read -p "${u[0]}?" s;[ $s = y ] &&u[0]=${u[1]}||{ echo "!Phil";exit;} fi;done;c=("${c[@]}" "$u");done;echo ${#c[@]};  ## Expanded and explained code: u=($1); # Array of paths.
c=($1); # Array of visited paths. # While$u != /Philosophy, ugly trick is to use $u instead of${u[0]}.
while ! [[ "$u" =~ /Philosophy$ ]];do
echo "$u"; # Print current page. # curl : prints retreived page to stdout. "-s" could be skipped. # tr : replace all newline with space. This is a ®sanity thing when it comes to # twidling with html using regex. # grep 1 : match
 tags. Using -P's ungreedy *?. # sed : remove all occurences of "(" something ")". # grep 2 : match links where "href" attribute starts with /wiki/ and is not e.g. File: # cut : match actual href value. # Result is added to array u''. u=($(curl -s "en.wikipedia.org$u" | tr '\n' ' ' | grep -Po '
.*?
' | sed 's/>[^<]*([^)]*)//g' | grep -o ']*f="/wiki/[^":]*"' | cut -d\" -f2)); # For previously visited pages as x. for x in "${c[@]}"; do
# If x equals to first page ...
if [ "$x" = "$u" ]; then
[ $2 ] && s=$2 || read -p "${u[0]}?" s; # If response is "y" use next link, else exit with status. [$s = y ] && u[0]=${u[1]} || { echo "!Phil"; exit; } fi; done; # Append current link to "visited" c=("${c[@]}" "$u"); done; # Print number of visited pages. echo${#c[@]}

• Darn it, you beat me by one point! :P I'm going to have to golf my solution more – Doorknob Jan 17 '14 at 21:47
• Ye ;), but not sure this is valid code. Using tools this way. – Runium Jan 18 '14 at 13:48

## JavaScript 726 (444 chars [556] + 170)

Now I appreciate that this might not be valid as a bookmarklet, but I've enjoyed tinkering with it anyway.

Usage: Navigate to the page you'd like to start from and run the following in the console:

(function(a){c=0,o="";$(u="html")[u](f=$('').on("load",function(){$=f.contentWindow.$;p=f.contentDocument.title[s="split"](" - ")[0];c++;p=="Philosophy"?document.write("
"+o+p+"\n"+c):(i=RegExp("^"+p+"$","m").test(o)?a||confirm("Loop, try next?")?2:0:1)&&(f.src=$("p>a").filter(function(){return(t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]("(").length==t[s](")").length})[--i].href);o+=p+"\n"})[0])})(true)  For JavaScript the output is the following: JavaScript Interpreter (computing) Computer science Science Knowledge Fact Proof (truth) Argument Logic Reason Consciousness Quality (philosophy) Property (philosophy) Modern philosophy Philosophy 15  This solution will assume you want to jump to the next link on a loop being detected, but if you change the true at the end to false it'll pop up a confirmation box instead (quite annoying...) not sure if that qualifies for the secondary bonus or not. I'll assume not. Indented: (function(l){ c=0,o='';$(u='html')[u](f=$('').on('load',function(){ // Firefox needs the ? to properly load the frame$=f.contentWindow.$; // reference repeated calls as strings to save more bytes p=f.contentDocument.title[s='split'](' - ')[0]; // get the title c++; p=='Philosophy'? document.write('
'+o+p+'\n'+c): // pre for nice formatting (i=RegExp('^'+p+'$','m').test(o)?
l||confirm('Loop, try next?')?
2: // desired index + 1 so we can use as a boolean
0
:
1)&&
(f.src=$('p>a').filter(function(){ return (t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]('(').length == t[s](')').length // shorter, but still not overly happy with this...
})[--i].href);
o+=p+'\n' // update output
})[0])
})(true) // change this to show confirm box when loop detected

So I originally missed the part about ignoring items in parens, adding that made it a lot more wordy, so I'm hoping to golf that filter function down (or hopefully replace it entirely).

Working in both Chrome and Firefox (tested in Firefox 26)

• Looks awesome, but fails in Firefox 20. – boothby Jan 17 '14 at 18:38
• Argghh! I only tested Chrome. I'll look into it! – Dom Hastings Jan 17 '14 at 19:12
• @boothby Should be working in Firefox now... Still want to work on the links I'm choosing though! – Dom Hastings Jan 17 '14 at 20:40

# C# - 813 chars

Score: 1000-813+50+170+140 = 547 :(

No external libraries. Loop detection.

First argument is the Source Article, second is the Target Article.

Golfed version:

class Program
{
static void Main(string[] a)
{
Func<XmlDocument,IList<string>> G=delegate(XmlDocument xd){return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n=>n.Attributes["href"].InnerText).ToList();};Action<string> W=delegate(string s){Console.WriteLine(s);};var h=new HashSet<string>();var c=new WebClient();var x=new XmlDocument();var t=c.DownloadString(@"http://wikipedia.org/wiki/"+a[0]);int i=0,C=0;
GO:
COL:
END:
W("Found in "+C);
}
}

Intelligible version:

class Program
{
// arg[0] source article. arg[1] target article
static void Main(string[] arg)
{
Func<XmlDocument, IList<string>> G = delegate(XmlDocument xd)
{
return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n => n.Attributes["href"].InnerText).ToList();
};
Action<string> W = delegate(string s) { Console.WriteLine(s); };
var h = new HashSet<string>(); var c = new WebClient(); var x = new XmlDocument();
int i = 0; int C = 0;
GO:
var ns = G(x);
COL:
var f = ns[i];
if (f.Equals("/wiki/" + arg[1], StringComparison.OrdinalIgnoreCase))
{
goto END;
}
if (h.Contains(f))
{
W("loop: " + f); i++; goto COL;
}
else
{
}
W(f);
goto GO;
END:
W("Found in " + C);
}
}

Example run, from "Sky" to "Philosophy":

C:\>wiki.exe Sky Philosophy

/wiki/Earth
/wiki/Geometric_albedo
/wiki/Phase_angle_(astronomy)
/wiki/Observational_astronomy
/wiki/Astronomy
/wiki/Natural_science
/wiki/Sciences
/wiki/Latin_language
/wiki/Classical_antiquity
/wiki/History
/wiki/Ancient_Greek
/wiki/Greek_language
/wiki/Modern_Greek
loop: /wiki/Greek_language
/wiki/Colloquialism
/wiki/Word
/wiki/Linguistics
/wiki/Science
loop: /wiki/Latin_language
/wiki/Knowledge
/wiki/Fact
/wiki/Latin
loop: /wiki/Classical_antiquity
/wiki/Italic_languages
/wiki/Indo-European_languages
/wiki/Language_family
/wiki/Language
/wiki/Human
/wiki/Extinct
/wiki/Biology
loop: /wiki/Natural_science
/wiki/Life
loop: /wiki/Earth
/wiki/Physical_body
/wiki/Physics
loop: /wiki/Greek_language
loop: /wiki/Natural_science
/wiki/Matter
/wiki/Rest_mass
/wiki/Center_of_momentum_frame
loop: /wiki/Physics
/wiki/Inertial_frame
loop: /wiki/Physics
/wiki/Frame_of_reference
loop: /wiki/Physics
/wiki/Coordinate_system
/wiki/Geometry
loop: /wiki/Ancient_Greek
/wiki/Mathematics
/wiki/Quantity
/wiki/Property_(philosophy)
/wiki/Modern_philosophy
Found in 41

C:\>

# Scala (294 chars => 1000-294+140 = 846 points)

The updated solution which automatically takes the next link if one has already been consumed. Thanks for the 140 bonus points.

Logic: Pick up the first "/wiki" link that doesn't have a ":" in it (so it ignores "File:" links). Rinse and repeat with recursion returning the count + 1 every time. I keep a list of all previous outputs handy so the program doesn't go into an infinite loop.

Regular Expression: I have 2 forms of the regular expression.

• "
.*?\"/wiki/([^:]*?)\".*?/p>" which finds links within the
 tags
• "p>.*?/wiki/([^:]*?)\"" which is a slightly more experimental tag that has proven to work but provide different results because it, at times, picks up links from the right side info bar. These are regular articles so I believe it is still valid. If it's adjudged to not be, the OP (or someone else) can leave me a comment and I can update my solution to a better reg-ex.

I'm going to be using the second regular expression until I find a test case where it doesn't work or the OP mentions picking up links from the side bar aren't allowed (in my opinion, the info bars are still part of the actual article itself; more of a summary).

Minified Source:

object W extends App{print(x(Seq(args(0))));def x(s:Seq[Any]):Int={val? =s.last;println(?);?match{case "Philosophy"=>1;case _=>x(s:+"p>.*?/wiki/([^:]*?)\".*?/p>".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/"+ ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next)+1}}}

object W extends App {
print(x(Seq(args(0))))

def x(s: Seq[Any]): Int = {
val ? = s.last
println(?)
? match {
case "Philosophy" => 1
case _ => x(s :+ "p>.*?/wiki/([^:]*?)\"".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/" + ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next) + 1
}
}
}

Sample Output:

Input

Space_toilet

Output

Space_toilet
Weightlessness
G-force
Weight
Force
SI_unit
French_language
Second_language
Language_acquisition
Word
Linguistics
Science
Latin_language
Pope_Benedict_XVI
Pope_Benedict_(disambiguation)
Regnal_name#Catholic_Church
Monarch
State_(polity)
Community
Commutative_property
Mathematics
Quantity
Property_(philosophy)
Modern_philosophy
Philosophy
26

• Scala doesn't require a main object or method. You can run it with the interpreter as "scala <filename> [args..]". Use args(0) to get the first argument, get rid of your object and main definitions, and I think you can remove the :Int too. pastebin.com/YqywKcG8 – KChaloux Jan 17 '14 at 20:11
• Turns out you can't remove the : Int. Didn't realize you were doing a recursive call. Also my pastebin was taken from your old Readable Source, but the same concepts apply. – KChaloux Jan 17 '14 at 20:13
• I'll try out getting rid of the main method. And yeah, recursive calls made me add the :Int there. Later today, I'll also add a readable form of the 333 char solution I have. Thanks for the suggestions @KChaloux – javatarz Jan 18 '14 at 5:45
• Like I said, the reference to object Q extends App { ... } is totally unnecessary if you run the code with the interpreter rather than compiling with scalac. Just run with scala <filename> [args..] – KChaloux Jan 21 '14 at 13:44

### R, 379 characters; 1000-379+170=791 points

Version that ask users how to proceed when looping detected

library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),[,'href'),v=T),"/"),[,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)

library(XML) #Uses package XML
w="http://en.wikipedia.org"
W="/wiki/"
n=1
A=c(scan(,"")) #Stdin + makes it a vector so we can store each iteration
while(A[n]!="Philosophy"){
a=paste0(w,W,A[n])
d=sapply(strsplit(grep(W,sapply( #The heart of the program
[,'href'),v=T),"/"),[,3)
B=d[-grep(":",d)] #get rid of Templates, Files ,etc...
n=n+1
#Ask user if should proceed when loop encountered
#(any answer other than "n" is considered agreement):
cat(A[n],"\n")
}
cat(n-1)

Example run:

> library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste(w,W,A[n],sep="");d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),[,'href'),v=T),"/"),[,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)
1: Extended_ASCII
2:
Eight-bit
Computer_architecture
Computer_science
Science
Logic
List_of_aestheticians
Art
Human_behavior
Behavior
Organism
Biology
Mathematics
Quantity
Property_(philosophy)
Modern_philosophy
Philosophy
16

### R, 325 characters; ??? points

Version that, by default takes first non-redundant link (i. e. non-looping).

library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),[,'href'),v=T),"/"),[,3);B=d[-grep(":",d)];n=n+1;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)


text:
Share

# Abcd is a Parallelogram and Apq is a Straight Line Meeting Bc at P and Dc Produced at Q. Prove that the Rectangle Obtained by Bp and Dq is Equal to the Ab and Bc. - Mathematics

Course

#### Question

ABCD is a parallelogram and APQ is a straight line meeting BC at P and DC produced at Q. Prove that the rectangle obtained by BP and DQ is equal to the AB and BC.

#### Solution

Given: ABCD is a parallelogram

To prove: BP × DQ = AB × BC

Proof: In ΔABP and ΔQDA

∠B = ∠D                             [Opposite angles of parallelogram]

∠BAP = ∠AQD                     [Alternate interior angles]

Then, ΔABP ~ ΔQDA              [By AA similarity]

therefore"AB"/"QD"="BP"/"DA"                [Corresponding parts of similar Δ are proportional]

But, DA = BC                     [Opposite sides of parallelogram]

Then, therefore"AB"/"QD"="BP"/"BC"

⇒ AB × BC = QD × BP

Is there an error in this question or solution?

#### APPEARS IN

RD Sharma Solution for Class 10 Maths (2018 (Latest))
Chapter 7: Triangles
Ex. 7.5 | Q: 17 | Page no. 75
RD Sharma Solution for Class 10 Maths (2018 (Latest))
Chapter 7: Triangles
Ex. 7.5 | Q: 17 | Page no. 75

#### Video TutorialsVIEW ALL [3]

Solution Abcd is a Parallelogram and Apq is a Straight Line Meeting Bc at P and Dc Produced at Q. Prove that the Rectangle Obtained by Bp and Dq is Equal to the Ab and Bc. Concept: Criteria for Similarity of Triangles.
S


text:
NOAO >   Observing Info >   Approved Programs >   2004A-0466

# Proposal Information for 2004A-0466

PI: Jaehyon Rhee, Caltech, rhee@caltech.edu
Address: Space Astrophysics Laboratory, 1200 E. California Blvd., MC 405-47, Pasadena, CA 91125

CoI: Inese Ivans, Caltech
CoI: Andrew McWilliam, OCIW

Title: Chemical Compositions of Newly Discovered Extremely Metal-Poor Giants from the HK-II Survey

Abstract: We propose to initiate a \it new high-resolution spectroscopy program for extremely metal-poor (EMP) giant stars with [Fe/H] \le - 2.5 in the halo and thick disk of the Galaxy. Thanks to previous medium-resolution spectroscopy using NOAO observing facilities, the HK- II survey has been able to newly discover some 100 [Fe/H] \le -2.5 giants with 11 \le B \le 16, over 7000 deg^2 (one-sixth of the entire sky). Comprehensive chemical abundance analyses for the stars placed at various directions and distances will allow us to understand early history of the Galactic chemical evolution and place a strong constraint on lower limits on the age of the Universe by age dating of individual r-process enhanced EMP giant stars. The results from this effort will enable us to have refined'' metallicity distribution function of [Fe/H] \le -2.5 populations and, combined with proper motions from astrometric surveys (e.g., UCAC2), will provide full space motions of the extremely old stars to uncover the dynamical history of the early Galaxy.

National Optical Astronomy Observatory, 950 North Cherry Avenue, P.O. Box 26732, Tucson, Arizona 85726, Phone: (520) 318-8000, Fax: (520) 318-8360

 NOAO >   Observing Info >   Approved Programs >   2004A-0466


text:
Conjugate variables

1. Dec 11, 2008

spidey

Why there is an uncertainty relation between conjugate variables?
what exactly are conjugate variables?

2. Dec 11, 2008

malawi_glenn

http://en.wikipedia.org/wiki/Canonical_conjugate

The uncertainty relation are due to the non-commuting nature of those variables. If you know how to derive HUP for x and p, it is straight forward to do it for several other pairs of conjugate variables/operators.

3. Dec 11, 2008

Avodyne

Given a lagrangian $L(q,\dot q)$, the conjugate momentum to $q$ is $p=\partial L/\partial\dot q$. There is an uncertainty relation between canonically conjugate variables because that's what quantum mechanics says, and quantum mechanics has been verified by tens of thousands of experiments (at least) to date.


text:
Annotation¶

CalcDegreeStats¶

Performs a TCR neighborhood enrichment test (TCRNET), testing each sample for clonotypes that have more neighbours (higher degree in a graph), i.e. clonotypes with similar CDR3 amino acid sequences, than would be expected by chance according to some control dataset. User can specify the actual search scope (i.e. number of allowed CDR3 mismatches), whether to only compare clonotypes with same V/J, and the control sample. If control sample is not provided, a pooling (see PoolSamples) of all provided samples is used. Note that this test, if supplied with real samples and a control pooled using -i strict option will account for the number of neighbours with the same CDR3 amino acid sequence, but distinct nucleotide sequences. If this is not desired, all input samples and control should be pre-pooled with -i aa or -i aaVJ to collapse variants coding for the amino acid CDR3 sequence.

Note

Running this routine will not return the actual clonotype graph for you, just annotate input samples. To build the graph, one should refer to VDJmatch software and its Cluster routine. Make sure the search scope option is the same as -o used for CalcDegreeStats and that all scoring/filtering is turned off. Next, one should retain only the edges that connect pairs of enriched clonotypes and enriched clonotypes with their neighbours.

$VDJTOOLS CalcDegreeStats \ [options] [sample1.txt sample2.txt ... if -m is not specified] output_prefix  Parameters: Shorthand Long name Argument Description -m --metadata path Path to metadata file. See Common parameters -b --background path Path to the background (control) sample, used to compute expected statistics/P-values. If not provided, will pool input samples and uses them as control. -o --search-scope s,i,d Search scope: number of substitutions (s), indels (id) and total number of mismatches (t) allowed. Default is 1,0,1 -g --grouping string Primary grouping type, limits set of clonotype comparisons: ‘dummy’ (no grouping, default), ‘vj’ (same V and J) or ‘vjl’ (same V, J and CDR3 length). -g2 --grouping2 string Secondary grouping, used for computing statistics, accepts same values as -g. By default will select ‘vjl’ if no indels allowed and ‘vj’ otherwise. -h --help Display help message Note There are two possible schemes for running the algorithm. Firstly, one can select, say a search scope of 1,0,1 allowing no indels, and -g vjl to only allow comparisons between clonotypes that match in V, J and CDR3 length. Then, one should only consider p.value.g in the output and disregard all columns with g2/group2. On the other hand, if one wants to allow comparison of clonotypes with different V/J, and/or comparisons with indels, the option -g dummy should be used. If one thinks there might be certain biases in V/J frequencies between control/background sample and input samples, and one wants to control for them, he should select -g2 vj, then observed degree values will be provided as is (i.e. not limiting clonotype comparisons to a fixed V/J), but the expected degree will be corrected to account for V/J usage difference between input sample and control. One should only consider p.value.g2 in this case. See below for more explaination on output columns. Tabular output¶ Processed samples will have additional annotation columns appended to VDJtools clonotype table columns. These columns are the following: Column Description degree.s Degree (number of neighbours) of a given clonotype in sample. The degree is the number of unique clonotypes (incl. nucleotide variants) that match a given clonotype under specified search scope. group.count.s Number of unique clonotypes that match the group, defined by primary grouping (-g), of a given clonotype in sample, say have the same V and J. group2.count.s Same as above, but the group is defined by secondary grouping -g2. degree.c Degree (number of neighbours) of a given clonotype in the control sample. group.count.c Number of unique clonotypes in the control sample that match the group of given clonotype as defined by primary grouping (-g). group2.count.c Same as above, but the group is defined by secondary grouping -g2. p.value.g P-value for the neighbour (degree) enrichment of a given clonotype according to primary grouping. The P-value is computed as Pbinom(n=degree.s|p=degree.c/group.count.c, N=group.count.s). p.value.g2 P-value for the neighbour (degree) enrichment of a given clonotype according to secondary grouping. The P-value is computed as Ppoisson(n=degree.s|lambda=group.count.s*degree.c/group.count.c). A metadata file will be created for resulting samples with degstat appended to the ..filter.. metadata column. Graphical output¶ none CalcCdrAAProfile¶ Generates amino acid physical properties profile of CDR3. Amino acids are first grouped to corresponding CDR3 sub-regions and then binned by position within the sub-region. Amino acids in a given bin is scored according to its physical properties, sums of those scores and total number of amino acids is reported for each sample/sub-region/bin/property combination. For example under the polarity property amino acids are marked as polar (1) and non-polar (0) and the sum of these values is returned. When divided by the total number of amino acids one will get the fraction of polar amino acids in a given sample/sub-region. For volume the same operation will return the average volume of amino acids. Command line usage¶ $VDJTOOLS CalcCdrAAProfile \
[options] [sample1.txt sample2.txt ... if -m is not specified] output_prefix

Parameters:

Shorthand Long name Argument Description
-m --metadata path Path to metadata file. See Common parameters
-w --weighted   If set, will weight amino acid property values by clonotype frequency.
-n --normalize   If set, will normalize amino acid property values by dividing them by corresponding CDR3 sub-region size.
-r --region-list region1,… List of CDR3 sub-regions to count statistics for, default is "CDR3-full,VJ-junc,V-germ,J-germ
-o --property-list property1,… List of amino acid physicochemical properties to use, see below for allowed value. Uses all amino acid properties from list below by default.
-h --help   Display help message

Supported CDR3 sub-regions:

Name Description
CDR3-full Complete CDR3 region
CDR3-center Central 5 amino acids of CDR3
V-germ Germline part of CDR3 region corresponding to Variable segment
D-germ Germline part of CDR3 region corresponding to Diversity segment
J-germ Germline part of CDR3 region corresponding to Joining segment
VD-junc Variable-Diversity segment junction, applicable when D segment is mapped
DJ-junc Diversity-Joining segment junction, applicable when D segment is mapped
VJ-junc Variable-Joining segment junction, including D segment if it is mapped

Supported amino acid physical properties (see full table for raw values):

Name Description Reference
alpha Preference to appear in alpha helices Stryer L et al. Biochemistry, 5th edition. ISBN 978-0716746843
beta Preference to appear in beta sheets Stryer L et al. Biochemistry, 5th edition. ISBN 978-0716746843
turn Preference to appear in turns Stryer L et al. Biochemistry, 5th edition. ISBN 978-0716746843
surface Residues that have unchanged accessibility area when PPI partner is present PMID:22559010
rim Residues that have changed accessibility area, but no atoms with zero accessibility in PPI interfaces PMID:22559010
core Residues that have changed accessibility area and at least one atom with zero accessibility in PPI interfaces PMID:22559010
disorder Intrinsic structural disorder-promoting, order-promoting and neutral amino acids PMID:11381529
charge Charged/non-charged amino acids Wikipedia
pH Amino acid pH level Wikipedia
polarity Polar/non-polar amino acids Wikipedia
hydropathy Amino acid hydropathy Wikipedia
volume Amino acid volume Wikipedia
strength Strongly-interacting amino acids / amino acids depleted by purifying selection in thymus PMID:18946038
mjenergy Mean value of MJ statistical potential for each amino acid, used to derive ‘strength’ PMID:8604144
kf1..kf10 Values of 10 Kidera factors summarizing physicochemical properties of amino acids unpublished

Tabular output¶

A summary table with averaged amino acid property values is generated, suffixed cdr3aa.profile.[wt or unwt based on -u].txt. The table contains the following columns:

Column Description
sample_id Sample unique identifier
Sample metadata columns. See Metadata section
region Current CDR3 sub-region, see above
property Amino acid physical property name, see above
mean Mean property value

none

Annotate¶

This routine will compute a set of properties for each clonotype’s CDR3 sequence and append them to resulting clonotype table. For example, number of added N-nucleotides and the sum of polar amino acids in CDR3. The main difference from CalcCdrAAProfile is that the former computes sample-level average while this routine performs calculation on clonotype level.

$VDJTOOLS Annotate \ [options] [sample1.txt sample2.txt ... if -m is not specified] output_prefix  Parameters: Shorthand Long name Argument Description -m --metadata path Path to metadata file. See Common parameters -b --base param1,param2,… Comma-separated list of basic clonotype features to calculate and append to resulting clonotype tables. See below for allowed values. Default: cdr3Length,ndnSize,insertSize -a --aaprop property1,… Comma-separated list of amino acid properties. Amino acid property value sum will be calculated for CDR3 sequence (blank annotations will be generated for non-coding clonotypes). See below for allowed values. Default: hydropathy,charge,polarity,strength,contact -h --help Display help message List of basic annotation properties: Name Description cdr3Length Length of CDR3 region NDNSize Number of nucleotides between last base of V germline and first base of J germline parts of CDR3 insertSize Number of added N-nucleotides VDIns Number of added N-nucleotides in V-D junction or -1 if D segment is undefined DJIns Number of added N-nucleotides in D-J junction or -1 if D segment is undefined See CalcCdrAAProfile for the list of amino acid properties available for annotation. Sum of specified amino acid property values across all amino acids of CDR3 will be computed. It can be divided by cdr3Length / 3 basic property value to get the average. Tabular output¶ Processed samples will have additional annotation columns appended to VDJtools clonotype table columns. Those columns will be prefixed with base. for basic CDR3 properties and aaprop. for CDR3 amino acid composition properties. A metadata file will be created for resulting samples with annot:[-b value]:[-a value] appended to the ..filter.. metadata column. Graphical output¶ none ScanDatabase (DEPRECATED since v1.0.5, use VDJmatch)¶ Annotates a set of samples using immune receptor database based on V-(D)-J junction matching. By default uses VDJdb, which contains CDR3 sequences, Variable and Joining segments of known specificity obtained using literature mining. This routine supports user-provided databases and allows flexible filtering of results based on database fields. The output of ScanDatabase includes both detailed (clonotype-wise) annotation of samples and summary statistics. Only amino-acid CDR3 sequences are used in database querying. Command line usage¶ $VDJTOOLS ScanDatabase \
[options] [sample1.txt sample2.txt ... if -m is not specified] output_prefix

Parameters:

Shorthand Long name Argument Description
-m --metadata path Path to metadata file. See Common parameters
-D --database path Path to an external database file. Will use built-in VDJdb if not specified.
-d --details   Will provide a detailed output for each sample with annotated clonotype matches
-f --fuzzy   Will query database allowing at most 2 substitutions, 1 deletion and 1 insertion but no more than 2 mismatches simultaneously. If not set, only exact matches will be reported
--filter expression Logical pre-filter on database columns. See below
--v-match   V segment must to match
--j-match   J segment must to match
-h --help   Display help message

Note

Database filter is a logical expression that contains reference to input table columns. Database column name references should be surrounded with double underscores (__). Syntax supports Regex and standard Java/Groovy functions such as .contains(), .startsWith(), etc. Here are some examples:

__origin__=~/EBV/
!(__origin__=~/CMV/)

Note that the expression should be quoted: --filter "__origin__=~/HSV/"

Tabular output¶

A summary table suffixed annot.[database name].summary.txt is generated. First header line marked with ##FILTER contains filtering expression that was used. The table contains the following columns:

Column Description
sample_id Sample unique identifier
Sample metadata columns. See Metadata section
diversity Number of clonotypes in sample
match_size Number of matches between sample and database. In case --fuzzy mode is on, all matches will be counted. E.g. if clonotype a in the sample matches clonotypes A and B in the database and clonotype b in the sample matches clonotype B the value in this column will be 3.
sample_diversity_in_matches Number of unique clonotypes in the sample that matched clonotypes from the database
db_diversity_in_matches Number of unique clonotypes in the database that matched clonotypes from the sample
sample_freq_in_matches Overall frequency of unique clonotypes in the sample that matched clonotypes from the database
mean_matched_clone_size Geometric mean of frequency of unique clonotypes in the sample that matched clonotypes from the database

Detailed database query results will be also reported for each sample if -d is specified. Those tables are suffixed annot.[database name].[sample id].txt and contain the following columns.

Column Description
score CDR3 sequence alignment score
query_cdr3aa Query CDR3 amino acid sequence
query_v Query Variable segment
query_j Query Joining segment
subject_cdr3aa Subject CDR3 amino acid sequence
subject_v Subject Variable segment
subject_j Subject Joining segment
v_match true if Variable segments of query and subject clonotypes match
j_match true if Joining segments of query and subject clonotypes match
mismatches Comma-separated list of query->subject mismatches
Database fields corresponding to subject clonotype

none


text:
Homework Help: 3rd-order Energy Correction Derivation

1. Sep 15, 2010

cscott

1. The problem statement, all variables and given/known data

Time-independent, non-degenerate perturbation theory:

- Let |k> represent k-th order wave function correction.
- Let $E^{(k)}$ represent k-th order energy correction
- H' is the perturbed Hamiltonian.

Want the third order energy correction:
$$E^{(3)} = <1|H' - E^{(1)}|1> - 2E^{(2)}<0|1>$$

2. Relevant equations

Equating coefficients of equal powers of the parameter:
$$H_0|3> + H'|2> = E^{(0)}|3> + E^{(1)}|2> + E^{(2)}|1> + E^{(3)}|0>$$

3. The attempt at a solution

Tried multiplying <0| on the left like when deriving the first order correction, $E^{(1)}$.

I get,
$$E^{(3)} = <0|H' - E^{(1)}|2>$$

I don't know what I'm missing to proceed... I'm in the same situation with a few other similar problems. I don't see how multiplying by anything else on the left would make sense either.

Hint on what I'm missing? Thanks

Last edited: Sep 16, 2010
2. Sep 16, 2010

cscott

did I state my question poorly? :\

This is problem 8.1 from B&J's book.

3. Sep 20, 2010

cscott

One last bump... haven't gotten anywhere with this.

4. May 5, 2011

bjorklund

Recently had to solve the same problem, and since noone has commented, I figured I'd leave a hint or two for the next person who comes along.

Hint 1:
The attempted solution in the opening post is the correct way to proceed, except for a term which has been forgotten:
$$E^{(3)}=<0|H'-E^{(1)}\mathbb{I}|2>-E^{(2)}<0|1>$$
(0)
The secret now is to look at the equations of the coefficients for the lower orders
$$H_0|1>+H'|0>=E^{(0)}|1>+E^{(1)}|0>$$
(1)
and
$$H_0|2>+H'|1>=E^{(0)}|2>+E^{(1)}|1>+E^{(2)}|0>.$$
(2)
Using these, the third order energy correction may be expressed in the form
$$E^{(3)}=<1|H'-E^{(1)}\mathbb{I}|1>-2E^{(2)}\textt{Re}<0|1>.$$
(3)

Hint 2:
The "dual equation" to equation (1) may be written as
$$<1|H_0=E^{(0)}<1|+E^{(1)}<0|-<0|H'.$$
(4)

Multiply <1| with equation (2).
Insert (4) in the first term of this and rearrange.
Insert this in (0).


text:
# Calculate hamming weight with low hamming weight

Create a program that computes the hamming weight of a string. Winner is the program with the lowest hamming weight.

Rules:

• Hamming weight for an ASCII character is defined as the total number of bits set to 1 in its binary representation.
• Assume input encoding is 7-bit ASCII, passed through whatever input mechanism is normal for your language (e.g. stdin, args, etc.)
• Output the result, as a number, to stdout or whatever default/normal output mechanism your language uses.
• It should go without saying, but you have to be able to actually run the program, in real life, for it to be a valid solution.
• Winner is the solution whose code has the lowest hamming weight.
• Sorry, no solutions in whitespace for this one! Ok, you can code in whitespace now I've sorted out the rules :)

Per-character examples:

char |  binary  | weight
-----+----------+-------
a    | 01100001 | 3
x    | 01111000 | 4
?    | 00111111 | 6
\x00 | 00000000 | 0
\x7F | 01111111 | 7

• if we take 0x20/ASCII 32 as the reference, isn't the humming weight of hello world 10 rather than 11? – Cristian Lupascu Jun 7 '12 at 13:11
• Why is the weight of hello world 11? Only 10 characters are different from a space. Also - a program's Hamming weight seems to be just its length, excluding spaces. Not so different from normal code golf. – ugoren Jun 7 '12 at 13:12
• Sorry, I totally screwed this up. Wikipedia's hamming weight article is rather misleading, and I totally fubar'ed the rules. Re-writing now. Update: Ok, re-written to define it as the number of bits set to 1 in the ASCII string, sorry for the screw-up. – Polynomial Jun 7 '12 at 13:16
• @ugoren A solution with lower-value ASCII characters has a lower hamming weight. – Polynomial Jun 7 '12 at 13:18
• Now it all makes sense. USE UPPERCASE, BEWARE OF ~ AND o. – ugoren Jun 7 '12 at 13:22

# J (33)

One lower than 34!

+/,#:3 u:

Heavily inspired by this answer, but a hamming weight of one lower.

   +/,#:3 u:'+/,#:3 u:'
33

## J, weight 34

+/,#:a.i.

Usage - place the string to be measured in quotes at the end:

   +/,#:a.i.'+/,#:a.i.'
34

Alternatively, taking input from the keyboard (weight 54):

   +/,#:a.i.1!:1[1
hello
21

• There's only one way to write this :) – ephemient Jun 7 '12 at 14:22
• There isn't... I found a solution that has a hamming weight of one lower. – ɐɔıʇǝɥʇuʎs Jun 23 '14 at 6:33
• Not trying to be a buzzkill, but the rules ask for a program, not a fragment. – FUZxxl Jun 23 '15 at 10:39

## J, 39

+/,#:a.i:]

This is a function taking one argument. (Or replace ] with the string directly; as Gareth notes, that brings the cost down to 34.)

   +/,#:a.i:] 'hello world'
45
+/,#:a.i:] '+/,#:a.i:]'
39

• Great minds think alike. :-) – Gareth Jun 7 '12 at 14:20

## Python, 189

print sum(bin(ord(A)).count("1")for A in raw_input())

• The Python 3 equivalent, print(sum(bin(ord(A)).count('1')for A in input())), has a score of 180. – dan04 Jun 8 '12 at 3:42
• @dan04: Use double quotes instead of single for 176. – Keith Randall Jun 8 '12 at 3:56

## QBasic, 322311286 264

H$=COMMAND$
FOR A=1 TO LEN(H$) B=ASC(MID$(H$,A,1)) WHILE B>0 D=D+B MOD 2 B=B\2 WEND NEXT ?D  Kind of the right tool for the job, still sucks of course. • +1 for using one of my favourite languages of all time. It's the first language I learnt to code in on a PC. – Polynomial Jun 7 '12 at 20:09 ## Unary 0 You all knew it was coming. First the BrainFuck program: ,[[>++[>>+>+<<<-]>>> [<<<+>>>-]>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>> [<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-] [-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>> [-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<< [>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<<< [>>+<[>>+>+<<<-]>>>[<<<+>>>-]>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>> [<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]> [-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<< [>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<<<]>>> [>+>+<<-]>>[<<+>>-][-]+<[>[-]<<[<<->>-]<<[>>+<<-]>>>[-]]>[<<<+<[-]>>>> [-]]<<[->>>>+<<<<]<[-<<+>>]<<],]>>>>>>>.  I added newlines to make it "readable" but it has a Hamming weight of 4066. It works by repeatedly getting the quotient/remainders of an input string and adding up all the remainders. Of course should you run it on itself you get: 226 (4066 % 256) (technically \xe2) so clearly it rules itself the winner. Now we convert it to Unary and get 000 ... 9*google^5.9 0's ... 000  We use a unary implementation with NULL characters \x00 for '0' and boom, hamming weight of 0. Bonus question: For what ASCII characters c can you run this program on a string consisting on N repitions and have it output that character. (E.G. a string of 32 spaces gives a space). What values of N work (either an infinite number of them will work, or none will). • I'm not sure I understand this solution. The brainfuck program has a huge hamming weight. Does Unary accept null bytes as a program, or would you need to re-implement Unary? If it's the latter, it's not really a valid solution - anyone could just say "I define a programming language where any single input byte gives {result}", and win every code golf challenge on the site. – Polynomial Jun 8 '12 at 10:08 • A null character Unary would be fine. All you need is an EOF to say stop counting. In fact here's some pseudo-C to read that file: main(){ bignum Unarynum = 0; int c; while(EOF!=(c=readchar())){ Unarynum++; } return Unarynum; } Doesn't matter at all what you choose to be your Unary char (as long as it isn't EOF). – walpen Jun 8 '12 at 12:02 • Well here's a unary to C compiler that works fine with null characters: ideone.com/MIvAg. Of course the file required to make this program would not fit in the universe, but we have the capacity to run it. – walpen Jun 8 '12 at 12:30 • If you can't actually run it, it's not really a solution. – Polynomial Jun 8 '12 at 12:33 • As Carl Sagan once said: "If you wish to calculate the hamming weight of a string, you must first invent 10^500 universes." (billions and billions, even) – walpen Jun 8 '12 at 23:13 ## C, weight 322263 256 Does the hamming weight of the hamming weight count? main(D,H,A)char*A,**H;{for(A=*++H;*A;A+=!(*A/=2))D+=*A%2;printf("%d",D-2);}  Used mostly standard golfing techniques. A single loop calculates weight (shifting right and adding until zero) and scans the string (advances pointer when zero reached). Assuming D is initialized to 2 (single parameter). Hamming weight specific optimizations: 1. ABDH, with weight 2 each, used for names. 2. *++H preferred over H[1]. • Hah, I utterly failed to understand your first sentence until just now. – breadbox Jun 8 '12 at 3:35 • You can get the score down to 230 by outputting the result as an unary number: main(D,H,A)char*A,**H;{for(A=*++H;*A;A+=!(*A/=2))if(*A%2)printf("@");} – schnaader Jun 9 '12 at 0:29 • @schnaader, I never knew @ was a digit in the unary system. I thought it only uses 0..0. But if you want to go this, way, printf("@"+*a%2) is shorter. – ugoren Jun 10 '12 at 6:19 • @ugoren: Depends on the convention/definition of unary. E.g. en.wikipedia.org/wiki/Unary_numeral_system does use tally marks and says "There is no explicit symbol representing zero in unary as there is in other traditional bases". – schnaader Jun 10 '12 at 9:54 • @schnaader, OK, but I think it's stretching the requirement "as a number" too far. – ugoren Jun 10 '12 at 10:11 ### Golfscript 8472 58 {2base~}%{+}*  (thanks to Howard and Peter Taylor for their help) Input: the input string has to be on the stack (passed as command line argument, or simply placed on the stack). In case you run it from the command line, make sure you use echo -n, otherwise the trailing newline will also be counted. Output: prints the hamming weight value to the console The program can be tested here. • Is Golfscript case-sensitive? If not, you can save a few bits by using BASE instead of base. Update: Just checked, BASE doesn't work. Good solution :) – Polynomial Jun 7 '12 at 13:40 • @Polynomial I tried that after seeing your TEST/test comment :) But it doesn't work. – Cristian Lupascu Jun 7 '12 at 13:43 • You can get rid of {...}2* by applying 2base~ in the first place. Gets score down to 72. – Howard Jun 7 '12 at 14:03 • @Howard thanks for this great tip! I've applied it in my answer. – Cristian Lupascu Jun 7 '12 at 14:14 • Your test mechanism is wrong, because you've forgotten an important limitation of your Web GolfScript page. You should have a ; before the string which you substitute for stdin, so that (; is unnecessary. Then Howard's observation gets it down to 65. – Peter Taylor Jun 7 '12 at 14:18 ## Perl, 80 (22 chars) Done and done: perl -0777nE 'say unpack"%32B*"'  Or here's an alternate version with a weight of 77 (21 chars): perl -0777pE '$_=unpack"%32B*"'

I don't like that version as much, though, because its output omits the final newline.

To calculate the weight, I'm assuming that I'm counting characters in the usual way (excluding the perl -e/-E, but including other option characters). If for some reason people complain about this, then the best I can do without options is 90 (26 chars):

$/=$,,say unpack"%32B*",<>

Sample usage:

$perl -0777nE 'say unpack"%32b*"' rickroll.txt 7071  Boom. # Pyth - 15 Disclaimer: This answer isn't eligible to win since Pyth is younger than this challenge. Uses .B for binary representation and counts the number of "1"'s. /.BQ\1  Takes input in a string to save on z versus Q. ### Scala 231 readLine().map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum  Selftesting code: """readLine().map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum""".map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum  with selftesting modification. • It's weight 495, not 231. You can't get weight 231 with 126 chars - that's an average of less than 2, and all printable chars (except @ and space, which you don't use) have weight 2 at least. – ugoren Jun 7 '12 at 20:27 • @ugoren: But it's only 65 chars. The program is printed nearly twice: Once the code to calculate the hamming weight, and a second time as static input to calculate it for the program. But the calculating part is missing the "readLine()" in front, because it takes the literal input. I tried to clarify the answer itself. – user unknown Jun 7 '12 at 23:15 # Java, weight 931774499 454 I think this is the only answer at the moment with a weight over about 300. class H{public static void main(String[]A){System.out.print(new java.math.BigInteger(A[0].getBytes()).bitCount());}}  Expects input as a command line argument. # GNU sed -r, 467 + 1 (+1 for use of -r - or should that be +4?) Outputs as a unary value per source line; to convert to a decimal total, redirect output into | tr -d "\n" | wc -c. Counts all printable ASCII characters (32-126), plus linefeed (10). s@[a-z]@\U& @g s@[?{}~]@ @g s@[][/7;=>OW|^]@ @g s@[-'+.3569:<GKMNSUVYZ\\]@ @g s@[#%&)*,CEFIJL1248ORTX]@ @g s@$|[!"$(ABDH0P]@ @g y! @!11!  It's hard to avoid listing all characters, but we can reduce this observing that lowercase letters have a Hamming weight of one more than the corresponding uppercase letters. We prefer newline (score 2) over semicolon (score 5) as a statement separator; we prefer @ (score 1) or ! (score 2) over / (score 5) as pattern delimiter. Note - to get the right sets of characters, I created this table from the one in man ascii, sorted by weight. Just add the scores right and below to get the overall weight of each character:  2 4 3 5 6 7 --- ------ - 0: @ 0 P  p |0 1: ! A 1 Q a q | 2: " B 2 R b r |1 4:$ D   4 T d   t |
8: ( H   8 X h   x |

3: # C   3 S c   s |
5: % E   5 U e   u |
6: & F   6 V f   v |2
9: ) I   9 Y i   y |
A: * J   : Z j   z |
C: , L   < \ l   | |

7: ´ G   7 W g   w |
B: + K   ; [ k   { |3
D: - M   = ] m   } |
E: . N   > ^ n   ~ |

F: / O   ? _ o     |4
---  ------   -
1      2     3

This might prove useful to others.

# Julia 262 268

Modified version uses handy 'count_ones' function for a saving of 6 (262)

show(mapreduce(x->count_ones(x),+,map(x->int(x),collect(ARGS[1]))))

Old version using no built in one-counting function (268)

show(mapreduce(x->int(x)-48,+,mapreduce(x->bits(x),*,collect(ARGS[1]))))

Uses command line argument for input.

# CJam 52 or 48

If input is not already on the stack (52)

q:i2fbs:s:i:+

If input is on stack (48)

:i2fbs:s:i:+

For example

"Hello World":i2fbs:s:i:+

# Julia, HW 199

H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))

With

A="H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))"

or by directly inserting the string:

julia> H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect("H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))")))
199

The ungolfed version (HW 411) looks like this:

bitstring=mapreduce(x->bits(x),*,collect(teststring[:]))
mapreduce(checkbit->checkbit=='1',+,bitstring)

And for the fun of it, here is an optimized version (Hamming Weight 231) of bakerg’s take on the problem:

A=mapreduce;show(A(B->int(B)-48,+,A(B->bits(B),*,collect(H[:]))))

with

H="A=mapreduce;show(A(B->int(B)-48,+,A(B->bits(B),*,collect(H[:]))))"

# HPPPL (HP Prime Programming Language), 74

sum(hamdist(ASC(a),0))

The HP Prime graphing calculator has a built-in hamdist() function. The hamming weight of each character is the same as the hamming distance from 0.

ASC(string) creates an array of the ASCII values of each character in a string.

hamdist(value,0) computes the hamming distance from 0 for each ASCII value

sum() sums up all values.

Calculating the hamming weight of its own source code:

# 05AB1E, weight 17 (4 bytes)

ÇbSO

Explanation:

Ç       # Convert the characters in the (implicit) input to their ASCII decimal values
#  i.e. "Test" → [84,101,115,116]
b      # Convert those values to binary
#  i.e. [84,101,115,116] → ["1010100","1100101","1110011","1110100"]
S     # Split it into a list of 0s and 1s (implicitly flattens)
#  i.e. ["1010100","1100101","1110011","1110100"]
#   → [1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,0,1,0,0]
O    # Sum those (and output implicitly)
#  i.e. [1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,0,1,0,0] → 16

# Perl 6, 102

+*.ords>>.base(2).comb(~1)

Try it online!

While this isn't code golf, the shortest solution also seems to have the smallest hamming weight...


text:
### cgy4ever's blog

By cgy4ever, history, 16 months ago, ,

Topcoder SRM 708

•
• +53
•

 » 16 months ago, # |   +12 And all room winners get T-shirts: https://www.topcoder.com/blog/a-flood-of-love-hits-the-topcoder-community/
•  » » 16 months ago, # ^ |   +12 Did anyone receive their shirts for SRM 701?
•  » » 16 months ago, # ^ | ← Rev. 2 →   +3 Even for Div2? Why am I in Div1 :( And I ended up second in the room.. RIP all who came second in room
•  » » 16 months ago, # ^ |   0 I'm lucky :) Do I just have to set my address in the settings? What about T-Shirt size, didn't find any setting?
•  » » » 16 months ago, # ^ |   +3 I don't actually send out the t-shirts, I just follow the news related to them :-) But you definitely have to set your address in your profile.
 » 16 months ago, # |   +6 Contest will start in 36 hours!
 » 16 months ago, # |   +5 Hour
 » 16 months ago, # |   +14 Please, Someone explain his solution for Div 1 250 :)
•  » » 16 months ago, # ^ | ← Rev. 2 →   +33 My idea is to use only 3 characters to support up to 15 strings Like this: a, a ... a, bcbcbc....
•  » » » 16 months ago, # ^ |   0 Nice One. Thank you.
 » 16 months ago, # |   +8 Solution for 500 ?
•  » » 16 months ago, # ^ | ← Rev. 2 →   +5 I used three DPs: dpOut[i][j] means count of palindromes in substring (i .. j), dpOutReal[i][j] means count of palindromes in substring (i .. j) which strictly have ith and jth characters. dpIn[i][j] means count of palindromes in subsequence (0 .. i); (j .. n-1). Then, we choose i for which we want to calculate x[i]. Where can it be in the palindrome. Imagine the palindome: abcdedcba ^ Let the last c will be our ith character. So, the inner part of the palindome will be cdedc (it will have our ith element as one of its ends) and the outer part of the palindrome will be ab baSo, let's iterate all possible inner parts. Let the beginning of inner part will be the x character, and the ending of inner part will be y (it's easy to see that x = i or y = i).Now, for that inner part there will be dpOutReal[x][y] and to choose an outer part for it we will use dpIn[x-1][y+1] + 1 (+1, beacuse we can have no outer part). Now, we'll add to x[i] dpOutReal[x][y] * (dpIn[x-1][y+1] + 1)
 » 16 months ago, # | ← Rev. 5 →   +84 WINNERS: rng_58, tourist, Petr, anta and baklazan. Congratulations guys!div2-med: greedily try to insert strings with as big score as possible (but don't exceed the value of K)div2-hard: dynamic programming in O(n2). Let dp[i][j] (i < j) denote the number of ways to choose subseqeunces of indices on the left from i and from the right from j so that they will be symmetric. At the end answers are dp[i-1][i+1] or something like that.div1-easy: First string can be ABABABAB..., the second CDCDCDCDC..., and each of other strings should consist of one letter only (from 'e' to 'z'). You can check that two first strings produce enough "instability".div1-med: Two dynamic programmings: from inside and from outside. Let dp_out[i][j] denote the number of ways to choose indices on the left from i and right from j so that they will be symmetric, and let dp_in[i][j] denote more standard dp: the number of palindromes in the interval [i, j].div1-hard: It turns out that the probability of getting to the goal amount of money (when playing an optimal strategy) depends on rounded value of . A naive approach to the given problem is O(goal2·k) dynamic programming. The key observation is that values close to each other in one "interval" (interval defined by the same value of probability of winning in optimal strategy) have similar sets of optimal bets. If you divide numbers from 1 to goal into 2k "intervals", for each previous amount of money the set of good (got from optimal bets) new values in one "interval" is a smaller interval itself. A related fact mentioned earlier: the set of optimal moves from a and from a + 1 (where a and a + 1 are from the same interval) differ only by constant number of elements.
•  » » 16 months ago, # ^ | ← Rev. 2 →   0 I think you have a typo in your div2-hard explanation: "left from i and from the left from j" should be from the right of j
•  » » » 15 months ago, # ^ |   0 Yes, thanks.
•  » » 15 months ago, # ^ |   0 Why greedy works in Div2-med? What if we run into situation where we used 49 strings and we still need the score 53 (or any other prime number  > 50)?
•  » » » 15 months ago, # ^ |   +3 The biggest possible score of one string is 26·50 = 1300. You can use it at most times. After using some multiply of 50 in the next string the remaining needed score will be less than 50 (otherwise we would use a bigger multiply of 50). Note that we can use a string with score that is not multiply of 50 but it can only make things better. Finally, in one more string we can get exactly the remaining needed score because it's less than 50.
•  » » » » 15 months ago, # ^ |   0 Note that we can use a string with score that is not multiply of 50 but it can only make things better. Thank you! I understood the first part with multiples of 50, but I couldn't understand why using a different number makes things better.For example, this code doesn't use multiples of 50 as the last step. I thought that he was lucky before I saw that note. Does this code exhaust the K in the same way you've described?
•  » » » » » 15 months ago, # ^ |   +3 We can use strings with scores that are not multiplies of 50. It's a possibility, not an obligation. An extra possibility can't make things worse. I don't claim that it's useful though.That code uses big multiples of 26 and squares of numbers smaller than 26. It's slightly more complicated to prove its correctness but it indeed achieves any allowed K in at most 50 moves. You can analyze it this way: once you start decreasing a variable len, how big can K be in the next step? And how big can it be in yet another step?
 » 16 months ago, # |   +25 REPORT Admin please have a look into this http://imgur.com/CHav3o4PS: I would like to know to how add a pic in a comment.
•  » » 16 months ago, # ^ | ← Rev. 4 →   +28 Maybe this is what you wanted : EDIT: Seems YoScienceBitch is here to stay RankList
•  » » » 16 months ago, # ^ |   +44 I pity YoScienceBitch for having slow internet connection.
•  » » » » 16 months ago, # ^ |   0 Maybe he thought that submitting 20-30 seconds later will make him look any less suspicious.
 » 15 months ago, # |   +3 Can someone explain Div2-Hard in more detail? I don't completely understand the above explanation.Thanks
•  » » 15 months ago, # ^ |   +4 Let dp(L, R) denote the number of palindromic subsequences you can choose in the range (0,L) U (R, N-1). For each i, you need to calculate dp(i-1, i+1). Now the recurrence relation. Divide it into cases.Suppose you are at state dp(l,r) and decide to neglect str[l]. Then you move to state dp(l-1, r). If you reject str[r], you move to dp(l, r+1). Add both of these. But this induces double counting, i.e. when you reject both str[l] and str[r]. So subtract dp(l-1, r+1) from the answer.Also, when str[l]==str[r], you can choose both and go to state dp(l-1, r+1), so add this value whenever applicable. :)To sum up,When str[l]!=str[r], dp(l,r) = dp(l-1,r) + dp(l, r+1) — dp(l-1,r+1)When str[l]==str[r], dp(l,r) = dp(l-1,r) + dp(l, r+1)


text:
# Goodness-of-Fit Test

• /
• Blog
• /
• Goodness-of-Fit Test

The chi-square test is a statistical test commonly used to determine whether there is a significant difference between the expected and observed frequencies in a categorical data set. It is a goodness-of-fit test, which means that it is used to assess how well the observed data fit a particular theoretical distribution.

To perform a Chi-square test, the following steps are typically followed:

1. Specify the null and alternative hypotheses. The null hypothesis is usually that the observed and expected frequencies are the same, while the alternative hypothesis is that they are different.
2. Collect and summarize the data. Calculate the observed frequencies and the expected frequencies for each category.
3. Calculate the Chi-square statistic using the formula: $$\LARGE{\chi^2 = \sum_{i=1}^{n}\frac{(O_i - E_i)^2}{E_i}}$$  Where: • $$O_i$$ is the observed frequency in category i • $$E_i$$ is the expected frequency in category i • $$n$$ is the number of categories
4. Determine the critical value of the Chi-square statistic based on the significance level (alpha) of the test and the degrees of freedom. The degrees of freedom are calculated as the number of categories minus 1 (df = n - 1).
5. Compare the calculated Chi-square statistic to the critical value to determine whether to reject or fail to reject the null hypothesis. If the calculated Chi-square statistic exceeds the critical value, the null hypothesis is rejected, and the alternative hypothesis is accepted.

The assumptions of the Chi-square test are that the data is randomly sampled from a population, that the expected frequencies are greater than 5 in each category, and that all observations are independent.

In addition to testing the goodness-of-fit of a categorical data set, the Chi-square test can also be used to test the independence of two categorical variables. The steps to perform a Chi-square independence test (Contingency Table) are similar to those outlined above, except for using a two-dimensional contingency table to organize the data and calculate the expected frequencies.

 (adsbygoogle = window.adsbygoogle || []).push({});
###### About the Author Quality Gurus

Customers served! 1

Quality Management Course

FREE! Subscribe to get 52 weekly lessons. Every week you get an email that explains a quality concept, provides you with the study resources, test quizzes, tips and special discounts on our other e-learning courses.

 (adsbygoogle = window.adsbygoogle || []).push({});

Similar Posts:

December 27, 2022

## Hypergeometric Distribution

Hypergeometric Distribution

December 21, 2022

## One Proportion Z Test

One Proportion Z Test

September 12, 2021

## Seven Basic Quality Tools

Seven Basic Quality Tools

November 18, 2021

## Brainstorming Guide

Brainstorming Guide

December 12, 2021

## Design for Six Sigma (DFSS)

Design for Six Sigma (DFSS)

December 21, 2022

## One Sample Variance Test (Chi-square)

One Sample Variance Test (Chi-square)

December 27, 2021

## Seven New Management and Planning Tools

Seven New Management and Planning Tools

September 28, 2022

## Accelerated Life Tests (ALT)

Accelerated Life Tests (ALT)

December 27, 2022

## Chi-square Distribution

Chi-square Distribution

32 Courses on SALE!


text:
Compare a single proportion to the population proportion

The single proportion (or one-sample) binomial test is used to compare a proportion of responses or values in a sample of data to a (hypothesized) proportion in the population from which our sample data are drawn. This is important because we seldom have access to data for an entire population. The hypothesized value in the population is specified in the Comparison value box.

We can perform either a one-sided test (i.e., less than or greater than) or a two-sided test (see the Alternative hypothesis dropdown). We use one-sided tests to evaluate if the available data provide evidence that a sample proportion is larger (or smaller) than the comparison value (i.e., the population value in the null-hypothesis).

## Example

A car manufacturer conducted a study by randomly sampling and interviewing 1,000 consumers in a new target market. The goal of the study was to determine if consumers would consider purchasing this brand of car.

Management has already determined that the company will enter this segment. However, if brand preference is lower than 10% additional resources will be committed to advertising and sponsorship in an effort to enhance brand awareness amongst the target consumers. In the sample, 93 consumers exhibited what the company the company considered strong brand liking.

You can find information on the responses by survey participants in the consider.rda data set. The data set contains two variables, id and consider.

Our null-hypothesis is that the proportion of consumers that would consider the car brand for a future purchase is equal to 10%. Select the consider variable from the Variable dropdown. To evaluate the proportion of yes responses in the sample select yes from the Choose level dropdown.

Choose the Less than option from the Alternative hypothesis drop-down to determine if the available data provides sufficient evidence to reject the null-hypothesis in favor of the alternative that the proportion of consumers that will consider the brand is less than 10%.

The first two blocks of output show basic information about the test (e.g.,. the null and alternative hypothesis) and summary statistics (e.g., the proportion of “yes” responses). The final row of output shows the following:

• diff is the difference between the sample proportion (0.093) and the comparison value (0.1)
• ns is the number of successes. This is the number we can compare to a binomial-distribution with paramters $$n = 1000$$ and $$p = 0.10$$.
• p.value is the probability of finding a value as extreme or more extreme than diff if the null hypothesis is true
• 0% 95% show the 95% confidence interval around the sample proportion (0 to 0.11). These numbers provide a range within which the true population mean is likely to fall

### Testing

There are three approaches we can use to evaluate the null hypothesis. We will choose a significance level of 0.05.1 Of course, each approach will lead to the same conclusion.

#### p.value

Because the p.value is larger than the conventional significance level ($$0.249 > 0.05$$) we cannot reject the null hypothesis and do not suggest that management should commit resources to increase brand awareness.

We can also obtain the p.value by using the probability calculator in the Basics menu. Enter the number of successes in the data (93) as the lower bound (value) for a binomial-distribution with $$n = 1000$$ and $$p = 0.1$$. The p.value is the probability of observing a number of successes as or more extreme than the 93 we got in our sample. We see that $$P(X <= 93) = 0.249$$ which is the same value we got from Basics > Proportions > Single proportion.

#### confidence interval

Because the comparison value is contained in the confidence interval (i.e., $$0 < 0.1 < 0.11$$) we cannot reject the null hypothesis and do not suggest that management should commit resources to increase brand awareness.

#### number of successes

We can obtain the critical value by using the probability calculator in the Basics menu. For a binomial-distribution with $$n = 1000$$ and $$p = 0.1$$ the critical value is 85. We have to enter 0.05 as the lower probability bound because the alternative hypothesis is Less than.2

Because the number of successes (i.e., the number of “yes” responses) is larger than the critical value (93 vs 85) we cannot reject the null hypothesis and do not suggest that management should commit resources to increase brand awareness.

### Stats speak

This is a single proportion test of the null hypothesis that the true population proportion is equal to 0.1. Using a significance level of 0.05, we cannot reject the null hypothesis, and cannot conclude that the true population proportion is less than 0.1.

The p.value for this test is 0.249. This is the probability of observing a sample proportion (or number of successes) that is as or more extreme than the sample value we estimated from the data if the null hypothesis is true. In this case, it is the probability of observing a sample proportion (number of successes) that is less than (or equal to) 0.093 (93) if the true population proportion is 0.1.

The 95% confidence bound is 0.11. If repeated samples were taken and the 95% confidence bound computed for each one, the true population proportion would be below that bound in 95% of the samples

1 The significance level, often denoted by $$\alpha$$, is the highest probability you are willing to accept of rejecting the null hypothesis when it is actually true. A commonly used significance level is 0.05 (or 5%)

2 $$1 - \alpha$$ is called the confidence level. A commonly used confidence level is 0.95 (or 95%)


text:
Force on Moving Charges & Right Hand Rule Video Lessons

Concept

# Problem: This question has three equal parts. See the figure below and give the direction of the magnetic force on the charged particle (black dot). Note that for 1 and 2 the magnetic field is into the page and for 3 it is to the right. Note also the sign of the charge on the particle is given in parentheses (+) or (-)1. What is the direction of the force on particle (1)?A. Towards the left of the screen.B. Towards the bottom of the screen.C. Towards the right of the screen.D. Towards you out of the screen.E. Away from you into the screen.F. Towards the top of the screen.2. What is the direction of the force on particle (2)?A. Towards the right of the screen.B. Towards you out of the screen.C. Towards the bottom of the screen.D. Towards the top of the screen.E. Away from you into the screen.F. Towards the left of the screen.3. What is the direction of the force on particle (3)?A. Towards you out of the screen.B. Towards the right of the screen.C. Towards the bottom of the screen.D. Away from you into the screen.E. Towards the left of the screen.F. Towards the top of the screen.

###### FREE Expert Solution

We'll use the right-hand rule for a positive charge:

Thumb points in the direction of the velocity. Fingers point in the direction of the magnetic field. Palm points in the direction of the force on a positive charge.

A negative charge experiences a force opposite to that on a proton.

84% (496 ratings)
###### Problem Details

This question has three equal parts. See the figure below and give the direction of the magnetic force on the charged particle (black dot). Note that for 1 and 2 the magnetic field is into the page and for 3 it is to the right. Note also the sign of the charge on the particle is given in parentheses (+) or (-)

1. What is the direction of the force on particle (1)?

A. Towards the left of the screen.
B. Towards the bottom of the screen.
C. Towards the right of the screen.
D. Towards you out of the screen.
E. Away from you into the screen.
F. Towards the top of the screen.

2. What is the direction of the force on particle (2)?

A. Towards the right of the screen.
B. Towards you out of the screen.
C. Towards the bottom of the screen.
D. Towards the top of the screen.
E. Away from you into the screen.
F. Towards the left of the screen.

3. What is the direction of the force on particle (3)?

A. Towards you out of the screen.
B. Towards the right of the screen.
C. Towards the bottom of the screen.
D. Away from you into the screen.
E. Towards the left of the screen.
F. Towards the top of the screen.

Frequently Asked Questions

What scientific concept do you need to know in order to solve this problem?

Our tutors have indicated that to solve this problem you will need to apply the Force on Moving Charges & Right Hand Rule concept. You can view video lessons to learn Force on Moving Charges & Right Hand Rule. Or if you need more Force on Moving Charges & Right Hand Rule practice, you can also practice Force on Moving Charges & Right Hand Rule practice problems.