text:
XSQL routines have a very flexible variable management mechanism, similar in some aspects to scripting languages such as JavaScript.

# 1 Basic Concepts

• In XSQL, variables are declared by a set tag and take the name of the name attribute.
• The name of the variable is case-sensitive.
• The type of variable is automatic unless declared explicitly by the attribute type.
• The declaration of a variable creates a tag with the variable name, which can be referenced with a tag of the same name on the (function) context. For this reason, variable names cannot collide with previously-defined tag names.
• Variables can also be accessed through the get tag.
Copy
<xsql-script>

<set name='idx'>10</set>
<set name='Pi'>3.14</set>
<set name='name'>Robert</set>
<println><idx /></println>
<println><Pi /></println>
<println><name /></println>
<println><get name='idx' /></println>

</xsql-script>

By default, variables are always assigned by value. This means that when you assign an expression to a variable, the full value of the original expression is copied into the destination variable. As such, for example, after assigning the value of one variable to another, changes made to one of these variables will not affect the other with the exception of complex types (arrays, maps, etc.) that are assigned by reference.

# 2 Declaration of Variables

The <set/> tag allows users to declare a variable and perform the assignment of a value in the same statement. To create a variable named 'a' with a string 'test'

Copy
<set name='a'>test</set>

or, to be more explicit

Copy
<set name='a'><string>test</string></set>

## 2.1 Declaration of Variables from External Sources (Records)

A very important option in XSQL is the ability to automatically bind variables from a database and vice versa.

In the following example, you will see the use of the select tag to automatically declare SQL statement fieldsm_.

Copy
<xsql-script>

<column name='id' type='int' />
<column name='name' type='char' size='30' />

<insert table='tmp1'>
<column name='id'>1</column>
<column name='name'>CARS</column>
</insert>

<insert table='tmp1'>
<column name='id'>2</column>
<column name='name'>BIKES</column>
</insert>

<select prefix='m_'>
<columns>*</columns>
<from table='tmp1' />
<where>id=2</where>
</select>

<println>
<m_id />:<m_name />
</println>

</xsql-script>

The declaration of records from a database statement must be accompanied by a prefix to avoid collision with reserved identifiers.

## 2.2 Declaration of Iterator Variables

Some iteration commands allow you to create and assign values in the process loop. The iterator tag allows the user to go through arrays and maps. The value of an array element, key or map value, is automatically defined in the variable indicated by the name attribute.

Copy
<iterator name='a' type='key|entry'>
<in>
<map|array />
</in>
<do>
[instructions]
</do>
</iterator>
The iterators are described below in the Control Structures section.

# 3 Scope of Variables

The scope of a variable is the context within which the variable is defined. Most XSQL variables have a simple scope. This simple scope also covers the included files. For example:

Copy
<xsql-script>

<set name='a'>1</set>
<include name='file.xml'/>

</xsql-script>

Here, the variable a will be available inside the script including file.xml.

However, within the functions defined by the user, a local scope is introduced for the function. Any variable used within a function is, by definition, limited to the local scope of the function. Moreover, defined functions are opaque to predecessor functions, so that their variables are invisible. For example:

Copy
<xsql-script>

<function name='sub1'>

<set name='a'>2</set>
<println>sub1: </println>

</function>

<set name='a'>1</set>
<println>main: </println>
<sub1/>
<println>main: </println>

</xsql-script>

In the following example, you can see that the variable a is different in the local function sub1, and therefore, the variable a in the main function is invisible within the local function. Local functions, therefore, have their own variables not shared with predecessor functions. If required, some variables must be in argument form.

## 3.1 Global Variables

The option exists to declare global variables for the life cycle of the main function and its descendants. Global variables are declared by the global.set tag and, unlike normal variables, do not appear declared as language tags and can only be referenced by global.set and global.get.

Copy
<xsql-script>

<function name='sub1'>

<println>sub1: <global.get name='a'/></println>
<global.set name='a'>2</global.set>
<println>sub1: <global.get name='a'/></println>

</function>

<global.set name='a'>1</global.set>
<println>main: <global.get name='a'/></println>
<sub1/>
<println>main: <global.get name='a'/></println>

</xsql-script>

# 4 Reference to Variables

Variables can be referenced in different ways according to the scope of reference.

## 4.1 References in Context

Within the XML body, variables can be referenced in two ways:

• Using a tag as the name of the variable itself.
• Using the get tag with the name attribute indicating the variable.
Copy
<xsql-script>

<set name='a'>Hello</set>
<println></println>
<println><get name='a'/></println>

</xsql-script>

## 4.2 References in Attributes

In some cases, it is necessary to use a variable within an attribute. In such cases, there are two ways to reference the variable.

• #var is accepted for compatibility but cannot be used in all cases, such as when using an embedded script or when the script is executed as a code in an SQL object where #var refers to a main cursor field.
• ${var}, which is the recommended and safest way. Copy <xsql-script>  <array name='list'> <string>row 0</string> <string>row 1</string> <string>row 2</string> <string>row 3</string> <string>row 4</string> <string>row 5</string> <string>row 6</string> <string>row 7</string> <string>row 8</string> <string>row 9</string> <string>row 10</string> <string>row 11</string> </array> <set name='pos'>1</set>  <println><pos/> <array.get> <list /> <pos /> </array.get> </println>   <println>#pos <array.getElementAt position='#pos'> <list /> </array.getElementAt> </println>  <println>{$pos}
<array.getElementAt position='${pos}'> <list /> </array.getElementAt> </println>  <println>1{$pos}
<array.getElementAt position='1${pos}'> <list /> </array.getElementAt> </println>  </xsql-script> ## 4.3 Variable Names It is sometimes useful to have variable names that can be defined and used dynamically. A normal variable is established by a statement as: Copy <xsql-script>  <set name='mes_1'>Enero</set> <set name='mes_2'>Febrero</set> <set name='idx'>2</set> <println><get name='mes_${idx}'/></println>

</xsql-script>

## 4.4 Reference in an SQL Statement

### 4.4.1 Reference Types

In SQL expressions, the reference operator '#' can be used to obtain the value of a variable. The difference between using the reference operator and using a tag with the name of the variable is:

• the first one is transformed before executing the SQL statement.
• the second uses a prepared statement and resolves the value of the variable at that moment.

Normally, it is preferable to use a tag with the name of the variable, but there are cases in which using the reference operator is necessary. The following examples have the same result:

Copy
<xsql-script>

<column name='id' type='int' />
<column name='name' type='char' size='30' />

<insert table='tmp1'>
<column name='id'>1</column>
<column name='name'>CARS</column>
</insert>

<insert table='tmp1'>
<column name='id'>2</column>
<column name='name'>BIKES</column>
</insert>

<set name='p_id'>2</set>

<select prefix='m_'>
<columns>*</columns>
<from table='tmp1' />
<where>id = #p_id</where>
</select>

<select prefix='m_'>
<columns>*</columns>
<from table='tmp1' />
<where>id = <p_id /></where>
</select>

<println>
<m_id />:<m_name />
</println>

</xsql-script>

#### SQL Statement with Reference Operator

In the previous example, the first SQL statement is resolved as:

Copy
SELECT * FROM tmp1 WHERE id = 2

#### SQL Statement with Operator Tag

And the second SQL statement is resolved as:

Copy
SELECT * FROM tmp1 WHERE id = ?

The second case is much more efficient if the variable will take different values and perform multiple SQL operations, since the same PreparedStatement will always be used.

### 4.4.2 Quotation Marks

Returning to the previous example, let's assume that we want to select using the name field of the table, which belongs to the character type. It should be written:

Copy
<xsql-script>

<column name='id' type='int' />
<column name='name' type='char' size='30' />

<insert table='tmp1'>
<column name='id'>1</column>
<column name='name'>CARS</column>
</insert>

<insert table='tmp1'>
<column name='id'>2</column>
<column name='name'>BIKES</column>
</insert>

<set name='p_name'>BIKES</set>

<select prefix='m_'>
<columns>*</columns>
<from table='tmp1' />
<where>name = '#p_name'</where>
</select>

<select prefix='m_'>
<columns>*</columns>
<from table='tmp1' />
<where>name = <p_name /></where>
</select>

<println>
<m_id />:<m_name />
</println>

</xsql-script>

In this case, quotation marks must be used if the reference to the p_name variable is used so that the SQL statement is correctly formed. On the other hand, using the variable tag is not necessary for a PreparedStatement.

#### SQL Statement with Reference Operator

In the previous example, the first SQL statement is resolved as:

Copy
SELECT * FROM tmp1 WHERE name = 'BIKES'

In this case, quotation marks have been added to the reference operator.

#### SQL Statement with Operator Using Tag

And the second SQL statement is resolved as:

Copy
SELECT * FROM tmp1 WHERE name = ?

In some cases, the reference operator must be used explicitly, e.g. if the value of a condition of the "where" clause is placed in a variable. In this case, this part cannot be prepared and, therefore, it is necessary to resolve the SQL expression directly.

Here is an example where it is used: <where>#p_where</where>:

Copy
<xsql-script>

<column name='id' type='int' />
<column name='name' type='char' size='30' />

<insert table='tmp1'>
<column name='id'>1</column>
<column name='name'>CARS</column>
</insert>

<insert table='tmp1'>
<column name='id'>2</column>
<column name='name'>BIKES</column>
</insert>

<set name='p_where'>name = 'BIKES'</set>

<select prefix='m_'>
<columns>*</columns>
<from table='tmp1' />
<where>#p_where</where>
</select>

<println>
<m_id />:<m_name />
</println>

</xsql-script>

# 5 Deletion of Variables

It is possible to delete variables that have been created previously. A variable can be deleted manually by indicating its name, or several variables can be deleted by indicating the prefix of the name.

locales

Copy
<unset name='a' />
<unset>a</unset>
<unset></unset>
<unset>variable_</unset>
<unset></unset>
<unset prefix='capuntes_' />

globales

Copy
<global.unset name='a' />
<global.unset>a</global.unset>
<global.unset></global.unset>
<global.unset>variable_</global.unset>
<global.unset></global.unset>
<global.unset prefix='capuntes_' />

# 6 Variable Data Types

A variable can contain any supported data type. The variables do not have a predefined type. They acquire the type of data they contain at each moment. Therefore, a variable can be re-assigned to different types of data.

Copy
A string is assigned to the variable

<set name='a'>
<string>HELLO</string>
</set>

An (integer) number is assigned to the variable
<set name='a'>
<number>10</number>
</set>

A decimal number is assigned to the variable

<set name='a'>
<number type='decimal'>10</number>
</set>

Note that the number constructor is the <number> function. This returns the object of some numeric primitive types such as smallint, integer, long, float, double, decimal depending on the size and precision of the number or value of the optional attribute.

Variables take the same data type depending on the means of assignment.

• Assignment with automatic conversion
• Assignment for another variable
• Assignment by function
• Assignment by argument type

## 6.1 Assignment with Automatic Conversion

A variable declaration with a type omission comes from automatic detection. This system generates string, integer or decimal types depending on the entry data. For example:

Copy
<set name='a1'>Hello</set>
<set name='a2'>10</set>
<set name='a3'>10.05</set>
<set name='a3'>2000000000</set>
<set name='a4'>2000000000000000000000</set>

#### Note

This option is not recommended, as the type must be declared explicitly.

## 6.2 Assignment by Another Variable

When a variable is assigned to another variable, the latter takes the value and the type of the former.

Copy
<set name='a1'>Hello</set>
<set name='a2'>10</set>
<set name='a3'><a1/></set>
<set name='a4'><a2/></set>

#### Note

Note that if the object to which it refers is an object value, the two variables contain copies of the object. However, if it is a reference, both of them point to the same object.

## 6.3 Assignment by Function

When a variable is defined by a function call (of the system or a subroutine), it has a value determined by the function.

Copy
<set name='a1'><string>Hello</string></set>
<set name='n1'><number>10</number></set>
<set name='n2'><number>10.05</number></set>
<set name='n3'><number>20000000000</number></set>
<set name='n4'><number>2000000000000000000000</number></set>

#### Note

Note that the '''<number>''' function takes different types of numbers and creates a numeric object size, as well as corresponding precision for the source value.

## 6.4 Assignment by Type of Argument

After the value of a function has been determined, the argument can define a data type. In this case, the constructor of the function will force the original's conversion to a specified type. If it is omitted, the argument will have the source variable type.

Copy
<xsql-script name='args'>

<function name='divide1'>
<args>
<arg name='x' />
<arg name='y' />
</args>

<return>
<x/><y/>
</return>

</function>

<function name='divide2'>
<args>
<arg name='x' type='double' />
<arg name='y' type='double' />
</args>

<return>
<x/><y/>
</return>

</function>

<set name='a'><number>10</number></set>
<set name='b'><number>2</number></set>

<println><divide1></divide1></println>

<println><divide2></divide2></println>

</xsql-script>

# 7 Variables by Value or Reference

A variable can be assigned to another variable or passed as an argument to another routine or function. The resulting variable of assignment or function parameter are variables too. The important issue is knowing whether the new variable is:

• a copy of the original variable (different).
• a reference to the original variable, meaning the same variable with a different name.

In the following example, we can see how the modified number value of the function is not reflected in the main function, but the map is modified. This means that the numeric value is a value, while the map is a reference.

Copy
<xsql-script>

<function name='sub1'>
<args>
<arg name='p_num' />
<arg name='p_map' />
</args>

<map.put name='p_map'><string>TANKS</string><number>2</number></map.put>

</function>

<set name='n1'>90</set>
<map name='m1'>
<item><string>CARS</string><number>10</number></item>
<item><string>BIKES</string><number>20</number></item>
</map>

<sub1>
<n1/>
<m1/>
</sub1>

<println><n1 /></println>
<println><m1 /></println>

</xsql-script>

## 7.1 Pass by Value

When a call is done on a routine or function and variables are passed as arguments, it is said that the variable is passed by value when the modifications made to the routine or function do not affect the variable.

Some variables with types are passed by value. In other words, the variable is not what passes by value, but rather the data type it contains. Types which are passed by value include:

• string
• smallint
• integer
• bigint
• long
• float
• double
• decimal
• date
• time
• timestamp
• dateunits

## 7.2 Pass by Reference

When a call is done on a routine or function and variables are passed as arguments, the variable is passed by reference when the modifications done on the routine or call function affect the variable which has been passed.

The objects comprise collections or maintain connections with other systems. Types which are passed by reference include:

• byte
• file
• node
• element
• array
• map
• vtable

# 8 Concatenation of Variables

It is important to keep in mind that tags <set> and <global.set> only receive an argument. For this reason, if the content must be concatenated in two or more variables, an argument must be passed to a function which will be the unique argument <set>. For example, to concatenate two strings, the following code must be used:

Copy

c = a + space + b

<xsql-script>

<set name="a">Hello</set>
<set name="b">world</set>
<set name='c'>
<string><string.space /></string>
</set>

<println>
<c />
</println>

</xsql-script>

# 9 Variable Inspection

To verify if a local variable has been instanced, the <isdefined> tag can be used.

Copy
<xsql-script>

<println><isdefined name='a' /></println>

</xsql-script>

The <variable.typeof> tag verifies if a variable type can be used.

Copy
<xsql-script>

<set name='p_boolean' ><true/></set>
<set name='p_integer' >5000</set>
<set name='p_long' >20000000000</set>
<set name='p_bigint' >20000000000000000000000</set>
<set name='p_decimal'>3.14</set>
<set name='p_date'><date.today /></set>

<set name='p_smallint' type='smallint'>5000</set>
<set name='p_float' type='float'>3.14</set>
<set name='p_double' type='double'>3.14</set>

<println>Automatic</println>
<println>p_boolean : <p_boolean />  : <variable.typeof><p_boolean /></variable.typeof></println>
<println>p_integer : <p_integer />  : <variable.typeof><p_integer /></variable.typeof></println>
<println>p_long    : <p_long    />  : <variable.typeof><p_long /></variable.typeof></println>
<println>p_bigint  : <p_bigint  />  : <variable.typeof><p_bigint /></variable.typeof></println>
<println>p_decimal : <p_decimal />  : <variable.typeof><p_decimal /></variable.typeof></println>
<println>p_date    : <p_date />     : <variable.typeof><p_date /></variable.typeof></println>
<println />
<println>Fixed type</println>
<println>p_smallint: <p_smallint /> : <variable.typeof><p_smallint /></variable.typeof></println>
<println>p_float   : <p_float />    : <variable.typeof><p_float /></variable.typeof></println>
<println>p_double  : <p_double />   : <variable.typeof><p_double /></variable.typeof></println>

</xsql-script>

# 10 Type Conversion

XSQL language is very flexible in relation to passing arguments. If a relaxed system is chosen, it is not necessary to indicate the argument type of routines or functions. Conversely, if more rigid verificaction is needed at execution time, the data type can be indicated for the arguments.

When an argument does not fulfill the expected type and the conversion fails, an error will be shown at the time of execution. A frequent scenario is to pass a large size number to a routine which expects a smaller numeric data type. For example, if the user passes a value of 40000 to a routine which expects smallint types, whose rank is -32768, an error will be produced.

Copy
<xsql-script>

<function name='sub1'>
<args>
<arg name='p_num' type='smallint' />
</args>

</function>

<sub1>
<number>40000</number>
</sub1>

</xsql-script>

In the same way, assign a value to a variable with a strict type

Copy
<xsql-script>

<set name='p_num' type='smallint'>40000</set>

</xsql-script>


text:
MathSciNet bibliographic data MR965244 58F25 (54H20 58F10) Kuperberg, K. M.; Reed, Coke S. A dynamical system on ${\bf R}^3$${\bf R}^3$ with uniformly bounded trajectories and no compact trajectories. Proc. Amer. Math. Soc. 106 (1989), no. 4, 1095–1097. Article

For users without a MathSciNet license , Relay Station allows linking from MR numbers in online mathematical literature directly to electronic journals and original articles. Subscribers receive the added value of full MathSciNet reviews.

format: plain


text:
## Why doesn't \emph work?

2010-03-15
2013-04-29
• Hi all.  Any reason why jsMath doesn't seem to interpret \emph{Hello World}?

# In this paper, we study a long existing open problem on Landsberg metrics in Finsler geometry. We consider Finsler metrics defined by a Riemannian metric and a $1$-form on a manifold. We show that a \emph{regular} Finsler metric in this form is Landsbergian if and only if it is Berwaldian. We further show that there is a two-parameter family of functions, $\phi=\phi(s)$, for which there are a Riemannian metric $\alpha$ and a $1$-form $\beta$ on a manifold $M$ such that the scalar function $F=\alpha \phi (\beta/\alpha)$ on $TM$ is an almost regular Landsberg metric, but not a Berwald metric.

…is nicely interpreted by jsMath, but for the \emph{regular} which is undigested.

Check http://www.cms.math.ca/10.4153/CJM-2009-064-9 and flip the Format: between jsMath and Latex to see what I mean.


text:
# Weak NP-completeness

I know that the Knapsack problem is weakly NP-complete. I also notice that on Wikipedia:

"A problem is said to be strongly NP-hard if a strongly NP-complete problem has a polynomial reduction to it [...]"

The way I prove the NP-hardness is by a reduction chain: SAT $$\leq$$ 3SAT $$\leq$$ Tripartite Matching $$\leq$$ Exact cover by 3-sets $$\leq$$ Subset sum $$\leq$$ Knapsack.

Does it mean all these problems are weakly NP-complete? Because it seems that according to Wikipedia if one of them is strongly NP-complete, Knapsack will be strongly NP-complete.

As is often the case, the Wikipedia article is misleading.

A problem involving integers parameters is:

• Strongly NP-complete if the problem is NP-complete when the parameters are encoded in unary (i.e., $$n$$ is encoded as $$0^n$$).
• Weakly NP-complete if the problem is NP-complete when the parameters are encoded in binary (which is the usual encoding).

In other words, there is only one notion of NP-completeness, and the confusing terms strongly and weakly NP-complete simply refer to different encodings of problems.

For a problem like SAT, these terms are simply inapplicable, since SAT has no integer parameters. The terms do apply to the related problem of weighted MAX-SAT, in which the input is a set of weighted clauses and a target, and the problem is to determine whether there is an assignment which satisfies clauses whose total weight exceeds the target.

• So you mean weighted MAX-SAT can be said weakly NP-complete ? Even if weights are integers, there is no polynomial solution to it, does it ? – Vince Jun 7 at 9:40
• Weighted MAX-SAT in strongly NP-complete, by reduction from SAT. This means that weighted MAX-SAT with weights encoded in unary is NP-complete. – Yuval Filmus Jun 7 at 9:43


text:
by Kaya Stechly 1562 days ago | link | parent | on: Paraconsistent Tiling Agents (Very Early Draft) Section 4.1 is fairly unpolished. I’m still looking for better ways of handling the problems it brings up; solutions 4.1 and 4.2 are very preliminary stabs in that direction. The action condition you mention might work. I don’t think it would re-introduce Löbian or similar difficulties, as it merely requires that $$\overline{a}$$ implies that $$G$$ is only true, which is a truth value found in $$LP$$. Furthermore, we still have our internally provable T-schema, which does not depend on the action condition, from which we can derive that if the child can prove $$(\overline{a}\rightarrow G)\land\lnot(\overline{a}\rightarrow\lnot G)$$, then so can the parent. It is important to note that “most” (almost everything we are interested in) of $$\mathcal{PA}\star$$ is consistent without problem. Now that I think about it, your action condition should be a requirement for paraconsistent agents, as otherwise they will be willing to do things that they can prove will not accomplish $$\mathcal{G}$$. There may yet be a situation which breaks this, but I have not come across it. reply
 by Kaya Stechly 1567 days ago | Jessica Taylor likes this | link | parent | on: Paraconsistent Tiling Agents (Very Early Draft) 1. Any extension of $$LP$$ will work as well unless it leads to triviality; however, we cannot in general validate the $$T$$-schema for an arbitrary conditional. For example, any conditional $$\rightarrow$$ that satisfies the inference of contraction ($$\alpha\rightarrow(\alpha\rightarrow\beta)\Vdash\alpha\rightarrow\beta$$) will succumb to Curry’s paradox and lead to triviality (consider the fixed point formula $$\gamma$$ of the form $$T(\gamma)\rightarrow\perp$$). Now, as far as I can tell, we can validate the T-schema of the conditional for $$RM_3$$; since $$LP\supset$$’s conditional is expressively equivalent, it seems like it shouldn’t be too hard to show that we can also validate its T-schema. For further discussion on the topic (with proofs, etc.), see chapter 8 of Priest’s part of volume XI of the second edition of Gabbay and Geunther’s Handbook of Philosophical Logic (what a mouthful of of’s). A thorough presentation of $$LP$$ can be found in Priest’s An Introduction to Non-Classical Logics, section 7.4. Sections 7.1-7.3 introduce the general structures of such logics and delineate their differences. This book does not say much about truth schemas. Priest’s paper “The Logic of Paradox” from ’79 also describes $$LP$$, although I find the presentation a bit clunky. For a better grasp of how inference works in $$LP$$, look at section III.9; there are examples of both inferences that are true and inferences that do not always hold even though we ay expect them to. I will probably be writing up a minimal formal description soon, as I code the PROLOG meta-interpreter. We can prove non-triviality of $$LP$$ and that the T-schema holds, so as a consequence L"ob must fail. This seems somewhat unsatisfactory as an answer to which step fails. I can think of a few reasons why L"ob might fail; I haven’t seen a discussion of this in the literature, so I will try to cobble together an answer or the shape thereof from what I know. One possible reason is that pseudo Modus Ponens fails in LP. That is, though $$A,A\rightarrow B$$ might entail $$B$$ for a well chosen conditional, $$A\wedge (A\rightarrow B)\rightarrow B$$ must fail or else lead to triviality due to Curry’s paradox. More likely is that this is a consequence of the way paraconsistency works with modal logic. From the wikipedia article you linked, we have that “in normal modal logic, Löb’s axiom is equivalent to the conjunction of the axiom schema 4, ($$\Box\Box A\rightarrow\Box A$$) and the existence of modal fixed points.” We have both of those, so the difference must stem from the phrase “normal modal logics.” The proof uses the fact of the existence of a modal fixed point of a certain form; this may not hold in a modal extension of $$LP$$ (which would be analogous to $$KM_3$$, the modal extension of $$RM_3$$, just as $$K$$ is the modal extension of classical logic.). More details on modal extensions of paraconsistent logics can be found in McGinnis’ paper “Tableau Systems for Some Paraconsistent Modal Logics,” though this paper does not mention modal fixed points. In fact, none of the papers I’ve read so far on paraconsistent modal logics have mentioned fixed points. I would construct a proof on my own, but I am currently too unfamiliar with modal logic; if it is important, I can go learn enough and do it. Thanks for your comments! I hope to have at least somewhat answered your questions. Paraconsistency is still to me a very strange subject, so my studies and understanding are still very much incomplete. reply

### NEW DISCUSSION POSTS

[Note: This comment is three
 by Ryan Carey on A brief note on factoring out certain variables | 0 likes

There should be a chat icon
 by Alex Mennen on Meta: IAFF vs LessWrong | 0 likes

Apparently "You must be
 by Jessica Taylor on Meta: IAFF vs LessWrong | 1 like

There is a replacement for
 by Alex Mennen on Meta: IAFF vs LessWrong | 1 like

Regarding the physical
 by Vanessa Kosoy on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

I think that we should expect
 by Vanessa Kosoy on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

I think I understand your
 by Jessica Taylor on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

This seems like a hack. The
 by Jessica Taylor on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

After thinking some more,
 by Vanessa Kosoy on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

Yes, I think that we're
 by Vanessa Kosoy on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

My intuition is that it must
 by Vanessa Kosoy on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

To first approximation, a
 by Vanessa Kosoy on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

Actually, I *am* including
 by Vanessa Kosoy on The Learning-Theoretic AI Alignment Research Agend... | 0 likes

Yeah, when I went back and
 by Alex Appel on Optimal and Causal Counterfactual Worlds | 0 likes

> Well, we could give up on
 by Jessica Taylor on The Learning-Theoretic AI Alignment Research Agend... | 0 likes


text:
# The Datasaurus data package

#### 2018-09-20

This package wraps the awesome Datasaurus Dozen dataset, which contains 13 sets of x-y data. Each sub-dataset has five statistics that are (almost) the same in each case. (These are the mean of x, mean of y, standard deviation of x, standard deviation of y, and Pearson correlation between x and y). However, scatter plots reveal that each sub-dataset looks very different. The dataset is intended to be used to teach students that it is important to plot their own datasets, rather than relying only on statistics.

The Datasaurus was created by Alberto Cairo in this great blog post.

Datasaurus shows us why visualisation is important, not just summary statistics.

He’s been subsequently made even more famous in the paper Same Stats, Different Graphs: Generating Datasets with Varied Appearance and Identical Statistics through Simulated Annealing by Justin Matejka and George Fitzmaurice.

In the paper, Justin and George simulate a variety of datasets that the same summary statistics to the Datasaurus but have very different distributions.

This package looks to make these datasets available for use as an advanced Anscombe’s Quartet, available in R as anscombe.

## Usage

To see that statistics are (almost) the same for each sub-dataset, you can use dplyr.

library(datasauRus)
if(requireNamespace("dplyr")){
suppressPackageStartupMessages(library(dplyr))
datasaurus_dozen %>%
group_by(dataset) %>%
summarize(
mean_x    = mean(x),
mean_y    = mean(y),
std_dev_x = sd(x),
std_dev_y = sd(y),
corr_x_y  = cor(x, y)
)
}
## Loading required namespace: dplyr
## Warning: package 'dplyr' was built under R version 3.5.1
## # A tibble: 13 x 6
##    dataset    mean_x mean_y std_dev_x std_dev_y corr_x_y
##    <chr>       <dbl>  <dbl>     <dbl>     <dbl>    <dbl>
##  1 away         54.3   47.8      16.8      26.9  -0.0641
##  2 bullseye     54.3   47.8      16.8      26.9  -0.0686
##  3 circle       54.3   47.8      16.8      26.9  -0.0683
##  4 dino         54.3   47.8      16.8      26.9  -0.0645
##  5 dots         54.3   47.8      16.8      26.9  -0.0603
##  6 h_lines      54.3   47.8      16.8      26.9  -0.0617
##  7 high_lines   54.3   47.8      16.8      26.9  -0.0685
##  8 slant_down   54.3   47.8      16.8      26.9  -0.0690
##  9 slant_up     54.3   47.8      16.8      26.9  -0.0686
## 10 star         54.3   47.8      16.8      26.9  -0.0630
## 11 v_lines      54.3   47.8      16.8      26.9  -0.0694
## 12 wide_lines   54.3   47.8      16.8      26.9  -0.0666
## 13 x_shape      54.3   47.8      16.8      26.9  -0.0656

To see that each sub-dataset looks very different, you can draw scatter plots.

if(requireNamespace("ggplot2")){
library(ggplot2)
ggplot(datasaurus_dozen, aes(x=x, y=y, colour=dataset))+
geom_point()+
theme_void()+
theme(legend.position = "none")+
facet_wrap(~dataset, ncol=3)
}
## Loading required namespace: ggplot2
## Warning: package 'ggplot2' was built under R version 3.5.1


text:
## A community for students. Sign up today

Here's the question you clicked on:

## anonymous one year ago For the graph below, what should the domain be so that the function is at least 200? graph of y equals minus 2 times the square of x plus 30 times x plus 200 −5 ≤ x ≤ 20 0 ≤ x ≤ 15 x ≥ 0 All real numbers

• This Question is Closed
1. anonymous
2. anonymous

@Michele_Laino

3. Michele_Laino

hint: from your graph, I see that: f(0)= 200, f(15)=200, and fo r all point x between 0 and 15, is f(x)>200

4. Michele_Laino

oopss. for all points*

5. anonymous

I am sorry i am still confused.

6. Michele_Laino

|dw:1440187581388:dw|

7. anonymous

Okay.

8. Michele_Laino

at x=0, f(x) = 200 right?

9. anonymous

Right.

10. Michele_Laino

furthermore also at x=15, f(x)= 200

11. anonymous

Okay :]

12. Michele_Laino

and if x>0 and x<15, f(x) is > 200

13. anonymous

0 ≤ x ≤ 15

14. Michele_Laino

yes!

15. anonymous

Is that all for my answer?

16. Michele_Laino

yes!

17. anonymous

Can you help with 1 more? The following graph shows the functions f(x) and g(x): graph of function f of x equals x squared and graph of function g of x equals x squared plus 5 The function g(x) is obtained by adding _______ to f(x). (only input integers) Numerical Answers Expected! Answer for Blank 1:

18. Michele_Laino

we have: $\Large \begin{gathered} f\left( x \right) = {x^2} \hfill \\ g\left( x \right) = {x^2} + 5 \hfill \\ \end{gathered}$

19. Michele_Laino

now I replace x^2 with f(x) into the expression for g(x), and I can write this: $\Large g\left( x \right) = f\left( x \right) + 5$

20. Michele_Laino

so what can you conclude?

21. anonymous

Sorry i am confused.

22. Michele_Laino

the expression of f(x) and g(x) are correct, right?

23. Michele_Laino

expressions*

24. anonymous

Yes?

25. Michele_Laino

ok! now I can rewrite the first equation as below: $\Large {x^2} = f\left( x \right)$

26. anonymous

ok.

27. Michele_Laino

then, I replace x^2 with f(x), into the expression for g(x), so I get this equation: $\Large g\left( x \right) = f\left( x \right) + 5$

28. anonymous

Okay :]

29. Michele_Laino

ok! now, the geometrical meaning of that equation is: |dw:1440188519007:dw|

30. Michele_Laino

|dw:1440188632785:dw|

31. Michele_Laino

so, what is the requested number?

32. anonymous

5?

33. Michele_Laino

correct! since the graph of g(x), as you can see from my drawing, it is shifted up by 5 units with respect to the graph of f(x)

34. anonymous

Thank you!!!!!!!

35. Michele_Laino

:)

#### Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy


text:
# ExtrapolationScheme¶

class ExtrapolationScheme(include_first_order_term=None, include_second_order_term=None, include_third_order_term=None, minimum_number_of_atoms=None)

A container for parameters defining the extrapolation scheme to infinite supercell size to use.

The extrapolation is obtained by fitting the calculated formation energies against the inverse length 1/L of each supercell, where L is the cube root of the supercell volume. A polynomial of up to third order is fitted. The first, second and third order terms can each be included or not in the fit (if not, they are set to zero). In all cases the fitted zeroth order term gives the extrapolation to infinite supercell size.

Parameters: include_first_order_term (bool) – Whether to include the 1/L term (monopole-monopole) in the extrapolation fit. Default: True include_second_order_term (bool) – Whether to include the 1/L^2 term in the extrapolation fit. Default: False include_third_order_term (bool) – Whether to include the 1/L^3 term (monopole-quadrupole) in the extrapolation fit. Default: True minimum_number_of_atoms (int) – The minimum number of atoms for the supercell to be included in the fit. Any supercell with fewer atoms will be discarded. Default: 8
minimumNumberOfAtoms()
Returns: The minimum number of atoms for the supercell to be included in the fit. Any supercell with fewer atoms will be discarded. int
termsToInclude()
Returns: Whether to include the first, second and third order terms in the extrapolation fit. tuple (size 3) of bool


text:
December 31, 2013
By

(This article was first published on Open Geospatial Technologies » R, and kindly contributed to R-bloggers)

The function readOGR in the rgdal package is used to bring vector spatial data sources into R. readOGR() relies upon OGR (part of the GDAL/OGR library) for format conversion. Unfortunately, while OGR supports the ability to subset columns (with the -select switch) or rows (with the -where switch), or even to request a layer using a full SQL statement, none of that functionality is available in readOGR. Every so often this gets discussed in the mailing lists, but the functionality has not yet been implemented.

If your data is already in a SQL database though, you’re in luck. You can accomplish the same thing within R by creating a spatial view in-database, loading the spatial view with readOGR, then dropping the view. I’ve created a function that does just that for PostGIS data sources.

readOgrSql = function (dsn, sql, ...) {

require(rgdal)
require(RPostgreSQL)
require(stringr)

# check dsn starts "PG:" and strip
if (str_sub(dsn, 1, 3) != "PG:") {
stop("readOgrSql only works with PostgreSQL DSNs")
}
dsnParamList = str_trim(str_split(dsn, ":")[[1]][2])

# Build dbConnect expression, quote DSN parameter values
if (str_count(dsnParamList, "=")
== str_count(dsnParamList, "='[[:alnum:]]+'")) {
strExpression = str_c(
"dbConnect(dbDriver('PostgreSQL'), ",
str_replace_all(dsnParamList, " ", ", "),
")"
)
}
else {
dsnArgs = word(str_split(dsnParamList, " ")[[1]], 1, sep="=")
dsnVals = sapply(
word(str_split(dsnParamList, " ")[[1]], 2, sep="="),
function(x) str_c("'", str_replace_all(x, "'", ""), "'")
)
strExpression = str_c(
"dbConnect(dbDriver('PostgreSQL'), ",
str_c(dsnArgs, "=", dsnVals, collapse=", "),
")"
)
}

# Connect, create spatial view, read spatial view, drop spatial view
conn = eval(parse(text=strExpression))
strCreateView = paste("CREATE VIEW vw_tmp_read_ogr AS", sql)
dbSendQuery(conn, strCreateView)
dbDisconnect(conn)
return(temp)
}

Since readOGR can’t send arbitrary SQL to the data source, the function also requires the RPostgreSQL package. Because I wanted the readOgrSql function to conform to readOGR as closely as possible, the function takes the DSN as a character string, then chops it up to pass the DSN parameters to dbConnect. readOGR expects the DSN in this format:

"PG:dbname='db' host='host' port='5432' user='user' password='***'"

The user requires privileges to create objects in the public schema.

Then, readOgrSql can be called as follows:

strSQL = "
SELECT gid, name,
ST_Transform(geom, 4326)::geometry(MultiPolygon, 4326) AS geom
FROM geo_states"
row.names(spdfStates) = spdfStates\$name

(The last line is not strictly necessary, but is a little trick I use to make it easier to refer to specific features by name.)

At the moment this only works for PostGIS 2.0+. It relies on the fact that in recent versions of PostGIS, spatial views are automatically registered because the geometry_columns “table” is actually a view which finds all geometry columns in all tables. But for the view to work as a full spatial layer, the geometry column in the SELECT statement must be explicitly cast using a typmodded geometry. In the example, this is accomplished with ::geometry(MultiPolygon, 2263), but in general ::geometry(<geometry type>, <srid>). If there are no transformations on the geometry, the explicit cast can be avoided as long as the underlying table is defined using the PostGIS 2.0+ typmodded geometry columns:

SELECT gid, geom FROM my_spatial_table;

will work, but

SELECT gid, ST_Transform(geom, 4326) AS geom
FROM my_spatial_table;

will only work partially, because the transformed geometry is generic. See Manually Registering Geometry Columns in geometry_columns for details. Note that rgdal is smart enough to load the layer into an appropriate Spatial*DataFrame (e.g., SpatialPolygonsDataFrame for an OGC Polygon or MultiPolygon), but will lose the spatial reference information (i.e., the projection or coordinate system). It will plot OK, but unless you fix it in R, you won’t be able to combine it with layers in different coordinate reference systems.

Extending this to work for PostGIS pre-2.0 or for SpatiaLite shouldn’t be too difficult, but will require manually registering the spatial view in geometry_columns.


text:
# The density of CaO is $3.35 gm/cm^3$. The oxide crystallises in one of the cubic systems with an edge of 4.80 $A^{\large\circ}$. How many $Ca^{++ }$ ions and $O^{–2}$ ions belong to each unit cell, and which type of cubic system is present?

No of $Ca^{++}$ion=4,No of $O^{--}$ion=4,fcc


text:
# independent set and independence number

A set of vertices in a graph $G$ is called an if there are no edges between the vertices.

The independence number of a graph $G$, usually denoted by $\alpha(G)$, is the size of a maximal independent set in $G$. $\alpha(G)\geq\nu$ means that there are $\nu$ vertices with no edges between them.

An independent set is sometimes called a stable set or an anticlique.

Title independent set and independence number IndependentSetAndIndependenceNumber 2013-03-22 14:30:06 2013-03-22 14:30:06 rspuzio (6075) rspuzio (6075) 6 rspuzio (6075) Definition msc 05C69 stable set anticlique Clique2 independent set independence number


text:
# Quantifiers, Using Countable and Uncountable Nouns

English Quantifiers, Using Countable and Uncountable Nouns

 Quantifier Meaning Countable Noun Uncountable Noun Little Small, minor No Yes Few Small, slight Yes No A lot of a large number or amount Yes Yes Many Very, numerous Yes No Much Very, too, a lot No Yes Any Never, at all Yes Yes Lots of A lot of Yes Yes Some an unspecified amount or number of Yes Yes


text:
# Why are the residuals in this model so linearly skewed?

I am fitting a simple linear regression model with 4 predictors:

lm(Outcome ~ Predictor1 + Predictor2 + Predictor3 + Predictor4, data=dat.s)

I'm finding that the model predictions are consistently off as shown in this graph:

The model clearly overestimates the low values and underestimates the high values, but the miss-estimation is very linear -- it seems like the model should be able to just adjust the slope and fit the data better. Why is that not happening? In case it helps, here are scatterplots of the the Outcome against each of the four Predictors:

Using the car package outlierTest function did not identify any outliers.

You shouldn't plot the residuals against the predicator values because they are correlated, instead we plot against the fitted values, i.e. $\hat Y$. To see this, consider this simple data set:

x = runif(20)
y = rnorm(20)

Clearly $x$ and $y$ are unrelated. Now, we fitted a simple linear regression model

m = lm(y ~ x)

and plot the residuals against outcome and fitted values

plot(y, residuals(m))
plot(fitted.values(m), residuals(m))

to get:

Notice the plotting against the outcome $y$, doesn't give any insight. Hence, it's not really clear if there is something wrong with your model since we don't expect random scatter.

• Nice example but I think this is a little more complicated because it involves four predictors and not just one. Sep 25, 2012 at 22:01
• Thanks, the example was very helpful! I plotted the residuals against the predicted values and they are nicely evenly distributed. @MichaelChernick is right that my situation is a little more complicated and some of the predictors are correlated, but I think this was the crux of it. Sep 25, 2012 at 23:34

What you are seeing is called "Regression towards the Mean" and is completely expected. Any time that there is variability in the data (and yours looks like it has a bunch) then the prediction values will on average be between the overall mean and the observed values. The plot you created, of the outcome vs the predicted values is not commonly done, for the reasons that you are seeing, it tends to confuse more than enlighten. It is more common to plot the predicted values against the residuals as this plot will show more randomness if the model is reasonable.

csgillespie's example has been criticized for only including 1 predictor when the original question included 4. Here is some quick R code that can be run to show the same patterns with 4 predictors:

# simulated data, no relationship
df1 <- data.frame(y=rnorm(100), x1=rnorm(100), x2=rnorm(100),
x3=rnorm(100), x4=rnorm(100))

fit1 <- lm( y ~ ., data=df1 )
#plot(df1$y, fitted(fit1), asp=1) scatter.smooth(df1$y, fitted(fit1), asp=1)
abline(0,1)
abline(h=mean(fitted(fit1)), col='lightgrey')
plot(df1$y, resid(fit1)) abline(h=0) plot(fitted(fit1), resid(fit1)) abline(h=0) # simulated data, relationship library(MASS) df2 <- as.data.frame( mvrnorm(100, mu=1:5, Sigma= matrix(.7,5,5)+diag(rep(.3,5)))) names(df2) <- c('y','x1','x2','x3','x4') fit2 <- lm( y ~ ., data=df2 ) #plot(df2$y, fitted(fit2), asp=1)
scatter.smooth(df2$y, fitted(fit2), asp=1) abline(0,1) abline(h=mean(fitted(fit2)), col='lightgrey') plot(df2$y, resid(fit2))
abline(h=0)

plot(fitted(fit2), resid(fit2))
abline(h=0)

# real data
fit3 <- lm( Murder~Population+Income+Illiteracy+Frost, data=as.data.frame(state.x77))

scatter.smooth( state.x77[,'Murder'], fitted(fit3), asp=1)
abline(0,1)
abline(h=mean(fitted(fit3)), col='lightgrey')
plot(state.x77[,'Murder'], resid(fit3))
abline(h=0)

plot(fitted(fit3), resid(fit3))
abline(h=0)

Notice that the plots look very similar to those in the original question.

Notice also that in the plot of the original outcome vs. the fitted values that the points (and more so their trend) tend to fall between the $y=x$ line and the mean line. This is the idea of regression towards the mean as originally described by Galton See Here. The points are not randomly scattered about the $y=x$ line like the original poster assumed and what would happen without the regression towards the mean, rather they follow a linear trend along a line that represents proportianality between the $y=x$ line and the overall mean line, just as predicted by Galton. The term regression towards the mean (and variants) is sometimes used for other concepts (some closer related to the original than others) as can be seen in the above article, and that may be where some of the confusion comes from.

• I think you are misinterpreting the plots. i think the one on the left is outcome verses prediction and the second is outcome verses residuals. So the OP is right that the residuals look peculiar because they do not scatter randomly across values of the outcome but rather have a linear trend. Regression toward the mean is seen easily in simple linear regression when you plot the line on covariate vs outcome axes. But that is not what is shown in either graph and there are 4 predictor covariates involved. Sep 25, 2012 at 20:33
• @MichaelChernick, what you say is how I interpreted the plots. It is much more common to plot predicted vs. residuals (which will be independent) than outcome vs. residuals (which will be correlated as seen). My interpretation can be seen in the accepted answer above (but the accepted answer went the extra step of showing a demonstration). Sep 26, 2012 at 15:33
• Yes that is fine. I think it is a simplified way of getting an important point across about what could be deceptive in a plot as csgillispie demonstrated. But I am not satisfied with the regression toward the mean explanation because the plot is a projection onto a plane of residuals verses outcome and not predicted values versus outcome and the residuals depend on 4 predictors rather than 1. Sep 26, 2012 at 15:59
• @MichaelChernick, see the above edit to my response in answer to your comments. I think it is possibe that you are thinking of regression towards the mean in a different context than I am, so I added more information and a link. Sep 26, 2012 at 17:55


text:
# [R] Trying to understand the magic of lm (Still trying)

Sorkin, John j@ork|n @end|ng |rom @om@um@ry|@nd@edu
Tue May 14 04:01:03 CEST 2019

Terry ,

Thank you. Many years ago I took a course you taught in which you explained how to conduct survival analyses using S. The course was very useful, as was the email you sent me today. If you find a place where you can store your lecture notes, please send me the URL.

I believe that there is a great need for someone to explain not just how to write a package, but generally how to write a function that checks the parameters passed to it, that uses the parameters in a manner that allows the output of the function to produce output that informs the function users of the call to the function, etc. While these steps are needed when one writes a package, they should be taught as a matter of good coding practice when anyone writes a function that will be used more than once. Many years ago when I was a mainframe system programmer, it was de rigueur that one learned (and used) certain standards about saving registers at the beginning of a function and restoring them at the end of the function. The same should be true for all R functions; certain standardized, well described steps should be considered a part of writing any function. The problem, at least from my perspective, is that there is no commonly recognized document that explains the steps clearly.

Thank you,

John

John David Sorkin M.D., Ph.D.
Professor of Medicine
Chief, Biostatistics and Informatics
University of Maryland School of Medicine Division of Gerontology and Geriatric Medicine
Baltimore VA Medical Center
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
(Phone) 410-605-7119
(Fax) 410-605-7913 (Please call phone number above prior to faxing)

________________________________
From: Therneau, Terry M., Ph.D. <therneau using mayo.edu>
Sent: Monday, May 13, 2019 9:29 AM
To: r-help using r-project.org; Sorkin, John
Subject: Re: [R] Trying to understand the magic of lm (Still trying)

John,

The text below is cut out of a "how to write a package" course I gave at the R conference in Vanderbilt.   I need to find a home for the course notes, because it had a lot of tidbits that are not well explained in the R documentation.
Terry T.

----

Model frames:
One of the first tasks of any modeling routine is to construct a special data frame containing the covariates that will be used, via a call to the model.frame function. The code to do this is found in many routines, and can be a little opaque on first view. The obvious code would be
\begin{verbatim}
coxph <- function(formula, data, weights, subset, na.action,
init, control, ties= c("efron", "breslow", "exact"),
singular.ok =TRUE, robust=FALSE,
model=FALSE, x=FALSE, y=TRUE,  tt, method=ties, ...) {

mf <- model.frame(formula, data, subset, weights, na.action)
\end{verbatim}
since those are the coxph arguments that are passed forward to the model.frame routine.  However, this simple approach will fail with a not found'' error message if any of the data, subset, weights, etc. arguments are missing. Programs have to take the slightly more complicated approach of constructing a call.
\begin{verbatim}
Call <- match.call()
indx <- match(c("formula", "data", "weights", "subset", "na.action"),
names(Call), nomatch=0)
if (indx[1] ==0) stop("A formula argument is required")
temp <- Call[c(1,indx)]  # only keep the arguments we wanted
temp[[1]] <- as.name('model.frame')  # change the function called
mf <- eval(temp, parent.frame())

Y <- model.response(mf)
etc.
\end{verbatim}

We start with a copy of the call to the program, which we want to save anyway as documentation in the output object. Then subscripting is used to extract only the portions of the call that we want, saving the result in a temporary. This is based on the fact that a call object can be viewed as a list whose first element is the name of the function to call, followed by the arguments to the call. Note the use of \code{nomatch=0}; if any arguments on the list are missing they will then be missing in \code{temp}, without generating an error message. The \mycode{temp} variable will contain a object of type call'', which is an unevaluated call to a routine.  Finally, the name of the function to be called is changed from coxph'' to model.frame'' and the call is evaluated.  In many of the core routines the result is stored in a variable m''.  This is a horribly short and non-descriptive name. (The above used mf which isn't a much better.)  Many routines also use m'' for the temporary variable leading to \code{m <- eval(m, parent.frame())}, but I think that is unnecessarily confusing.

The list of names in the match call will include all arguments that should be evaluated within context of the named dataframe. This can include more than the list above, the survfit routine for instance has an optional argument id'' that names an identifying variable (several rows of the data may represent a single subject), and this is included along with formula'' etc in the list of choices in the match function.  The order of names in the list makes no difference.  The id is later retrieved with \code{model.extract(m, 'id')}, which will be NULL if the argument was not supplied. At the time that coxph was written I had not caught on to this fact and thought that all variables that came from a data frame had to be represented in the formula somehow, thus the use of \code{cluster(id)} as part of the formula, in order to denote a grouping variable.

On 5/11/19 5:00 AM, r-help-request using r-project.org<mailto:r-help-request using r-project.org> wrote:

A number of people have helped me in my mission to understand how lm (and other fucntions) are able to pass a dataframe and then refer to a specific column in the dataframe. I thank everyone who has responded. I now know a bit about deparse(substitute(xx)), but I still don't fully understand how it works. The program below attempts to print a column of a dataframe from a function whose parameters include the dataframe (df) and the column requested (col). The program works fine until the last print statement were I receive an error,  Error in [.data.frame(df, , col) : object 'y' not found . I hope someone can explain to me (1) why my code does not work, and (2) what I can do to fix it.

[[alternative HTML version deleted]]

More information about the R-help mailing list


text:
Chemical Sciences: A Manual for CSIR-UGC National Eligibility Test for Lectureship and JRF/Rydberg constant

The Rydberg constant, named after physicist Johannes Rydberg, is a physical constant that apperas in the Rydberg formula. It was discovered when measuring the spectrum of hydrogen, and building upon results from Anders Jonas Ångström and Johann Balmer. Each chemical element has its own Rydberg constant, which can be derived from the "infinity" Rydberg constant.

The Rydberg constant is one of the most well-determined physical constants with a relative experimental uncertainty of less than 7 parts per trillion. The ability to measure it directly to such a high precision confirms the proportions of the values of the other physical constants that define it.

For a series of discrete spectral lines emitted by atmoic hydrogen,

${\displaystyle {\frac {1}{\lambda }}=R\left({\frac {1}{m^{2}}}-{\frac {1}{n^{2}}}\right)}$.

The "infinity" Rydberg constant is (according to 2002 CODATA results):

${\displaystyle R_{\infty }={\frac {m_{e}e^{4}}{(4\pi \epsilon _{0})^{2}\hbar ^{3}4\pi c}}=1.0973731568525(73)\cdot 10^{7}\,\mathrm {m} ^{-1}}$
where
${\displaystyle \hbar \ }$ is the reduced Planck's constant,
${\displaystyle m_{e}\ }$ is the rest mass of the electron,
${\displaystyle e\ }$ is the elementary charge,
${\displaystyle c\ }$ is the speed of light in vacuum, and
${\displaystyle \epsilon _{0}\ }$ is the permittivity of free space.

This constant is often used in atomic physics in the form of an energy:

${\displaystyle hcR_{\infty }=13.6056923(12)\,\mathrm {eV} \equiv 1\,\mathrm {Ry} }$

The "infinity" constant appears in the formula:

${\displaystyle R_{M}={\frac {R_{\infty }}{1+{\frac {m_{e}}{M}}}}}$
where
${\displaystyle R_{M}}$ is the Rydberg constant for a certain atom with one electron with the rest mass ${\displaystyle m_{e}\ }$
${\displaystyle M\ }$ is the mass of its atomic nucleus.

Alternate expressions

The Rydberg constant can also be expressed as the following equations.

${\displaystyle R_{\infty }={\frac {\alpha ^{2}m_{e}c}{4\pi \hbar }}={\frac {\alpha ^{2}}{2\lambda _{e}}}}$

and

${\displaystyle hcR_{\infty }={\frac {hc\alpha ^{2}}{2\lambda _{e}}}={\frac {hf_{C}\alpha ^{2}}{2}}={\frac {\hbar \omega _{C}}{2}}\alpha ^{2}}$

where

${\displaystyle h\ }$ is Planck's constant,
${\displaystyle c\ }$ is the speed of light in a vacuum,
${\displaystyle \alpha \ }$ is the fine-structure constant,
${\displaystyle \lambda _{e}\ }$ is the Compton wavelength of the electron,
${\displaystyle f_{C}\ }$ is the Compton frequency of the electron,
${\displaystyle \hbar \ }$ is the reduced Planck's constant, and
${\displaystyle \omega _{C}\ }$ is the Compton angular frequency of the electron.

Rydberg Constant for hydrogen

Plugging in the rest mass of an electron and an atomic mass ${\displaystyle M}$ of 1 for hydrogen, we find the Rydberg constant for hydrogen, ${\displaystyle R_{H}}$.

${\displaystyle R_{H}=10967758\pm 1m^{-1}}$

Plugging this constant into the Rydberg formula, we can obtain the emission spectrum of hydrogen.

Derivation of Rydberg Constant

The Rydberg Constant can be derived using Bohr's condition, centripetal acceleration, and Potential Energy of the electron to the nucleus.

Bohr's condition,

${\displaystyle 2\pi r=n\lambda }$

where

${\displaystyle n}$ is some integer
${\displaystyle r}$ is the radius of some atom

Centripetal Acceleration,

${\displaystyle PE={\frac {mv^{2}}{r}}}$

where

${\displaystyle m_{e}\ }$ is the rest mass of the electron,
${\displaystyle v}$ is the electron's velocity

PE of Attraction between Electron and Nucleus

${\displaystyle PE={\frac {e^{2}}{4\pi \epsilon _{o}r^{2}}}}$

where

${\displaystyle e\ }$ is the elementary charge,
${\displaystyle \epsilon _{o}\ }$ is the permittivity of free space.

Firstly we substitute ${\displaystyle \lambda ={\frac {h}{p}}}$ into Bohr's condition, then solve for ${\displaystyle v}$ We obtain ${\displaystyle v^{2}={\frac {n^{2}h^{2}}{4\pi ^{2}r^{2}m^{2}}}}$

We equate centripetal acceleration and attraction between nucleus to obtain ${\displaystyle {\frac {mv^{2}}{r}}={\frac {e^{2}}{4\pi \epsilon _{o}r^{2}}}}$

Substitute ${\displaystyle v^{2}}$ in and solve for ${\displaystyle r}$ we obtain ${\displaystyle r={\frac {n^{2}h^{2}\epsilon _{o}}{\pi me^{2}}}}$

We know that ${\displaystyle E_{total}=-{\frac {e^{2}}{8\pi \epsilon _{o}r}}}$

Substitute ${\displaystyle r}$ into this energy equation and we get ${\displaystyle E_{total}={\frac {-me^{4}}{8\epsilon _{o}^{2}h^{2}}}.{\frac {1}{n^{2}}}}$

Therefore a chance in energy would be ${\displaystyle \Delta E={\frac {me^{4}}{8\epsilon _{o}^{2}h^{2}}}({\frac {1}{n_{initial}^{2}}}-{\frac {1}{n_{final}^{2}}})}$

We simply change the units to wave number (${\displaystyle {\frac {1}{\lambda }}={\frac {E}{hc}}}$) and we get ${\displaystyle \Delta {\tilde {\nu }}={\frac {m_{e}e^{4}}{8\epsilon _{o}^{2}h^{3}c}}({\frac {1}{n_{initial}^{2}}}-{\frac {1}{n_{final}^{2}}})}$ where

${\displaystyle h\ }$ is Planck's constant,
${\displaystyle m_{e}\ }$ is the rest mass of the electron,
${\displaystyle e\ }$ is the elementary charge,
${\displaystyle c\ }$ is the speed of light in vacuum, and
${\displaystyle \epsilon _{o}\ }$ is the permittivity of free space.
${\displaystyle n_{initial}}$ and ${\displaystyle n_{final}}$ being the excited states of the atom

We have therefore find the Rydberg constant for Hydrogen to be

${\displaystyle R_{H}={\frac {me^{4}}{8\epsilon _{o}^{2}h^{3}c}}}$


text:
# Probability question using binomial coefficient

I am trying to solve the following problem :

A biased coin which has P(heads) = p = .7 and p(tails) = q = .3 is tossed 3 times. the coin is tossed in such a way that the outcomes on each toss are independent. we obtain the probability of 0,1,2 and 3 heads using the formula : $$C = n! / (x!(n-x)!)$$

i) P(X=0) = ii) P(X=1) =

now I solved the above question using the formula however I got 1 as my answer and the formula that was mentioned is to find the combinations possible, not the probability. Could anyone explain how I would need to use the above formula to get the answer?

Variable Hint : - x = X - X = number of heads you want to achieve - N = total number of tries (3)

-
Your notation is inconsistent: what are $n,x$ and $X$? –  Ilya Mar 1 '12 at 8:01
@Ilya sorry about that, n is the number of tries (3) x is the number of heads you want to achieve and X = x technically... –  Ahoura Ghotbi Mar 1 '12 at 8:13
Would you fix it now in the original post? –  Ilya Mar 1 '12 at 8:14

You're right, this is just the formula for the number of ways of choosing $x$ out of $n$ tosses. To get the probabilities, you need to multiply this by the probabilities of the individual results. Thus, to get $x$ heads and $n-x$ tails out of $n$ tosses, you have $\binom nx$ ways of arranging the $x$ heads among the $n$ tosses, and for each of these arrangements the probability for it to occur contains a factor $p$ for each heads and a factor $q$ for each tails and is therefore $p^xq^{n-x}$. The probability for all $\binom nx$ of the events is therefore $\binom nx p^xq^{n-x}$. You can check this result by using the binomial expansion to find
$$\sum_{x=0}^n\binom nxp^xq^{n-x}=(p+q)^n=1^n=1\;,$$
so the total probability for any number of heads from $0$ to $n$ to occur is $1$, as it should be.


text:
The accounts payable turnover ratio treats net credit purchases as equal to the cost of goods sold (COGS) plus ending inventory, less beginning inventory. This figure, otherwise called total purchases, serves as the numerator in the accounts payable turnover ratio.

Most general purpose financial statements do not include total net purchases as a figure, but its components can be found separately in the statements.

## Net Credit Purchases

The specific calculation for net credit purchases – sometimes referred to as total net payables – might vary from company to company. Much also depends on the nature of the business; a business with many types of credit accounts and many types of operations has a more complex calculation for net credit purchases.

A baseline equation can be written as:

 \begin{aligned} &\text{Net Credit Purchases} = \text{COGS} + \text{Ending Inventory} - \text{SI} \\ &\textbf{where:} \\ &\text{COGS} = \text{Cost of goods sold} \\ &\text{SI} = \text{Starting inventory} \\ \end{aligned}

Payment requirements also vary among suppliers. It is not always the case that lower net credit purchases – which relates to a lower accounts payable turnover ratio – is a sign of poor debtor practices by the firm.

## Purpose of the Accounts Payable Turnover Ratio

Analysts use the accounts payable turnover ratio and its cousin, the accounts receivable turnover ratio, to measure the liquidity and operational efficiency of a company. In a vacuum, a higher ratio is a sign of speedy payment for creditor services.

This formula is very similar to the better-known accounts payable days formula. Lenders and suppliers are most interested in quality accounts payable practices since they have to assume counterparty risk when fronting cash or materials to the firm.


text:
# Predicting Probabilities and Outcomes with Estimated Models

Once a model has been estimated, it can be used to predict probabilities and / or outcomes for a set of alternatives. This vignette demonstrates examples of how to so using the predict() method along with an estimated model.

You can make predictions for any set of alternatives, so long as the columns in the alternatives correspond to estimated coefficients in your model. By default, if no new data are provided via the newdata argument, then predictions will be made for the original data used to estimate the model.

Predictions can be made using both preference space and WTP space models, as well as multinomial logit and mixed logit models. For mixed logit models, heterogeneity is modeled by simulating draws from the population estimates of the estimated model.

# Predicting probabilities

## Preference space models

In the example below, a preference space MNL model is estimated (mnl_pref) and then used to predict probabilities for the data used to estimate the model:

library("logitr")

mnl_pref <- logitr(
data    = yogurt,
outcome = 'choice',
obsID   = 'obsID',
pars    = c('price', 'feat', 'brand')
)

probs <- predict(mnl_pref)
#>   obsID predicted_prob
#> 1     1     0.41802407
#> 2     1     0.02118240
#> 3     1     0.23691737
#> 4     1     0.32387615
#> 5     2     0.26643822
#> 6     2     0.02255486

The predict() method returns a data frame containing the observation ID as well as the predicted probabilities. The original data can also be returned in the data frame by setting returnData = TRUE:

probs <- predict(mnl_pref, returnData = TRUE)
#>   obsID predicted_prob price feat brandhiland brandweight brandyoplait choice
#> 1     1     0.41802407   8.1    0           0           0            0      0
#> 2     1     0.02118240   6.1    0           1           0            0      0
#> 3     1     0.23691737   7.9    0           0           1            0      1
#> 4     1     0.32387615  10.8    0           0           0            1      0
#> 5     2     0.26643822   9.8    0           0           0            0      1
#> 6     2     0.02255486   6.4    0           1           0            0      0

To make predictions for a new set of alternatives, use the newdata argument. The example below makes predictions for just two of the choice observations from the yogurt dataset:

data <- subset(
yogurt, obsID %in% c(42, 13),
select = c('obsID', 'alt', 'price', 'feat', 'brand'))

probs_mnl_pref <- predict(
mnl_pref,
newdata = data,
obsID = "obsID"
)

probs_mnl_pref
#>   obsID predicted_prob
#> 1    13     0.43685145
#> 2    13     0.03312986
#> 3    13     0.19155548
#> 4    13     0.33846321
#> 5    42     0.60764778
#> 6    42     0.02602007
#> 7    42     0.17803313
#> 8    42     0.18829902

The ci argument can be used to obtain upper and lower bounds of a confidence interval for predicted probabilities, which are estimated using the Krinsky and Robb parametric bootstrapping method (Krinsky and Robb 1986). For example, a 95% CI is obtained with ci = 0.95:

probs_mnl_pref <- predict(
mnl_pref,
newdata = data,
obsID = "obsID",
ci = 0.95
)

probs_mnl_pref
#>   obsID predicted_prob predicted_prob_lower predicted_prob_upper
#> 1    13     0.43685145           0.41490293           0.45807457
#> 2    13     0.03312986           0.02605820           0.04220765
#> 3    13     0.19155548           0.17660037           0.20716517
#> 4    13     0.33846321           0.31736913           0.35773877
#> 5    42     0.60764778           0.57204770           0.64057358
#> 6    42     0.02602007           0.01872655           0.03732723
#> 7    42     0.17803313           0.16220968           0.19451696
#> 8    42     0.18829902           0.16778560           0.20931234

## WTP space models

WTP space models can also be used to predict probabilities. In the example below, a WTP space model is estimated and used to predict probabilities for the same data data frame as in the previous examples:

mnl_wtp <- logitr(
data     = yogurt,
outcome  = 'choice',
obsID    = 'obsID',
pars     = c('feat', 'brand'),
scalePar = 'price',
numMultiStarts = 10
)

probs_mnl_wtp <- predict(
mnl_wtp,
newdata = data,
obsID   = "obsID",
ci      = 0.95
)

probs_mnl_wtp
#>   obsID predicted_prob predicted_prob_lower predicted_prob_upper
#> 1    13     0.43686141           0.41626125           0.45759058
#> 2    13     0.03312947           0.02631329           0.04204450
#> 3    13     0.19154829           0.17587351           0.20824388
#> 4    13     0.33846083           0.31824968           0.35810533
#> 5    42     0.60767120           0.57426109           0.63738465
#> 6    42     0.02601800           0.01817677           0.03564045
#> 7    42     0.17802363           0.16251472           0.19536331
#> 8    42     0.18828717           0.16746411           0.20889147

Here is a bar chart comparing the predicted probabilities from the preference space and WTP space models. Since both models are equivalent except in different spaces, the predicted probabilities are identical:

library("ggplot2")

probs <- rbind(probs_mnl_pref, probs_mnl_wtp)
probs$model <- c(rep("mnl_pref", 8), rep("mnl_wtp", 8)) probs$alt <- rep(c("dannon", "hiland", "weight", "yoplait"), 4)
probs$obs <- paste0("Observation ID: ", probs$obsID)
ggplot(probs, aes(x = alt, y = predicted_prob, fill = model)) +
geom_bar(stat = 'identity', width = 0.7, position = "dodge") +
geom_errorbar(aes(ymin = predicted_prob_lower, ymax = predicted_prob_upper),
width = 0.2, position = position_dodge(width = 0.7)) +
facet_wrap(vars(obs)) +
scale_y_continuous(limits = c(0, 1)) +
labs(x = 'Alternative', y = 'Expected Choice Probabilities') +
theme_bw()

# Predicting outcomes

The predict() method can also be used to predict outcomes by setting type = "outcome" (the default is "prob" for predicting probabilities). In the examples below, outcomes are predicted using the same preference space and WTP space models as in the previous examples. The returnData argument is also set to TRUE so that the predicted outcomes can be compared to the actual choices made:

outcomes_pref <- predict(
mnl_pref,
type = "outcome",
returnData = TRUE
)

#>   obsID predicted_outcome price feat brandhiland brandweight brandyoplait
#> 1     1                 1   8.1    0           0           0            0
#> 2     1                 0   6.1    0           1           0            0
#> 3     1                 0   7.9    0           0           1            0
#> 4     1                 0  10.8    0           0           0            1
#> 5     2                 0   9.8    0           0           0            0
#> 6     2                 0   6.4    0           1           0            0
#>   choice
#> 1      0
#> 2      0
#> 3      1
#> 4      0
#> 5      1
#> 6      0

outcomes_wtp <- predict(
mnl_wtp,
type = "outcome",
returnData = TRUE
)

#>   obsID predicted_outcome feat brandhiland brandweight brandyoplait scalePar
#> 1     1                 1    0           0           0            0      8.1
#> 2     1                 0    0           1           0            0      6.1
#> 3     1                 0    0           0           1            0      7.9
#> 4     1                 0    0           0           0            1     10.8
#> 5     2                 1    0           0           0            0      9.8
#> 6     2                 0    0           1           0            0      6.4
#>   choice
#> 1      0
#> 2      0
#> 3      1
#> 4      0
#> 5      1
#> 6      0

The accuracy of each model can be computed by dividing the number of correctly predicted choices by the total number of choices:

chosen_pref <- subset(outcomes_pref, choice == 1)
chosen_pref$correct <- chosen_pref$choice == chosen_pref$predicted_outcome accuracy_pref <- sum(chosen_pref$correct) / nrow(chosen_pref)
accuracy_pref
#> [1] 0.3888889

chosen_wtp <- subset(outcomes_wtp, choice == 1)
chosen_wtp$correct <- chosen_wtp$choice == chosen_wtp$predicted_outcome accuracy_wtp <- sum(chosen_wtp$correct) / nrow(chosen_wtp)
accuracy_wtp
#> [1] 0.3909619

These results show that both models correctly predicted choice for approximately 39% of the observations in the yogurt data frame, which is significantly better than random (25%).

# References

Krinsky, Itzhak, and A Leslie Robb. 1986. “On Approximating the Statistical Properties of Elasticities.” The Review of Economics and Statistics, 715–19.


text:
# Translating an object along its heading

Solved! I was not applying the transformations in the proper order.

I am working on a simulation that requires me to have several objects moving around in 3D space (text output of their current position on the grid and heading is fine, I do not need graphics), and I am having some trouble getting objects to move along their relative headings.

I have a basic understanding of vectors and matrices. I am using a vector to represent their position, and I am also using Euler Angles. I can translate one of my entities with a matrix along whatever axis, and I can alter their heading.

For example, if I have an entity at (order is XYZ) 1, 1, 1, with a heading of 0, I can apply a translation matrix to get them to talk to 1, 1, 2 fine. However, if I change their heading to 270, they still walk to 1, 1, 3, instead of 2, 1, 2 as I desire.

I have a feeling that my problem lies in not translating my matrix from world space to object space, but I am not sure how to go about that. How can I do this?

Addition: I am using 3D vectors to represent their current position and their heading (using the three euler angles).

For now, all I want to do is have an entity walk in a square, reporting their current position at each step. So, assuming it starts at 10, 10, 10 I want it to walk as follows:

10,10,10 -> 10, 10, 15
10, 10, 15 -> 5, 10, 15
5, 10, 15 -> 5, 10, 10
5, 10, 10 -> 10, 10, 10

My 1 Z unit translation matrix is as follows:

[1 0 0 0]
[0 1 0 0]
[0 0 1 1]
[0 0 0 1]

My rotation matrix is as follows:

[0 0 1 0]
[0 1 0 0]
[-1 0 0 0]
[0 0 0 1]

If you have a rotation matrix that represents the current rotation of your object, the 3rd row/column represents a vector pointing in the direction the object is facing (heading). So translating the position by a factor of the 3rd row/column will move the position in a direction you are heading (local space forward direction).

//assuming row major matrix & Y up system:
position += -3drRowVector * distanceToMove;

if you are using a Z up system and/or a column Major matrix, this would need adjustment but the principle is the same.

• Actually, this was very helpful and resolved it better than what I was doing. Thank you! – Kuros Nov 26 '11 at 21:41


text:
## Algebra 2 (1st Edition)

Switching the elements of the domain and the range, we obtain: $w=0.5l+3\\w-3=0.5l\\l=2w-6$


text:
# Understanding container networking

Five questions for Lee Calcote on the scaling and performance of container architectures.

June 1, 2017
Construction Containers (source: Hans)

I recently sat down with Lee Calcote, senior director of technology strategy at SolarWinds, to talk about the benefits of container networks. Here are some highlights from our chat.

## What is container networking? How are people deploying container networks?

Much of what container networking is today revolves around core Linux network technologies, whether that be iptables for port-forwarding, firewalling and network address translation, or ipvs for load-balancing and service abstraction (virtual IP addressing). These battle-tested technologies are old friends of systems engineers, who have leveraged these kernel capabilities as they’ve built container engines and orchestrators.

## Learn faster. Dig deeper. See farther.

Join the O'Reilly online learning platform. Get a free trial today and find answers on the fly, or master something new and useful.

To date, container networking has largely been focused on simple network services like connectivity, IP addressing (IPAM), (domain) name services, and load-balancing. Beyond connectivity, most higher-level network services—like quality of service (QoS), virtual private networking, security policy (complex and dynamic firewalling), and topology optimization—are still emerging. So far, connectivity has largely equated to use of Linux bridges and network overlays, with VXLAN being a popular protocol. These common choices are in the face of a style of networking that’s arguably more straightforward in its approach: layer 3 networking.

Layer 3 networking involves routing as the connectivity method; BGP is the most popular protocol. I see layer 3 routing selected far less often than overlays as the deployment approach of choice, in part because public clouds don’t necessarily make layer 3 routing an easy choice. The convenience of overlays being at the fingertips of developers means that their deployments outstrip underlay deployments, despite the higher scale and efficiency provided by routing.

## What do engineers need to understand about containers and networking? And how does service discovery relate to them?

The need to understand container networking in-depth is really a factor of the architecture of the application being deployed. Whether engineers are deploying containers onto single hosts or multi-container applications across hosts will influence their need to consider networking and related services. The more distributed the application design, the more the network comes into focus.

Conceptually, developers using network overlays and the inherent load-balancing afforded through “service” constructs in any of the popular container orchestrators need a lesser understanding of networking intricacies. Through overlays, they will be able to interconnect multiple hosts (and their containers) within a cluster (whether under management by a container orchestrator or not).

Service discovery plays an important function in helping various components of a multi-container application identify one another and communicate. In clusters managed by a container orchestrator, service discovery is a built-in capability, wherein new container application services are announced and centrally tracked. The service discovery function is often delivered through domain name services (DNS), a common network service.

## Are the approaches to container networking compatible across different container technologies?

Yes, there are a number of container projects to consider compatibility! There are two proposed standards for configuring network interfaces for Linux containers: the container network model (CNM) and the container network interface (CNI). While there are various plugins created to integrate with each, the latter has been somewhat ubiquitously adopted across the container orchestration landscape. In fact, in part because of its broad compatibility across the container ecosystem, I’ve been working within the Cloud Native Computing Foundation (CNCF) to have CNI adopted as the 10th project within the foundation.

## What are some strategies and tricks for optimizing the performance of containerized architectures?

Interestingly, performance is a key factor to consider when deploying container networks. There are a number of different types of network plugins to use and possible configurations that have significant ramifications on performance (most notably throughput). In my role at SolarWinds, I’m having tooling created to educate engineers with respect to the nuances of these choices and their impact on network performance. I think people will be surprised at what they learn: there’s a cost to the convenience of network overlays.

## You’re speaking at the O’Reilly Velocity Conference in San Jose this June. What presentations are you looking forward to attending while there?

Surprisingly, this is my first Velocity conference, and it will certainly not be my last. The list of talks and workshops on the conference schedule is amazing! There are a couple of sessions—one by Sasha Goldshtein (Sela Group) and one by Brendan Gregg (Netflix)—on eBPF (extended Berkeley Packet Filter), which is a technology that piques my interest as a performant way to inject tracing into the kernel. In my mind, eBPF opens a new world of performance analysis of Linux systems from kernel to user-space frameworks. A number of monitoring vendors have begun to incorporate this technology into their offerings. I’m excited about the broad use cases of eBPF as virtualized in-kernel IO services for tracing, analytics, monitoring, security, and networking functions.

Post topics: Infrastructure
Share:


text:
Volume 340 - The 39th International Conference on High Energy Physics (ICHEP2018) - Parallel: Quark and Lepton Flavor Physics
Time-dependent $CP$-violation measurements in $B\rightarrow DX$ decays at LHCb
A. Birnkraut* on behalf of the LHCb collaboration
*corresponding author
Full text: pdf
Published on: August 02, 2019
Abstract
Measurements of the time-dependent $C\!P$-violation observables in $B^0\!\to D^\mp\pi^\pm$ and $B^0_s\!\to D_s^\mp K^\pm$ decys are reported. The decays are reconstructed in a dataset collected with the LHCb experiment in $pp$ collisions at centre-of-mass energies of $7$ and $8\,\text{TeV}$ corresponding to an integrated luminosity of$3\,\text{fb}^{-1}$. For $B^0\!\to D^\mp\pi^\pm$ decays, the $C\!P$-observables are measured to be $S_f = 0.058 \pm 0.020 \pm 0.011$ and $S_{\bar{f}} = 0.038 \pm 0.020 \pm 0.007$. For $B^0_s\!\to D_s^\mp K^\pm$ decays, $C_f = 0.730 \pm 0.142 \pm 0.045$, $S_f = -0.519 \pm 0.202 \pm 0.070$, $S_{\bar{f}} = -0.489 \pm 0.196 \pm 0.068$, $A_f^{\Delta\Gamma} = 0.387 \pm 0.277 \pm 0.153$ and $A_{\bar{f}}^{\Delta\Gamma} = 0.308 \pm 0.275 \pm 0.152$ are determined, where the first uncertainties are statistical and the second systematic. Using these observables the CKM angle $\gamma$ is constrained at \SI{68}{\percent} CL to be $[5,86]{}^{\circ}$ and $\left(128^{+17}_{-22}\right)^{\circ}$ modulo $180^\circ$ for $B^0\!\to D^\mp\pi^\pm$ and $B^0_s\!\to D_s^\mp K^\pm$ decays, respectively.
DOI: https://doi.org/10.22323/1.340.0246
How to cite

Metadata are provided both in "article" format (very similar to INSPIRE) as this helps creating very compact bibliographies which can be beneficial to authors and readers, and in "proceeding" format which is more detailed and complete.

Open Access


text:
# Sum of residuals and Matrix calculus (step by step)

1. Write the sum of residuals in matrix form.

Attempt: $(y-X\boldsymbol{\beta})^T(y-X\boldsymbol{\beta}) = y^Ty-\boldsymbol{\beta}^TX^Ty-y^TX\boldsymbol{\beta}+\boldsymbol{\beta}^TX^TX\boldsymbol{\beta} = y^Ty-2y^TX\boldsymbol{\beta}+\boldsymbol{\beta}^TX^TX\boldsymbol{\beta}.$

1. Minimize this and verify that $\hat{\boldsymbol{\beta}} = (X^TX)^{-1}X^Ty$.

Attempt: $\frac{\partial SSR(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = -2y^TX+2X^TX\boldsymbol{\beta} = 0 \rightarrow X^TX\boldsymbol{\beta}=y^TX \rightarrow \hat{\boldsymbol{\beta}} = (X^TX)^{-1}y^TX = (X^TX)^{-1}X^Ty.$

I haven't studied matrix calculus, so I am a little bit confused about the step in calculation. In the first problem, could you show me which rule is used for the first equality in the equation. And in the second problem, I am a little confused about the first step of differentiation.

I really appreciate if you show the calculation step by step.

Let $\mathbf A,\mathbf B$ be $m\times n$ matrices (or vectors is either $m$ or $n$ is $1$), \begin{align} (\mathbf A+\mathbf B)^T&=\mathbf A^T+\mathbf B^T \tag{1}\\ (\mathbf A\mathbf B)^T&=\mathbf B^T\mathbf A^T \tag{2} \end{align}
Thus, \begin{align} (\mathbf y-\mathbf X\beta)^T(\mathbf y-\mathbf X\beta)&=(\mathbf y^T-(\mathbf X\beta)^T)(\mathbf y-\mathbf X\beta)\\ &=(\mathbf y^T-\beta^T\mathbf X^T)(\mathbf y-\mathbf X\beta)\\ &=\mathbf y^T(\mathbf y-\mathbf X\beta)-\beta^T\mathbf X^T(\mathbf y-\mathbf X\beta)\\ &=\mathbf y^T\mathbf y-\mathbf y^T\mathbf X\beta-\beta^T\mathbf X^T\mathbf y+\beta^T\mathbf X^T\mathbf X\beta \\ &=\mathbf y^T\mathbf y-2\mathbf y^T\mathbf X\beta+\beta^T\mathbf X^T\mathbf X\beta \tag{3} \end{align} where line 1 uses $(1)$, line 2 uses $(2)$, and the last line follows from the fact that $\mathbf y^T\mathbf X\beta$ and $\beta^T\mathbf X^T\mathbf y$ are both $1\times1$ scalars.
Let $\mathbf a,\mathbf x$ be $n\times 1$ vectors and $\mathbf A$ a symmetric $n\times n$ matrix. Matrix calculus has the following rules: \begin{align} \frac{\mathrm d\ \mathbf a^T\mathbf z}{\mathrm d\ \mathbf z}&=\mathbf a \tag{4} \\ \frac{\mathrm d\ \mathbf z^T\mathbf A\mathbf z}{\mathrm d\ \mathbf z}&=2\mathbf A\mathbf z \tag{5} \end{align}
Applying these to differentiating $(3)$ with respect to $\mathbf\beta$, we get the first order condition: $$-2\mathbf X^T\mathbf y+2\mathbf X^T\mathbf X\beta=0$$ Solving for $\beta$, we get the usual OLS formula.


text:
### Is There Any Difference Between Flow Weighting Policies for Cash and Securities?

##### I hope this has been helpful! Let me know your thoughts!
Insert math as
$${}$$


text:
# How do use the first derivative test to determine the local extrema  f(x) = 3x^4-8x^3-90x^2+50?

Oct 24, 2015

Find the critical numbers and test for min/max using the first derivative test.

#### Explanation:

$f \left(x\right) = 3 {x}^{4} - 8 {x}^{3} - 90 {x}^{2} + 50$

$\text{dom} \left(f\right) = \left(- \infty , \infty\right)$

$f ' \left(x\right) = 12 {x}^{3} - 24 {x}^{2} - 180 x$

$f ' \left(x\right)$ is never undefined

$f ' \left(x\right) = 12 x \left({x}^{2} - 2 x - 15\right) = 12 x \left(x - 5\right) \left(x + 3\right) = 0$ at $x = - 3 , 0 , 5$

Here is one version of the sign chart for $f ' \left(x\right)$

{: (bb"Intervals:",(-oo,-3),(-3,0),(0,5),(5,oo)), (darr bb"Factors"darr,"========","======","=====","======"), (12x, bb" -",bb" -",bb" +",bb" +"), (x-5,bb" -",bb" -",bb" -",bb" +"), (x+3,bb" -",bb" +",bb" +",bb" +"), ("==========","========","======","=====","======"), (bb"Product"=f'(x),bb" -",bb" +",bb" -",bb" +") :}

At $x = - 3$, the sign of $f ' \left(x\right)$ changes from - to +, (so $f$ changes from decreasing to increasing) so $f \left(- 3\right) = - 301$ is a local minimum.

At $x = 0$, the sign of $f ' \left(x\right)$ changes from + to -, (so $f$ changes from increasing to decreasing) so $f \left(0\right) = 50$ is a local maximum.

At $x = 5$, the sign of $f ' \left(x\right)$ changes from - to +, (so $f$ changes from decreasing to increasing) so $f \left(5\right) = - 1325$ is a local minimum.


text:
10k views

What's your favorite equation, formula, identity or inequality? [closed]

Certain formulas I really enjoy looking at like the Euler-Maclaurin formula or the Leibniz integral rule. What's your favorite equation, formula, identity or inequality?
5k views

Examples of seemingly elementary problems that are hard to solve?

I'm looking for a list of problems such that a) any undergraduate student who took multivariable calculus and linear algebra can understand the statements, (Edit: the definition of understanding here ...
5k views

Is there a dense subset of the real plane with all pairwise distances rational?

I heard the following two questions recently from Carl Mummert, who encouraged me to spread them around. Part of his motivation for the questions was to give the subject of computable model theory ...
2k views

Status of PL topology

I posted this question on math stackexchange but received no answers. Since I know there are more people knowledgeable in geometric and piecewise-linear (PL) topology here, I'm reposting the question. ...
3k views

Open problems in Euclidean geometry ?

Which are some (research level) open problems in Euclidean geometry ? (Edit: I ask just out of curiosity, to understand how -and if- nowadays this is not a "dead" field yet) I should clarify a ...
2k views


text:
# zero locus of a sheaf homomorphism

The title says it all.

I'm just starting to go through the existence-proof of the quot scheme (http://www.math.utah.edu/~bertram/courses/hilbert/ps/hilbert.ps). On page 7, almost at the bottm of the page a scheme is defined as the zero locus of a homomorphism of sheaves.

What exactly is the zero locus of a sheaf homomorphism?

Greetings

Dan

-
I would guess it's the set of points $p$ on the base where the stalk of the morphism is the zero morphism. – Andrew Nov 14 '12 at 22:37


text:
This topic is 4916 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Found this out at university today, not one of the lecturers knew about it, nor the tutors (one of the students did it in a tutorial) anyway, this is completly valid code in C/C++:
printf("how"
"are"
"you?");

C concats the strings automagically for you. so;

void doStuff(char * text)
{
// blag
}

void main()
{
doStuff("I" "am" "fine");
}

is also fine. Weird huh? maybe it's just me, but to me, thats really really bad, the compiler effectivly changes your code.

##### Share on other sites
Well think about what you are saying there.

Your memory locations will look something like this (Char* purechar Char* purechar Char* purechar )

None of those has a \0 on the end of it so it'll read til it doesn't find characters any more. So it skips to the second group of characters. Does it output "Iamfine" or does it output it with spaces?

Remember the compiler never officially changes your code, it just interprets it, and if this functionality is in here (and it appears to be) it was supposed to be here, especially in something so overly used as printf.

##### Share on other sites
I use that feature frequently for long constant strings. I hate having my constant messages stretch right off the side of the screen so I do that. ;)
And like was said before thats how the compiler interprets it. It is just a long string. If you put ,'s or ;'s in between then it would be interpreted differently.

##### Share on other sites
I knew about that. I think it's great for breaking apart long lines, to keep the code neat and readable. Don't remember how I first found out about it though.

Then again, I haven't really used it since I started using C++ streams, I just do something like this:

cout << "I"
<< " am "
<< " fine " << endl;

In order to break up any long character strings and keep things readable.

Fun stuff!

##### Share on other sites
Quote:
 Original post by RipTornmaybe it's just me, but to me, thats really really bad, the compiler effectivly changes your code.

I'm not sure why you think it changes your code; it's just a feature of the laguage like anything else, you just haven't run into a good use for it yet. Most-commonly, you'll only be using it on either really long strings that would extend very far on one line, or if you are working with the preprocessor and want to concatenate two strings together. One quick example use would be:

#include <iostream>#define ERROR_MESSAGE( error_message ) "Error: " #error_message int main(){  ::std::cout << ERROR_MESSAGE( divide by zero );  // Same as  ::std::cout << "Error: divide by zero";}

Quote:
 Original post by RipTornvoid main(){ doStuff("I" "am" "fine");}is also fine.

Actually that is not fine, since void main is neither valid C nor C++. The main function must have the return type int in C and C++ (though many non-compliant compilers support void main, it is not standard).

##### Share on other sites
It's not weird at all, it's pretty useful in fact and is fairly widely used. I'm surprised nobody at your university had seen it before. It's particularly useful for doing something like this:

const char* helpText = "This is some multi-line help text that you wouldn't want to squeeze onto one \n""line in the source code. Think about how you'd have to lay out a string like this \n""if C/C++ didn't support automatic concatenation of string literals. The concatenation \n""happens at compile time, not at runtime, so the compiler isn't changing your code at \n""all, it's just saving you from having lines hundreds of characters long in your source. \n";

##### Share on other sites
I use it a occasionally. It is handy for building strings with macros. Saying the the compiler changes your code is not correct, since putting two strings together like that tells the compiler to concatenate them.

The only drawback is that bugs like this happen a lot:
char * array[] ={    "1",    "2",    "3",    "4"    "5",    "6"};
The above array has only five elements. Oops.

##### Share on other sites
Quote:
 Original post by Polymorphic OOPActually that is not fine, since void main is neither valid C nor C++. The main function must have the return type int in C and C++ (though many non-compliant compilers support void main, it is not standard).
Legality of void main().
I just felt like counter-nitpicking..

##### Share on other sites
Quote:
 Original post by cgoatI knew about that. I think it's great for breaking apart long lines, to keep the code neat and readable. Don't remember how I first found out about it though.Then again, I haven't really used it since I started using C++ streams, I just do something like this:cout << "I"<< " am "<< " fine " << endl;In order to break up any long character strings and keep things readable.Fun stuff!

Not that this is something that really needs optimizing but still, using streams for this is horrendously inefficient by comparison since string literals are concatenated by the compiler at compile time and so there is no runtime cost whereas doing it this way requires a function call for every concatenation.

##### Share on other sites
I didn't mean to imply that the iostreams were better or anything... just a comment on how I hadn't used that particular language feature since starting to use iostreams more often.

1. 1
2. 2
3. 3
4. 4
frob
14
5. 5

• 16
• 13
• 20
• 12
• 19
• ### Forum Statistics

• Total Topics
632168
• Total Posts
3004543

×


text:
## Marks 1

More
A discrete time all-pass system has two of its poles at 0.25$$\angle 0^\circ$$ and $$\angle 30^\circ$$. Which one of t...
GATE ECE 2018
A discrete-time signal$$x\left[ n \right]\, = \delta \left[ {n - 3} \right]\, + 2\delta \left[ {n - 5} \right]$$ has z-t...
GATE ECE 2016 Set 3
Consider the sequence $$x\left[ n \right]$$= $${a^n}u\left[ n \right] + {b^{\partial n}}u\left[ n \right]$$ , where u[n...
GATE ECE 2016 Set 1
Two casual discrete-time signals $$x\left[ n \right]$$ and $$y\left[ n \right]$$ =$$\sum\limits_{m = 0}^n x \left[ m \ri... GATE ECE 2015 Set 2 The sequence x$$\left[ n \right]$$=$${0.5^n}$$u[n], where u$$\left[ n \right]$$is the unit step sequence, is conv... GATE ECE 2014 Set 4 For an all-pass system H(z)=$${{({z^{ - 1}} - b)} \over {(1 - a{z^{ - 1}})}}$$where$$\left| {H({e^{ - j\omega }})} ...
GATE ECE 2014 Set 3
An FIR system is described by the system function $$H(z) = 1 + {7 \over 2}{z^{ - 1}} + {3 \over 2}{z^{ - 2}}$$$GATE ECE 2014 Set 2 Let x$$\left[ n \right]$$ = x$$\left[- n \right]$$ . Let X(z) be the z-transform of x$$\left[ n \right]$$. if 0.5 +j 0.2... GATE ECE 2014 Set 2 If $$x\left[ n \right]$$= $${(1/3)^{\left| n \right|}} - {(1/2)^n}u\left[ n \right]$$, then the region of convergence (R... GATE ECE 2012 Consider the z-transform X(z)=5$${z^2} + 4{z^{ - 1}} + 3;0 The inverse z - transform x$$\,\left[ n \right]$$is ... GATE ECE 2010 The ROC of Z-transform of the discrete time sequence x(n)=$${\left( {{1 \over 3}} \right)^{n}}u(n) - {\left( {{1 \over... GATE ECE 2009 If the region of convergence of $${x_1}\left[ n \right]$$ + $${x_2}\left[ n \right]$$ is 1/3... GATE ECE 2006 The region of convergence of z-transform of the sequence $${\left( {{5 \over 6}} \right)^n}u(n) - {\left( {{6 \over 5}}... GATE ECE 2005 The z transform of a system is H(z) =$${z \over {z - 0.2}}$$. If the ROC is$$\left| {z\,} \right|$$... GATE ECE 2004 The region of convergence of the z- transform of a unit step function is GATE ECE 2001 The z-transform F(z) of the function f(nT) =$${a^{nT}}$$is GATE ECE 1999 The z - transform of the time function$$\sum\limits_{k = 0}^\infty {\delta \left( {n - k} \right)} $$is GATE ECE 1998 ## Marks 2 More The ROC (region of convergence) of the z-transform of a discrete-time signal is represented by the shaded region in the ... GATE ECE 2016 Set 3 A sequence x$$\left[ n \right]$$is specified as$$\left[ {\matrix{ {x\left[ n \right]} \cr {x\left[ {n - 1} \ri... GATE ECE 2016 Set 1 A realization of a stable discrete time system is shown in the figure. If the system is excited by a unit step sequence ... GATE ECE 2015 Set 3 Suppose x $$\left[ n \right]$$ is an absolutely summable discrete-time signal. Its z-transform is a rational function wi... GATE ECE 2015 Set 3 The pole-zero diagram of a causal and stable discrete-time system is shown in the figure. The zero at the origin has mu... GATE ECE 2015 Set 1 For the discrete-time system shown in the figure, the poles of the system transfer function are located at ... GATE ECE 2015 Set 1 The z-transform of the sequence x$$\left[ n \right]$$ is given by x(z)= $${1 \over {{{(1 - 2{z^{ - 1}})}^2}}}$$ , with t... GATE ECE 2014 Set 3 Let $${H_1}(z) = {(1 - p{z^{ - 1}})^{ - 1}},{H_2}(z) = {(1 - q{z^{^{ - 1}}})^{ - 1}}$$ , H(z) =$${H_1}(z)$$ +r $${H_2}$$... GATE ECE 2014 Set 3 The input-output relationship of a causal stable LTI system is given as 𝑦[𝑛] = 𝛼 𝑦[𝑛 − 1] + $$\beta$$ x[n]. If ... GATE ECE 2014 Set 2 Let x $$\left[ n\right]$$= $${\left( { - {1 \over 9}} \right)^n}\,u(n) - {\left( { - {1 \over 3}} \right)^n}u( - n - 1).... GATE ECE 2014 Set 1 In the following network (Fig.1), the switch is closed at t = 0 and the sampling starts from t=0. The sampling frequency... GATE ECE 2008 In the following network (Fig .1), the switch is closed at t = 0- and the sampling starts from t = 0. The sampling frequ... GATE ECE 2008 The z-transform X (z) f a sequence x$$\left[ n \right]$$is given by =$${{0.5} \over {1 - 2{z^{ - 1}}}}$$. It is give... GATE ECE 2007 The z-transform of a signal is given by c(z)=$${1 \over 4}{{{z^{ - 1}}(1 - {z^{ - 4}})} \over {{{(1 - {z^{ - 1}})}^2}}}$...
GATE ECE 1999
The Z-transform of the following real exponential sequence: x(nT) = $${a^n}$$, nT $$\ge$$ 0 =0, nT 0 gives us by...
GATE ECE 1990

### EXAM MAP

#### Graduate Aptitude Test in Engineering

GATE ECE GATE CSE GATE CE GATE EE GATE ME GATE PI GATE IN


text:
# Math Help - Coordinates of Points

1. ## Coordinates of Points

What are the coordinates of point (2,–3) after it is reflected over the
x-axis?

(1) (2,3) (3) (–2,–3)

(2) (–2,3) (4) (–3,2)

2. Originally Posted by magentarita
What are the coordinates of point (2,–3) after it is reflected over the
x-axis?

(1) (2,3) (3) (–2,–3)

(2) (–2,3) (4) (–3,2)
Reflection over the x-axis means:
- The x-coordinate doesn't change
- The y-coordinate changes its sign.

Therefore the answer is (1): P'(2, 3)

3. ## ok...

Originally Posted by earboth
Reflection over the x-axis means:
- The x-coordinate doesn't change
- The y-coordinate changes its sign.

Therefore the answer is (1): P'(2, 3)
I thank you.