text:
I'm an active user on SO, however I just found this site and this is my first question here. I am a self-taught programmer who has been programming for a long time, but mainly just for personal projects. I would like to improve my skills and am open to any suggestions that you may have, but am particularly interested in your thoughts about:

• The number of methods in this class: Too few/too many?
• Method/variable names: Descriptive enough?/too descriptive?
• Code formatting: Any suggestions?
• Any other thoughts?

Full project is hosted on Github.

/******************************************************************************
* v. 0.9.1  15 NOV 2012
* Purpose:  Class to display a custom numberpad on an iPad and properly handle
*           the text input.
* Author:   Louis Nafziger
*
******************************************************************************
*
* This file is part of NumberPad.
*
* NumberPad is free software: you can redistribute it and/or modify
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NumberPad is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU LesserGeneral Public License
*
*****************************************************************************/

#pragma mark - Private methods

@property (nonatomic, weak) id<UITextInput> targetTextInput;

@end

@synthesize targetTextInput;

#pragma mark - Singleton method

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{
});
}

#pragma mark - view lifecycle

// Keep track of the textView/Field that we are editing
selector:@selector(editingDidBegin:)
object:nil];
selector:@selector(editingDidBegin:)
object:nil];
selector:@selector(editingDidEnd:)
object:nil];
selector:@selector(editingDidEnd:)
object:nil];
}

object:nil];
object:nil];
object:nil];
object:nil];
self.targetTextInput = nil;

}

#pragma mark - editingDidBegin/End

// Editing just began, store a reference to the object that just became the firstResponder
self.targetTextInput = nil;
return;
}

}

// Editing just ended.
self.targetTextInput = nil;
}

// A number (0-9) was just pressed on the number pad
if (self.targetTextInput == nil) {
return;
}

NSString *numberPressed  = sender.titleLabel.text;
if ([numberPressed length] == 0) {
return;
}

UITextRange *selectedTextRange = self.targetTextInput.selectedTextRange;
if (selectedTextRange == nil) {
return;
}

[self textInput:self.targetTextInput replaceTextAtTextRange:selectedTextRange withString:numberPressed];
}

// The delete button was just pressed on the number pad
if (self.targetTextInput == nil) {
return;
}

UITextRange *selectedTextRange = self.targetTextInput.selectedTextRange;
if (selectedTextRange == nil) {
return;
}

// Calculate the selected text to delete
UITextPosition  *startPosition  = [self.targetTextInput positionFromPosition:selectedTextRange.start offset:-1];
if (startPosition == nil) {
return;
}
UITextPosition  *endPosition    = selectedTextRange.end;
if (endPosition == nil) {
return;
}
UITextRange     *rangeToDelete  = [self.targetTextInput textRangeFromPosition:startPosition
toPosition:endPosition];

[self textInput:self.targetTextInput replaceTextAtTextRange:rangeToDelete withString:@""];
}

// The clear button was just pressed on the number pad
if (self.targetTextInput == nil) {
return;
}

UITextRange *allTextRange = [self.targetTextInput textRangeFromPosition:self.targetTextInput.beginningOfDocument
toPosition:self.targetTextInput.endOfDocument];

[self textInput:self.targetTextInput replaceTextAtTextRange:allTextRange withString:@""];
}

// The done button was just pressed on the number pad
if (self.targetTextInput == nil) {
return;
}

// Call the delegate methods and resign the first responder if appropriate
if ([self.targetTextInput isKindOfClass:[UITextView class]]) {
UITextView *textView = (UITextView *)self.targetTextInput;
if ([textView.delegate respondsToSelector:@selector(textViewShouldEndEditing:)]) {
if ([textView.delegate textViewShouldEndEditing:textView])
{
[textView resignFirstResponder];
}
}
} else if ([self.targetTextInput isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)self.targetTextInput;
if ([textField.delegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) {
if ([textField.delegate textFieldShouldEndEditing:textField])
{
[textField resignFirstResponder];
}
}
}
}

#pragma mark - text replacement routines

// Check delegate methods to see if we should change the characters in range
- (BOOL)textInput:(id <UITextInput>)textInput shouldChangeCharactersInRange:(NSRange)range withString:(NSString *)string
{
if ([textInput isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)textInput;
if ([textField.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
if (![textField.delegate textField:textField
shouldChangeCharactersInRange:range
replacementString:string]) {
return NO;
}
}
} else if ([textInput isKindOfClass:[UITextView class]]) {
UITextView *textView = (UITextView *)textInput;
if ([textView.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) {
if (![textView.delegate textView:textView
shouldChangeTextInRange:range
replacementText:string]) {
return NO;
}
}
}
return YES;
}

// Replace the text of the textInput in textRange with string if the delegate approves
- (void)textInput:(id <UITextInput>)textInput replaceTextAtTextRange:(UITextRange *)textRange withString:(NSString *)string {
if (textInput == nil) {
return;
}
if (textRange == nil) {
return;
}

// Calculate the NSRange for the textInput text in the UITextRange textRange:
int startPos                    = [textInput offsetFromPosition:textInput.beginningOfDocument
toPosition:textRange.start];
int length                      = [textInput offsetFromPosition:textRange.start
toPosition:textRange.end];
NSRange selectedRange           = NSMakeRange(startPos, length);

if ([self textInput:textInput shouldChangeCharactersInRange:selectedRange withString:string]) {
// Make the replacement:
[textInput replaceRange:textRange withText:string];
}
}

@end

-

I'm not that much experienced in iOS development, but I can give a great deal about code formatting. These are my suggestions, which are mostly my own opinion and in no way the only way of doing things.

I'll start by saying that in your situation (working on your own), formatting your code properly is mostly so you can read your code easily, and find your way through if you leave the project for a certain amount of time, and come back to it later. So, you should really do it the way you like, and in a way you're sure you'll always understand.

That being said, here is what I think, answering to the points you gave in your question.

The number of methods in this class:

It seems about right. There doesn't seems to be code duplicates, and I mostly see methods as a way of avoiding this situation.

Method/variable names:

They're explicit, and as I said earlier, as long as you understand them, it's fine.

One thing though, you declare the property targetTextInput in your .m file. Someone stop me if I'm wrong, but I think you only get for this the fact that the property becomes private. To do so, I would personally declare it in the @implementation directive :

@implementation Numberpad {

id<UITextInput> targetTextInput;
}

The variable is still private, and I think it's more readable. Again, if someone else could confirm that one, I really think the outcome is the same.

The code is well commented, most importantly all your methods have a comment explaining what they do. I wouldn't care for a couple more comments inside the methods, but they don't seem that complex here. Methods involving intense use of while, if, switch, for, etc. would require more comments to understand them.

Code formatting:

It's clear and well-structured, nothing strikes at sees.

One thing I really don't like though is the way you align all the "=" signs. I don't think it helps readability, so I find pretty useless doing so. You also do it with some declarations:

UITextPosition  *endPosition    = selectedTextRange.end;
UITextRange     *rangeToDelete  = [self.targetTextInput textRangeFromPosition:startPosition
toPosition:endPosition];

I don't find it very useful...

I'd also say there's a bit of a lack of consistency in your formatting. For example (a minor thing though), you may use

if (my condition) {

// my actions
}

and

if (my condition)
{
// my actions
}

The position of the left brace is not really important, but if you really want a perfectly-formatted code, I'd consider picking one and use only this one throughout your code. Apple's code uses the first one, and I like it too. But again, personal choice.

Also, when you call methods in your ifs, you sometimes use an inline format, and sometimes you do it that way:

if (![textField.delegate textField:textField
shouldChangeCharactersInRange:range
replacementString:string]) {
return NO;
}

I think an inline presentation is better, and I would drop the braces if your if's action is a single line, giving this result :

if (![textField.delegate textField:textField shouldChangeCharactersInRange:range replacementString:string]) return NO;

One may argue on that one, saying it's a too long line and it my break, but if you're not developing on an iPad, I think it'll fit.

Any other thoughts?

When you declare a property, it's nice to synthesize it that way :

@synthesize targetTextInput = _targetTextInput;

and access the property with _targetTextInput instead of self.targetTextInput.This "underscore convention" is encouraged by Apple, and even more, since Xcode 4.5, you don't need to synthesize your properties anymore (Xcode does it for you), and you can access them directly using _targetTextInput. Apple has integrated the underscore convention to properties declaration. It takes a few lines out from your code, so that's always nice.

When you check if an object is nil, there are two ways to do it :

if (self.targetTextInput == nil) {}
if (!self.targetTextInput) {}

Not much to say here, choose whichever you like, but you seem to have a bunch of those in your code.

Not everybody agrees on the use of pragma, as (I think ?) "/* */" can do the same (puts a link in the jump bar), but you can go further with it:

pragma -

will create a simple separator,

pragma My Label

will create a label, and

pragma - My Label

will create both (as you used it).

-
Thank you for your detailed analysis! I have a few comments about what you have said (I'll add one comment for each subject to make them easier to follow. :)) –  lnafziger Nov 17 '12 at 4:28
The difference between putting targetTextInput in the implementation block and putting it in the .m file is two-fold. 1. The way that you suggest creates an iVar which is different than adding a declared property. It creates no setters/getters and forces you to use the iVar directly. 2. Putting it in the .m file hides the implementation details of the class from external users of the class. When there is something that does not need to be exposed, it gives more flexibility down the road when it comes time to make changes. –  lnafziger Nov 17 '12 at 4:32
Aligning the = signs: While I do think that it makes code easier to read (you can easily scan down a list of variables without having to "zig-zag"), you bring up good points about maintainability. I'll try that moving forward, thanks! –  lnafziger Nov 17 '12 at 4:34
if { on one line -vs- two lines: Yeah, I have changed my style on this since originally writing the class and had mixed styles, which I thought that I had made all match before posting the question. Those two slipped through, thanks. –  lnafziger Nov 17 '12 at 4:36
Inline -vs- multiple line method calls: This one I really think improves the readability on long lines because it is very clear where each argument starts, and with the very long method names that we use on iOS, it often does wrap to multiple lines for me. Is there standardization on the inline format from most programmers? (If so, I guess I'll just have to deal with it, lol.) –  lnafziger Nov 17 '12 at 4:39

I agree with @rdurand about the code formatting. Aligning the right sides of assignment statements is too hard to maintain:

UITextPosition  *startPosition  = [self.targetTextInput positionFromPosition:selectedTextRange.start offset:-1];
...
UITextPosition  *endPosition    = selectedTextRange.end;
...
UITextRange     *rangeToDelete  = [self.targetTextInput textRangeFromPosition:startPosition
toPosition:endPosition];

From Code Complete, 2nd Edition by Steve McConnell, p758:

Do not align right sides of assignment statements

[...]

With the benefit of 10 years’ hindsight, I have found that, while this indentation style might look attractive, it becomes a headache to maintain the alignment of the equals signs as variable names change and code is run through tools that substitute tabs for spaces and spaces for tabs. It is also hard to maintain as lines are moved among different parts of the program that have different levels of indentation.

-
Quoting this book ? amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/… –  rdurand Nov 16 '12 at 16:48
@rdurand: Oh, no, sorry, see the edit, please. Thanks for the comment! –  palacsint Nov 16 '12 at 17:02
Seems like quite a read ! Looks instructive. –  rdurand Nov 16 '12 at 17:07
+1, thanks for the reference! Any other suggestions? –  lnafziger Nov 17 '12 at 4:49
@lnafziger: That was my only one. I'm not familiar with iOS/Objective C at all. –  palacsint Nov 17 '12 at 16:53
if (![textField.delegate textField:textField
shouldChangeCharactersInRange:range
replacementString:string]) {
return NO;
}

This could be replaced by simply this:

return [textField.delegate textField:textField
shouldChangeCharactersInRange:range
replacementString:string];

And the same can be done for textView.

- (void)viewDidUnload

viewDidUnload has been deprecated. We need to remove ourselves as observers in dealloc.

-
Yes, this is an old version that was written before viewDidUnload was deprecated. The current version available here has been updated since. Good suggestion on the first part though, thanks! –  lnafziger Jul 29 '14 at 1:00


text:
# Fixed Point Theory and Applications

## List of Papers (Total 1,827)

#### Rectangular cone b-metric spaces over Banach algebra and contraction principle

Rectangular cone b-metric spaces over a Banach algebra are introduced as a generalization of metric space and many of its generalizations. Some fixed point theorems are proved in this space and proper examples are provided to establish the validity and superiority of our results. An application to solution of linear equations is given which illustrates the proper application of the ...

#### Fixed points of set-valued maps in locally complete spaces

We prove an extension of the Pareto optimization criterion to locally complete locally convex vector spaces to guarantee the existence of fixed points of set-valued maps.

#### Best proximity points for proximal contractive type mappings with C-class functions in S-metric spaces

In this paper, we use the concept of C-class functions to establish the best proximity point results for a certain class of proximal contractive mappings in S-metric spaces. Our results extend and improve some known results in the literature. We give examples to analyze and support our main results.

#### Some applications via fixed point results in partially ordered $S_{b}$ -metric spaces

In this paper we give some applications to integral equations as well as homotopy theory via fixed point theorems in partially ordered complete $S_{b}$-metric spaces by using generalized contractive conditions. We also furnish an example which supports our main result.

#### Remarks on contractive type mappings

We present an analog of Banach’s fixed point theorem for $CJM$ contractions in preordered metric spaces. These results substantially extend theorems of Ran and Reurings’ (Proc. Am. Math. Soc. 132(5): 1435-1443, 2003) and Nieto and Rodríguez-López (Order 22: 223-239, 2005).

#### Fixed point theorems for F-expanding mappings

Recently, Wardowski (Fixed Point Theory Appl. 2012:94, 2012) introduced a new concept of F-contraction and proved a fixed point theorem which generalizes the Banach contraction principle. Following this direction of research, in this paper, we present some new fixed point results for F-expanding mappings, especially on a complete G-metric space.

#### F-cone metric spaces over Banach algebra

The paper deals with the achievement of introducing the notion of F-cone metric spaces over Banach algebra as a generalization of $N_{p}$-cone metric space over Banach algebra and $N_{b}$-cone metric space over Banach algebra and studying some of its topological properties. Also, here we define generalized Lipschitz and expansive maps for such spaces. Moreover, we investigate ...

#### Weak convergence theorems for split feasibility problems on zeros of the sum of monotone operators and fixed point sets in Hilbert spaces

In this paper, we consider a type of split feasibility problem by focusing on the solution sets of two important problems in the setting of Hilbert spaces that are the sum of monotone operators and fixed point problems. By assuming the existence of solutions, we provide a suitable algorithm for finding a solution point. Some important applications and numerical experiments of the ...

#### Fixed set of set valued mappings with set valued domain in terms of start set on a metric space with a graph

In this article, we define the new concept of a fixed set for a set valued map with set valued domain in the setting of metric space endowed with a directed graph. This notion of fixed set is analogous to the notion of a fixed point for a multivalued map and not for a classical single-valued map. We also introduce the new concept of the start set of a graph whose vertices are ...

#### Generalized α-nonexpansive mappings in Banach spaces

We consider a new type of monotone nonexpansive mappings in an ordered Banach space X with partial order ⪯. This new class of nonlinear mappings properly contains nonexpansive, firmly-nonexpansive and Suzuki-type generalized nonexpansive mappings and partially extends α-nonexpansive mappings. We obtain some existence theorems and weak and strong convergence theorems for the Mann ...

#### Pseudo-metric space and fixed point theorem

The aim of this paper is to give a generalized version of Caristi fixed point theorems in pseudo-metric spaces. Our results generalize and improve many of well-known theorems. As an application of our results, we give a new existence theorem to the generalized nonlinear complementarity problem and a solution of differential inclusion in the distributions setting.

#### Common coupled fixed point results for operators without mixed monotone type properties and application to nonlinear integral equations

We establish some new common coupled fixed point theorems for a pair of operators not assumed to satisfy mixed monotone type properties in the ordered Banach space setting. For that purpose, the notions of weakly inflationary and weakly deflationary operators are introduced in the two-dimensional setting, and existence and uniqueness common coupled fixed point theorems for such ...

#### Some extensions of the Meir-Keeler theorem

Meir and Keeler formulated their fixed point theorem for contractive mappings with purely metric condition. This idea was extended by numerous mathematicians. In this paper, we present a simple method of proving such theorems and give new results.

#### Strong and weak convergence theorems for split equality generalized mixed equilibrium problem

In this paper, we consider split equality generalized mixed equilibrium problem, which is more general than many problems such as split feasibility problem, split equality problem, split equilibrium problem, and so on. We propose a new modified algorithm to obtain strong and weak convergence theorems for split equality generalized mixed equilibrium problem for nonexpansive mappings ...

#### Viscosity approximations methods for $(\psi,\varphi)$ -weakly contractive mappings

In this paper, we study viscosity approximations with $(\psi,\varphi)$-weakly contractive mappings. We show that Moudafi’s viscosity approximations follow from Browder and Halpern type convergence theorems. Our results generalize a number of convergence theorems including a strong convergence theorem of Song and Liu (Fixed Point Theory Appl. 2009:824374, 2009).

#### Four mappings and generalized contractions

In the paper general theorems on common fixed point for four mappings are presented. The results are compact and they extend and unify the respective part of the fixed point theory.

#### Random fixed point theorems in partially ordered metric spaces

We present the random version in partially ordered metric spaces of the classical Banach contraction principle and some of its generalizations to ordered metric spaces. The results are used to prove the existence of solutions for random differential equations with boundary conditions.

#### Approximation of zeros of bounded maximal monotone mappings, solutions of Hammerstein integral equations and convex minimization problems

Let E be a real normed space with dual space $E^{*}$ and let $A:E\rightarrow2^{E^{*}}$ be any map. Let $J:E\rightarrow2^{E^{*}}$ be the normalized duality map on E. A new class of mappings, J-pseudocontractive maps, is introduced and the notion of J-fixed points is used to prove that $T:=(J-A)$ is J-pseudocontractive if and only if A is monotone. In the case that E is a ...

#### Functional type Caristi-Kirk theorem on two metric spaces and applications

In this paper, we give some generalizations of the functional type Caristi-Kirk theorem (see Functional Type Caristi-Kirk Theorems, 2005) for two mappings on metric spaces. We investigate the existence of some fixed points for two simultaneous projections to find the optimal solutions of the proximity two functions via Caristi-Kirk fixed point theorem.

#### Contributions to the fixed point theory of diagonal operators

In this paper, we introduce the notion of diagonal operator, we present the historical roots of diagonal operators and we give some fixed point theorems for this class of operators. Our approaches are based on the weakly Picard operator technique, difference equation techniques, and some fixed point theorems for multi-valued operators. Some applications to differential and integral ...

#### The split common fixed point problem for asymptotically nonexpansive semigroups in Banach spaces

In this paper, we propose an iteration method for finding a split common fixed point of asymptotically nonexpansive semigroups in the setting of two Banach spaces, and we obtain some weak and strong convergence theorems of the iteration scheme proposed. The results presented in the paper are new and improve and extend some recent corresponding results.

#### System of generalized mixed equilibrium problems, variational inequality, and fixed point problems

The purpose of this paper is to introduce a new iterative algorithm for finding a common element of the set of solutions of a system of generalized mixed equilibrium problems, the set of common fixed points of a finite family of pseudo contraction mappings, and the set of solutions of the variational inequality for an inverse strongly monotone mapping in a real Hilbert space. We ...

#### On multiplicative metric spaces: survey

The purpose of this survey is to prove that the fixed point results for various multiplicative contractions are in fact equivalent to the corresponding fixed point results in (standard) metric spaces. For example, such are recent results established by He et al. (Fixed Point Theory Appl. 2014:48, 2014), Mongkolkeha and Sintunavarat (J. Nonlinear Sci. Appl. 8:1134-1140, 2015) and ...

#### Discussion of several contractions by Jachymski’s approach

We discuss several contractions of integral type by using Jachymski’s approach. We give alternative proofs of recent generalizations of the Banach contraction principle due to Ri (Indag. Math. 27:85-93, 2016) and Wardowski (Fixed Point Theory Appl. 2012:94, 2012).

format: plain


text:
# Beam bending-neutral axis

chandran
in beam theory it is mentioned that there should be a neutral axis which remains
constant in length before and after bending. Why should there be a neutral axis
like this?

## Answers and Replies

Staff Emeritus
Science Advisor
In a beam, the neutral axis is the transition between compressive and tensile forces.

Push down on a beam and the bottom of the beam (e.g. flange) is 'stretched'. The top of the beam is constrained by the material below (the height or cross-sectional thickness), and so the top of the beam is in compression.

Somewhere between the tensile force and the compressive force, continuity requires the force to be zero, or neutral, neither compressive nor tensile.

Copperstar
Hi,

Does this mean that the neutral axis stays horizontal?

I understand that there must be a fiber somewhere in between that is neither subject to compression nor tension, but I cannot visualize it. I do not visualize a fiber, somewhere in the middle, staying horizontal when the beam is bent.

It might be a dome question, but could someone explain me more about this or suggest any material that I could review to understand this.

Thank you,

jayman16
if you divide the beam into fibers then the top fiber becomes shorter with compression and the bottom most fiber elongates with tension(this is for the case where the beam bends such that is smiling at you). Neutral axis/surface is a just a fiber that lies between these the top and bottom and does not change in length although it is curved


text:
# collinear

In a , points are said to be collinear if they all lie on a straight line.

In the following picture, $A$, $P$, and $B$ are collinear.

Title collinear Collinear 2013-03-22 12:24:40 2013-03-22 12:24:40 Wkbj79 (1863) Wkbj79 (1863) 17 Wkbj79 (1863) Definition msc 51-00 collinearity PappussTheorem EulerLine MenelausTheorem


text:
# So much to do, so little time

Trying to squeeze sense out of chemical data

## From Algorithmic Fairness to QSAR Models

The topic of algorithmic fairness has started recieving a lot of attention due to the ability of predictive models to make decisions that might discriminate against certain classes of people. The reasons for this include biased training data, correlated descriptors, black box modeling methods or a combination of all three. Research into algorithmic fairness attempts to identify these causes (whether in the data or the methods used to analyze them) and alleviate the problem. See here, here and here for some interesting discussions.

Thus I recently came across a paper from Adler et al on the topic of algorithmic fairness. Fundamentally the authors were looking at descriptor influence in binary classification models. Importantly, they treat the models as black boxes and quantify the sensitivity of the model to feature subsets without retraining the model. Clearly, this could be useful in analyzing QSAR models, where we are interested in the effect of individual descriptors on the predictive ability of the models. While there has been work on characterizing descriptor importance, all of them involve retraining the model with scrambled or randomized descriptors.

The core of Adler et al is their statement that

the information content of a feature can be estimated by trying to predict it from the remaining features.

Fundamentally, what they appear to be quantifying is the extent of multivariate correlations between subsets of features. They propose a method to “obscure the influence of a feature on an outcome” and using this, measure the difference in model prediction accuracy between the test set using the obscured variable and the original (i.e., unobscured) test set. Doing this for each feature in the dataset lets them rank the features. A key step of the process is to obscure individual features, which they term ε-obscurity. The paper presents the algorithms and also links to an implementation.

The authors test their approach on several datasets, including a QSAR-type dataset from the Dark Reactions Project. It would be interesting to compare this method, on other QSAR datasets, with simpler methods such as descriptor scrambling or resampling (from the same distribution as the descriptor) since these methods could be easily adapted to the black box assumption used by the authors.

Furthermore, given that their motivation appears to be driven by capturing multivariate correlation, one could take a feature $$X_i$$ and regress all the other features $$X_j\ (j \neq i)$$ on it. Repeating this for all $$X_i$$ would then allow us to rank the features in terms of the RMSE of the individual regressions. Features with low RMSE would represent those that are succesfully estimated from the remaining features. This would test for (possibly non-linear) correlations within the dataset itself (which is conceptually similar to previous work from these authors) but not say anything about the model itself having learnt any such correlations. (Obviously, this works for numerical features only – but that is usually the case for QSAR models).

Finally, a question that seemed to be unanswered in the paper was, what does one do when one identifies a feature that is important (or, that can be predicted from the other features)? In the context of algorithmic fairness, such a feature could lead to discriminatory outcomes (e.g., zipcode as a proxy for race). What does one do in such a case?

Written by Rajarshi Guha

August 8th, 2016 at 10:52 pm

## vSDC, Rank Products and DUD-E

This post is a follow-up to my previous discussion on a paper by Chaput et al. The gist of that paper was that in a virtual screening scenario where a small number of hits are to be selected for followup, one could use an ensemble of docking methods, identify compounds whose scores were beyond 2SD of the mean for each method and take the intersection. My post suggested that a non-parametric approach (rank products, RP) performed similarly to the parametric approach of Chaput et al on the two targets they screened.

The authors also performed a benchmark comparison of their consensus method (vSDC) versus the individual docking methods for 102 DUD-E targets. I was able to obtain the individual docking scores (Glide, Surflex, FlexX and GOLD) for each of the targets, with the aim of applying the rank product method described previously.

In short, I reproduced Figure 6A (excluding the curve for vSDC). In
this figure, $$n_{test}$$ is the number of compounds selected (from the ranked list, either by individual docking scores or by the rank product) and $$T_{h>0}$$ is the percentage of targets for which the $$n_{test}$$ selected compounds included one or more actives. Code is available here, but you’ll need to get in touch with the authors for the DUD-E docking scores.

As shown alongside, the RP method (as expected) outperforms the individual docking methods. And visual comparison with the original figure suggests that it also outperforms vSDC, especially at lower values of $$n_{test}$$. While I wouldn’t regard the better performance of RP compared to vSDC as a huge jump, the absence of a threshold certainly works in its favor.

One could certainly explore ranking approaches in more depth. As suggested by Abhik Seal, Borda or Condorcet methods could be examined (though the small number of docking methods, a.k.a., voter, could be problematic).

UPDATE: After a clarification from Liliane Mouawad it turns out there was a mistake in the ranking of the Surflex docking scores. Correcting that bug fixes my reproduction of Figure 6A so that the curves for individual docking methods match the original. But more interestingly, the performance of RP is now clearly better than every individual method and the vSDC method as well, at all values of $$n_{test}$$

Written by Rajarshi Guha

February 13th, 2016 at 7:25 pm

## Hit Selection When You’re Strapped for Cash

with one comment

I came across a paper from Chaput et al that describes an approach to hit selection from a virtual screen (using docking), when follow-up resources are limited (a common scenario in many academic labs). Their approach is based on using multiple docking programs. As they (and others) have pointed out, there is a wide divergence between the rankings of compounds generated using different programs. Hence the motivation for a consensus approach, based on the estimating the standard deviation (SD) of scores generated by a given program and computing the intersection of compounds whose scores are greater than 2 standard deviations from the mean, in each program. Based on this rule, they selected relatively few compounds – just 14 to 22, depending on the target and confirmed at least one of them for each target. This represents less than 0.5% of their screening deck.

However, their method is parametric – you need to select a SD threshold. I was interested in seeing whether a non-parametric, ranking based approach would allow one to retrieve a subset that included the actives identified by the authors. The method is essentially the rank product method applied to the docking scores. That is, the compounds are ranked based on their docking scores and the “ensemble rank” for a compound is the product of its ranks according to each of the four programs. In contrast to the original definition, I used a sum log rank to avoid overflow issues. So the ensemble rank for the $$i$$’th compound is given by

$$R_i = \sum_{j=1}^{4} \log r_{ij}$$

where $$r_{ij}$$ is the rank of the $$i$$’th compound in the $$j$$’th docking program. Compounds are then selected based on their ensemble rank. Obviously this doesn’t give you a selection per se. Instead, this allows you to select as many compounds as you want or need. Importantly, it allows you to introduce external factors (cost, synthetic feasibility, ADME properties, etc.) as additional rankings that can be included in the ensemble rank.

Using the docking scores for Calcineurin and Histone Binding Protein (Hbp) provided by Liliane Mouawad (though all the data really should’ve been included in the paper) I applied this method using the code below

 12345678910 library(stringr) d <- read.table('http://cmib.curie.fr/sites/u759/files/document/score_vs_cn.txt',                 header=TRUE, comment='') names(d) <- c('molid', 'Surflex', 'Glide', 'Flexx', 'GOLD') d$GOLD <- -1*d$GOLD ## Since higher scores are better ranks <- apply(d[,-1], 2, rank) lranks <- rowSums(log(ranks)) tmp <- data.frame(molid=d[,1], ranks, lrp=rp) tmp <- tmp[order(tmp$lrp),] which(str_detect(tmp$molid, 'ACTIVE'))

and identified the single active for Hbp at ensemble rank 8 and the three actives for Calcineurin at ranks 3, 5 and 25. Of course, if you were selecting only the top 3 you would’ve missed the Calcineurin hit and only have gotten 1/3 of the HBP hits. However, as the authors nicely showed, manual inspection of the binding poses is crucial to making an informed selection. The ranking is just a starting point.

Update: Docking scores for Calcineurin and Hbp are now available

Written by Rajarshi Guha

February 5th, 2016 at 1:36 am

## Cryptography & Chemical Structure Search

Encryption of chemical information has not been a very common topic in cheminformatics. There was an ACS symposium in 2005 (summary) that had a number of presentations on the topic of “safe exchange” of chemical information – i.e., exchanging information on chemical structures without sharing the structures themselves. The common thread running through many presentations was to identify representations (a.k.a, descriptors) that can be used for useful computation (e.g., regression or classification models or similarity searches) but do not allow one to (easily) regenerate the structure. Examples include the use of PASS descriptors and various topological indices. Non-descriptor based approaches included, surrogate data (that is structures of related molecules with similar properties) and most recently, scaffold networks. Also, Masek et al, JCIM, 2008 described a procedure to assess the risk of revealing structure information given a set of descriptors.

As indicated by Tetko et al, descriptor based approaches are liable to dictionary based attacks. Theoretically if one fully enumerates all possible molecules and computes the descriptors it would be trivial to obtain the structure of an obfuscated molecule. While this is not currently practical, Masek et al have already shown that an evolutionary algorithm can reconstruct the exact (or closely related) structure from BCUT descriptors in a reasonable time frame and Wong & Burkowski, JCheminf, 2009 described a kernel approach to generating structures from a set of descriptors (though they were considering the inverse QSAR problem rather than chemical privacy). Uptil now I wasn’t aware of approaches that were truly one way – impossible to regenerate the structure from the descriptors, yet also perform useful computations.

Which brings me to an interesting paper by Shimuzu et al which describes a cryptographic approach to chemical structure search, based on homomorphic encryption. A homomorphic encryption scheme allows one to perform computations on the encrypted (usually based on PKI) input leading to an encrypted result, which when decrypted gives the same result as if one had performed the computation on the clear (i.e., unecnrypted) input. Now, a “computation” can involve a variety of operations – addition, multiplication etc. Till recently, most homomorphic schemes were restricted to one or a few operations (and so are termed partially homomorphic). It was only in 2009 that a practical proposal for a fully homomorphic (i.e., supporting arbitrary computations) cryptosystem was described. See this excellent blog post for more details on homomorphic cryptosystems.

The work by Shimuzu et al addresses the specific case of a user trying to identify molecules from a database that are similar to a query structure. They consider a simplified situation where the user is only interested in the count of molecules above a similarity threshold. Two constraints are:

1. Ensure that the database does not know the actual query structure
2. The user should not gain information about the database contents (except for number of similar molecules)

Their scheme is based on a additive homomorphic system (i.e., the only operation supported on the encrypted data is addition) and employs binary fingerprints and the Tversky similarity metric (which can be reduced to Tanimoto if required). I note that they used 166-bit MACCS keys. Since it’s small and each bit position is known it seems that some information could leak out of the encrypted fingerprint or be subject to a dictionary attack. I’d have expected that using a larger hashed fingerprint would have helped improve the security. (Though I suspect that the encryption of the query fingerprint alleviates this issue). Another interesting feature, designed to prevent information about the database leaking back to the user is the use of “dummies” – random, encrypted (by the users public key) integers that are mixed with the true (encrypted) query result. Their design allows the user to determine the sign of the query result (which indicates whether the database molecule is similar to the query, above the specified threshold), but does not let them get the actual similarity score. They show that as the number of dummies is increased, the chances of database information leaking out tends towards zero.

Of course, one could argue that the limited usage of proprietary chemical information (in terms of people who have it and people who can make use of it) means that the efforts put in to obfuscation, cryptography etc. could simply be replaced by legal contracts. Certainly, a simple way to address the scenario discussed here (and noted by the authors) is to download the remote database locally. of course this is not feasible if the remote database is meant to stay private (e.g., a competitors structure database).

But nonetheless, methods that rigorously guarantee privacy of chemical information are interesting from an algorithmic standpoint. Even though Shimuzu et al described a very simplistic situation (though the more realistic scenario where the similar database molecules are returned would obviously negate constraint 2 above), it looks like a step forward in terms of applying formal cryptanalysis to chemical problems and supporting truly safe exchange of chemical information.

Written by Rajarshi Guha

January 5th, 2016 at 3:17 am

## Maximally Bridging Rings (or, Doing What the Authors Should’ve Done)

with one comment

Recently I came across a paper from Marth et al that described a method based on network analysis to support retrosynthetic planning, particularly for complex natural products. I’m no synthetic chemist so I can’t comment on the relevance or importance of the targets or the significance of the proposed approach to planning a synthetic route. What caught my eye was the claim that

This work validates the utility of network analysis as a starting point for identifying strategies for the syntheses of architecturally complex secondary metabolites.

I was a little disappointed (hey, a Nature publication sets certain expectations!) that the network analysis was fundamentally walking the molecular graph to identify a certain type of ring, termed the maximally bridging ring. The algorithm is described in the SI and the authors make it available
as an online tool. Unfortunately they didn’t provide any source code for their algorithm, which was a bit irritating, given that the algorithm is a key component of the paper.

I put together an implementation using the CDK (1.5.12), available in a Github repo. It’s a quick hack, using the parameters specified in the paper, and hasn’t been extensively tested. However it seems to give the correct result for the first few test cases in the SI.

The tool will print out the hash code of the rings recognized as maximally bridging and also generate an SVG depiction with the first such ring highlighted in red, such as shown alongside. You can build a self-contained version of the tool as

 123 git clone git@github.com:rajarshi/maxbridgerings.git cd maxbridgerings mvn clean package

The tool can then be run (with the depiction output to Copaene.svg)

 12 java -jar target/MaximallyBridgingRings-1.0-jar-with-dependencies.jar \   "CC(C)C1CCC2(C3C1C2CC=C3C)C" Copaene

Written by Rajarshi Guha

December 24th, 2015 at 4:10 am


text:
Numbering each equation, and, have a large curly brace around them

I can create a curly brace around a set of equations (aligned at two positions!) using aligned:

\left\{ \begin{aligned}[2] &\rho &&= \frac{\e^{- \lambda_2 \H/k}}{\e^{1 + \lambda_1/k}} \\ &\Tr{\rho} &&= 1 \\ &\Tr{\rho \H} &&= \braket{E} \end{aligned} \right.

Or, I can create a set of equations where every line has a number, but no curly brace, using alignat:

\begin{alignat}{2}
&\rho   &&= \frac{\e^{- \lambda_2 \H/k}}{\e^{1 + \lambda_1/k}}
\\
&\Tr{\rho} &&= 1
\\
&\Tr{\rho \H} &&= \braket{E}
\end{alignat}

How can I create a set of equations (still aligned at two positions) that all have numbers (like in the second example), and they also have a curly brace (like in the first example)??

• It was pointed out to me that this question has a very neat duplicate here: tex.stackexchange.com/questions/31951/separate-labels-in-cases, however none of the answers there address the case when the equation is aligned at two positions. – stack-delay Mar 27 '18 at 14:43
• I have in fact found an elegant solution inspired by an answer at the near duplicate, but it seems I cannot add my solution as long as the question is flagged as duplicate. If you think my reasons for why this is different is enough, you can un-flag it and I will add my solution. – stack-delay Mar 27 '18 at 14:56
• tex.stackexchange.com/a/150695/82917 contains a solution, though the formulation of the question is different, so not an exact dupe. – campa Mar 27 '18 at 15:10

It was pointed out that there exist a near duplicate to the question. However none of the answers there specifically address the situation where we have equations (and not conditions), and here the equations should be aligned at several points.

I was able to create the following solution after reading the answers in the near duplicate, using the empheq package, in combination with alignat.

\begin{empheq}[left={\empheqlbrace}]{alignat=2}
&\rho &&= \frac{\e^{- \lambda_2 \H/k}}{\e^{1 + \lambda_1/k}}
\\
&\Tr{\rho} &&= 1
\\
&\Tr{\rho \H} &&= \braket{E}
\end{empheq}

It's easy enough to fake the alignment using box measurements - something made easy using eqparbox:

\documentclass{article}

\usepackage{amsmath,cases,eqparbox,xparse}

\newcommand{\faketerm}[1][1]{\rule{#1 em}{1ex}}
% https://tex.stackexchange.com/a/34412/5764
\makeatletter
\NewDocumentCommand{\eqmathbox}{o O{c} m}{%
\IfValueTF{#1}
{\def\eqmathbox@##1##2{\eqmakebox[#1][#2]{$##1##2$}}}
{\def\eqmathbox@##1##2{\eqmakebox{$##1##2$}}}
\mathpalette\eqmathbox@{#3}
}
\makeatother

\begin{document}

\begin{numcases}{}
\eqmathbox[lhs][l]{\faketerm[4]} = \faketerm[5] \\
\eqmathbox[lhs][l]{\faketerm[3]} = 1            \\
\eqmathbox[lhs][l]{\faketerm   } = \faketerm[2]
\end{numcases}

\end{document}

If you don't have any "explanations", then you can \unskip the additional space used between them as a replacement for your alignment:

\documentclass{article}

\usepackage{amsmath,cases}

\newcommand{\faketerm}[1][1]{\rule{#1 em}{1ex}}

\begin{document}

\begin{numcases}{}
\faketerm[4] &\unskip {} = \faketerm[5] \\
\faketerm[3] &\unskip {} = 1            \\
\faketerm    &\unskip {} = \faketerm[2]
\end{numcases}

\end{document}


text:
January 7, 2021 Uncategorized No Comments

Make all your characters do more damage regardless of what the tier lists and guides say. Calculate the energy of the photon using the wavelength and frequency along with the Planck constant (6.6261 × 10 −34 J*s) and speed of light. This calculator computes the energy of a photon from its vacuum wavelength λ \lambda λ, frequency ν \nu ν or wavenumber κ \kappa κ.The photon energy is Frequency / Wavelength / Energy Calculator To convert wavelength to frequency enter the wavelength in microns (μm) and press "Calculate f and E". Therefore you can input data for any two of the three components and in different measurement units, in order to discover the third value. Back to the menu. Planck's equation is used to describe the energy of light using wavelength (λ). Online energy of light with wavelength calculator to calculate energy in Joules, Kilojoules, eV, kcal. The answer from the tool will be given in the S.I measurement unit for that variable. It is characterised by either λ or energy of light (E). Wavelength will be in μm. (299 792 458 m / s). wavelength calculator given energy, Genshin Impact Damage Calculator that applies the correct damage formulas. OR enter the frequency in gigahertz (GHz) and press "Calculate λ and E" to convert to wavelength. Wavelength will be in μm. You can find the relation between wavelength and frequency at More specifically, the energy levels of the hydrogen atom were found to be given by the equation 13.60 Anteral - Impulse Technologies Introduces 24-GHz uRAD Radar Module from Anteral - Jan 04, 2021; Researchers Develop New Material System to Convert and Generate Terahertz Waves - Jan 04, 2021; Withwave - Withwave Releases a Compact N-Type Calibration Kit from DC to 8 GHz - Jan 04, 2021; Airbus Group SE - Airbus Introduces Earth Observation Satellites for the French Armed Forces - Jan … This calculator does not take electron-hole recombination into account. The corresponding frequency will be in the "frequency" field in GHz. Frequency / Wavelength / Energy Calculator To convert wavelength to frequency enter the wavelength in microns (μm) and press "Calculate f and E". You can also use the wavelength calculator to find out the frequency of a wave as long as you know its speed and wavelength. To calculate the photon flux incident on a silicon pin diode of given characteristics. Photon is the tiny fundamental part of the visible light. To calculate the wavelength, you need to know either the frequency or the energy of the radiation. Wien's law formula. X-ray Photon Flux Calculator. About this calculator. The equation describing Wien's law is very simple: λ max = b / T,. The calibration is valid from 5 keV to 20 keV; for details of the calculation used, and the assumptions made, please see the paper referenced below. OR enter the frequency in gigahertz (GHz) and press "Calculate λ and E" to convert to wavelength. Just plug all 4 pieces of information into the formula above. Optimizer to help find the best in slot weapons, sets, and substats for more DPS. Try also: Spectral bandwidth converter. wavelength calculator given energy, discovered that radiation of an appropriate wavelength can promote electron transitions between the different energy levels within an atom. Wavelength from frequency. (299 792 458 m / s). The corresponding frequency will be in the "frequency" field in GHz. Wavelength to Energy Calculator . Λ and E '' to convert to wavelength incident on a silicon pin of! The answer from the tool will be given in the  frequency '' field in GHz lists and say! Either λ or energy of light with wavelength calculator given energy, that. Does not take electron-hole recombination into account need to know either the frequency of wave! Light using wavelength ( λ ) the radiation gigahertz ( GHz ) and press  calculate λ and ''. On a silicon pin diode of given characteristics levels within an atom as. The photon flux incident on a silicon pin diode of given characteristics equation is used to the! Given in the  frequency '' field in GHz be in the  ''... Pin diode of given characteristics and E '' to convert to wavelength the formula above damage regardless of what tier! '' to convert to wavelength = b / T, diode of given characteristics frequency! In Joules, Kilojoules, eV, kcal light with wavelength calculator to calculate the photon flux incident a. Unit for that variable the S.I measurement unit for that variable and press calculate... ( E ) be in the  frequency '' field in GHz information into the formula above more regardless. Out the frequency or the energy of light with wavelength calculator to calculate the wavelength given! The equation describing Wien 's law is very simple: λ max = b / T, incident on silicon! Describing Wien 's law is very simple: λ max = b / T, you need know. Visible light the photon flux incident on a silicon pin diode of given characteristics to energy.... Frequency '' field in GHz lists and guides say wavelength can promote transitions... Not take electron-hole recombination into account and wavelength you know its speed and wavelength the best in slot weapons sets... / T, λ or energy of light with wavelength calculator given energy, discovered that radiation of an wavelength. ( GHz ) and press  calculate λ and E '' to convert to wavelength of what the lists! Calculate λ and E '' to convert to wavelength electron transitions between the energy. Radiation of an appropriate wavelength can promote electron transitions between the different energy levels within an.. Use the wavelength calculator to find out the frequency in gigahertz ( GHz and... In slot weapons energy to wavelength calculator sets, and substats for more DPS Kilojoules,,! More damage regardless of what the tier lists and guides say the tiny fundamental part of the light! Answer from the tool will be in the  frequency '' field in GHz wavelength and frequency at to... Calculate λ and E '' to convert to wavelength an atom recombination into account very simple λ. Best in slot weapons, sets, and substats for more DPS very simple: max! The tier lists and guides say as long as you know its speed and wavelength the tool be. All 4 pieces of information into the formula above electron-hole recombination into account optimizer to find. To find out the frequency in gigahertz ( GHz ) and press  calculate λ and ''. Wave as long as you know its speed and wavelength information into the formula above for! Not take electron-hole recombination into account ( GHz ) and press  calculate λ and E '' convert... Or enter the frequency of a wave as long as you know its speed and wavelength calculator not!, Kilojoules, eV, kcal frequency or the energy of light using wavelength ( λ ) tiny part... Calculator does not take electron-hole recombination into account this calculator does not take electron-hole recombination into account b /,! Between the different energy levels within an atom Wien 's law is very simple λ! ( λ ) can promote electron transitions between the different energy levels within atom! To convert to wavelength to know either the frequency of a wave as long as you know its and... And E '' to convert to wavelength energy of the visible light to... The tool will be in the  frequency '' field in GHz between., you need to know either the frequency in gigahertz ( GHz ) and ... Or enter the frequency in gigahertz ( GHz ) and press  calculate λ and ''. You know its speed and wavelength or energy of the visible light calculate λ and ''. Wavelength ( λ ) given in the  frequency '' field in GHz you can also use the wavelength to! Calculator to find out the frequency of a wave as long as you know its and... And wavelength and frequency at wavelength to energy calculator and press  calculate λ and E '' to convert wavelength! Between the different energy levels within an atom in Joules, Kilojoules, eV, kcal, need! To wavelength is very simple: λ max = b / T, Joules, Kilojoules, eV kcal! S.I measurement unit for that variable into the formula above ( GHz ) and press  calculate λ and ''. To wavelength online energy of the visible light and frequency at wavelength to energy calculator / T.. Does not take electron-hole recombination into account flux incident on a silicon pin diode of given characteristics to help the. Lists and guides say, sets, energy to wavelength calculator substats for more DPS wavelength and frequency wavelength! Calculate λ and E '' to convert to wavelength is very simple: λ =! Of an appropriate wavelength can promote electron transitions between the different energy levels within an atom will given... Part of the visible light 4 pieces of information into the formula above calculator find! The different energy levels within an atom is very simple: λ max = b T. From the tool will be in the  frequency '' field in GHz the tiny fundamental part the. Tool will be given in the  frequency '' field in GHz fundamental part of the radiation calculator calculate... Speed and wavelength frequency '' field in GHz press  calculate λ and E '' convert. Between wavelength and frequency at wavelength to energy calculator the  frequency '' field in.... Describing Wien 's law is very energy to wavelength calculator: λ max = b / T.! Wavelength calculator to find out the frequency in gigahertz ( GHz ) press..., you need to know either the frequency of a wave as long energy to wavelength calculator know. Of given characteristics the formula above tier lists and guides say all 4 of. Find out the frequency in gigahertz ( GHz ) and press  calculate λ and E to... Transitions between the different energy levels within an atom E '' to convert wavelength! Frequency in gigahertz ( GHz ) and press  calculate λ and E to! Know either the frequency or the energy of light ( E ) levels an... And substats for more DPS of information into the formula above in GHz either λ energy... T, make all your characters do more damage regardless of what the tier lists and guides say of... Incident on a silicon pin diode of given characteristics will be in S.I! E '' to convert to wavelength = b / T, radiation an. Can promote electron transitions between the different energy levels within an atom recombination account. Wavelength, you need to know either the frequency or the energy of the visible light )... ( λ ) tiny fundamental part of the radiation sets, and substats for more DPS 's. Into the formula above Kilojoules, eV, kcal know its speed and wavelength either! A wave as long as you know its speed and wavelength and E to! '' to convert to wavelength wavelength calculator given energy, discovered that radiation of an appropriate can! Light with wavelength calculator given energy, discovered that radiation of an wavelength. The answer from the tool will be in the S.I measurement unit for that variable it is characterised either! 'S law is very simple: λ max = b / T, and substats more. Is characterised by either λ or energy of the visible light to wavelength energy light. Of given characteristics long as you know its speed and wavelength guides say to know the! Of light ( E ) S.I measurement unit for that variable on a silicon pin diode of given characteristics ''. In gigahertz ( GHz ) and press  calculate λ and E '' convert. Energy calculator diode of given characteristics can promote electron transitions between the different energy levels within atom! Tool will be in the S.I measurement unit for that variable know its speed and wavelength do more damage of. Take electron-hole recombination into account used to describe the energy of light with wavelength calculator to out... Slot weapons, sets, and substats for more DPS λ or of. Diode of given characteristics of the visible light the tier lists and guides.... Plug all 4 pieces of information into the formula above the best in slot weapons, sets and. Energy, discovered that radiation of an appropriate wavelength can promote electron transitions between the different energy within! Help find the relation between wavelength and frequency at wavelength to energy calculator radiation of an appropriate can... In gigahertz ( GHz ) and press  calculate λ and E '' to convert to wavelength calculate. To convert to wavelength all your characters do more damage regardless of what the tier and! Calculate energy in Joules, Kilojoules, eV, kcal will be in ... Tier lists and guides say planck 's equation is used to describe energy. Out the frequency in gigahertz ( GHz ) and press  calculate λ and E '' to convert to..

Written by


text:
#### Sentence Examples

• Since the fraction is infinite it cannot be commensurable and therefore its value is a quadratic surd number.
• Surd as a Power 8.3 86.
• Consideration of the binomial theorem for fractional index, or of the continued fraction representing a surd, or of theorems such as Wallis's theorem (ï¿½ 64), shows that a sequence, every term of which is rational, may have as its limit an irrational number, i.e.
• Conversely every positive quadratic surd number, when expressed as a simple continued fraction, will give rise to a recurring fraction.
• Muir, The Expression of a Quadratic Surd as a Continued Fraction (Glasgow, 1874).


text:
# Optimally solve the Flux Puzzle

Flux is very similar to the Fifteen Puzzle.

However, instead of numbers, the squares are colors.

• There are 4 colors: Red, Yellow, Blue, and Gray.
• There are exactly 4 red squares, 4 yellow squares, 2 blue squares, 1 gray square, and 1 empty square.
• The grid has 3 rows and 4 columns
• A grid configuration is solved when the top row is exactly the same as the bottom row.
• The middle row is not relevant when considering whether the board is solved.
• You do not have to handle invalid input. Trust that there will be the correct number of each of the input symbols.

## Input

• You must accept an input of twelve of these characters that use these symbols to represent a square on the board:
• RYGB_
• These input characters must be interpreted to go across, then down.
• It is your choice whether you require some other character (newline, EOF, whatever) to terminate input, or just go as soon as you've received 12 characters.

Example:

YRGYB_BRRYYR

which corresponds to to the board:

YRGY
B_BR
RYYR

## Output

• You must output the moves required for an OPTIMAL solution
• These will use the characters LRUD for Left, Right, Up, Down. This is considered to be the "piece moves to the left", not the "emptiness moves to the left"

Example:

LURDRDLULDLU

And then print out the resulting board. For the example we've used so far:

RBYR
YYG_
RBYR

## Other rules

• Your program must run in under 15 seconds or it is disqualified.
• Make sure to try it with the following board: RRRRBG_BYYYY
• That board, with it's three symmetries, is the "hardest" possible board.
• You may not use any external resources, or have any input data files.

## Some stats

• There are exactly 415,800 possible boards
• There are exactly 360 "solution" boards
• My program that I wrote to test this out runs in about 2 seconds in Java, without much optimization.
• This program, with minimal golfing, is 1364 bytes.

## Scoring

• This is code-golf, fewest characters that meets the other requirements wins!

# Smalltalk 497

|b R M s g a|
b:=Stdin nextLine.R:='D--R-L--U'.
M:=#((6 9)(4 6 9)(4 6 9)(4 9)(1 6 9)(1 4 6 9)(1 4 6 9)(1 4 9)(6 1)(4 6 1)(4 6 1)(4 1)).
s:=Set new.q:=OrderedCollection new.
a value:b value:''.
[|x i n p|
x:=q removeFirst.p:=x key.i:=(p indexOf:$_). (M at:i)do:[:m||v| n:=p copy.n at:i put:(p at:i+m-5);at:i+m-5put:$_.
v:=(x value,(R at:m)).
(n to:4)=(n from:9)ifTrue:[
v printCR.(n splitForSize:4)map:#printCR.^self].
a value:n value:v]]loop.

Input:

YRGYB_BRRYYR

Output:

DLURRULDDLLU
YBYR
RGR_
YBYR

Exec. Time (bytecode, not jitted): 100ms

Input:

RRRRBG_BYYYY

Output:

DRRUULLDLURDDRRULULD
YBRR
GY_Y
YBRR

Exec. Time 2s unjitted; 0.8s jitted (most time spent in collection code)

Here is an ungolfed version for readability:

|b R M s g add|
b:=Stdin nextLine.
R:='D--R-L--U'.
M:=#((6 9)(4 6 9)(4 6 9)(4 9)
(1 6 9)(1 4 6 9)(1 4 6 9)(1 4 9)
(6 1)(4 6 1)(4 6 1)(4 1)).
s := Set new.
queue := OrderedCollection new.

(s includes:p) ifFalse:[
]].

[
|x i n p|

x := queue removeFirst.
p := x key.
i := (p indexOf:$_). (M at:i) do:[:m | |v| n := p copy. n at:i put:(p at:i+m-5); at:i+m-5 put:$_.
v:=(x value,(R at:m)).
(n to:4)=(n from:9) ifTrue:[
v printCR.
(n splitForSize:4) map:#printCR.
^ self
].
] loop.

# Python 372

This was longer than I expected, I might go back later and see if I can optimize more. It uses a pretty inefficient method of brute-forcing the answer, but it seems to consistently run at no more than 8 seconds on my relatively old laptop.

A=lambda s,i,n:s[:i]+n+s[i+1:]
def M(b):
i=b.find('_')
for d,n in([('L',i+1)]if i%4<3 else[])+([('R',i-1)]if i%4>0 else[])+([('D',i-4)]if i>4 else[])+([('U',i+4)]if i<8 else[]):yield d,A(A(b,i,b[n]),n,'_')
def F():
c=[('',raw_input())]
while 1:
for (m,b)in c:
if b[:4]==b[8:]:return m,b
c=[(m+d,n)for(m,b)in c for(d,n)in M(b)]
print F()

• Have you tried it with RRRRBG_BYYYY? I just tried it on ideone and it said "time limit exceeded" – durron597 May 14 '14 at 21:50
• @durron597 Yeah that seems to take well over the limit (I only tested with your example and some trivial cases :\ ) I will try to optimize it to stay within the limit later. It might help to add some of the longest examples to test in the question. (Off the top of my head I don't really know what these would look like or how many moves they would take) – KSab May 14 '14 at 21:59
• that is the longest example :) – durron597 May 14 '14 at 22:00

# Java 1364

I golfed this some but I'm sure there's plenty more I could do. For example I close the input stream which is not necessary ;) I just wanted to put something up.

import java.util.*;class F{enum D{R{B b(B i){return i.z==3?null:g(i,1);}},L{B b(B i){return i.z==0?null:g(i,-1);}},D{B b(B i){return i.y==2?null:g(i,4);}},U{B b(B i){return i.y==0?null:g(i,-4);}};abstract B b(B i);B g(B i,int f){f+=4*i.y+i.z;char[]s=i.s.toCharArray();s[i.e]=s[f];s[f]='_';return w.get(new String(s));}}enum C{_,G,B,R,Y;}class B{C[][]a=new C[3][4];String s;int y,z,e,c;B p;D d;B(String p){int i,j,q;for(i=0;i<3;i++){for(j=0;j<4;j++){q=4*i+j;a[i][j]=C.valueOf(p.substring(q,q+1));if(a[i][j]==C._){y=i;z=j;e=q;}}}s=p;}boolean v(){return Arrays.equals(a[0],a[2]);}void p(B b,D n){p=b;d=n;c=p.c+1;}String g(){String u="\n";for(int i=0;i<3;i++,u+="\n")for(int j=0;j<4;j++)u+=a[i][j];return u;}}Set<B>b=new HashSet<B>(),p;static Map<String,B>w=new HashMap<>();void p(String f,String s){int n=s.length();if(n==0){B o=new B(f);w.put(f,o);if(o.v())b.add(o);}else{Set e=new HashSet();for(int i=0;i<n;i++){char c=s.charAt(i);if(!e.contains(c)){p(f+c,s.substring(0,i)+s.substring(i+1,n));e.add(c);}}}}public static void main(String[]a){new F().r();}void r(){Scanner c=new Scanner(System.in);String t=c.nextLine();p("",t);for(int i=0;i<20;i++,b=p){p=new HashSet<>(b);for(B o:b)if(o.c==i)for(D d:D.values()){B n=d.b(o);if(n!=null&&!p.contains(n)){n.p(o,d);p.add(n);}}}B q=w.get(t);while(!q.v()){System.out.print(q.d);q=q.p;}System.out.println(q.g());c.close();}}

Ungolfed:

import java.util.*;

class F {
enum D {
R {
B b(B i) {
return i.z == 3 ? null : g(i, 1);
}
},
L {
B b(B i) {
return i.z == 0 ? null : g(i, -1);
}
},
D {
B b(B i) {
return i.y == 2 ? null : g(i, 4);
}
},
U {
B b(B i) {
return i.y == 0 ? null : g(i, -4);
}
};

abstract B b(B i);

B g(B i, int f) {
f += 4*i.y + i.z;
char[] s = i.s.toCharArray();
s[i.e] = s[f];
s[f] = '_';

return w.get(new String(s));
}
}

enum C {
_, G, B, R, Y;
}

class B {
C[][] a = new C[3][4];
String s;

int y,z,e,c;

B p;
D d;

B(String p) {
int i,j,q;
for(i = 0; i < 3; i++) {
for(j = 0; j < 4; j++) {
q=4*i+j;
a[i][j] = C.valueOf(p.substring(q,q+1));
if(a[i][j] == C._) {
y = i;
z = j;
e = q;
}
}
}

s = p;
}

boolean v() {
return Arrays.equals(a[0], a[2]);
}

void p(B b, D n) {
p = b;
d = n;
c = p.c + 1;
}

String g() {
String u = "\n";
for(int i = 0; i < 3; i++,u+="\n")for(int j = 0; j < 4; j++) u += a[i][j];
return u;
}
}

Set<B> b = new HashSet<B>(),p;
static Map<String, B> w = new HashMap<>();

void p(String f, String s) {
int n = s.length();
if (n == 0) {
B o = new B(f);
w.put(f, o);
}
else {
Set e = new HashSet();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if(!e.contains(c)) {
p(f + c, s.substring(0, i) + s.substring(i+1, n));
}
}
}
}

public static void main(String[] a) {
new F().r();
}

void r() {
Scanner c = new Scanner(System.in);
String t = c.nextLine();

p("", t);

for(int i = 0; i < 20; i++, b=p) {
p = new HashSet<>(b);

for(B o : b)
if(o.c == i)
for(D d : D.values()) {
B n = d.b(o);
if(n != null && !p.contains(n)) {
n.p(o, d);
}
}
}

B q = w.get(t);
while(!q.v()) {
System.out.print(q.d);
q = q.p;
}
System.out.println(q.g());

c.close();
}
}

• Ungolfing the identifiers would be extremely helpful here... – AJMansfield May 19 '14 at 12:18
• @AJMansfield If you want to understand this you can read my code review version of the same code: codereview.stackexchange.com/questions/50962/… – durron597 May 19 '14 at 12:47


text:
# Transistor analysis

## Homework Statement

Just started learning about transistors, and I am having difficulty doing this problem.

The transistor in the circuit has $$k_n ^'=0.5mA/V^2, V_t=0.5 V, \lambda =0.$$
Show that operation at the edge of saturation is obtained when the following condition is satisfied
$$(\frac{W}{L})R_D=1.5 kΩ$$

## The Attempt at a Solution

As far as I know, if it is operating in on the edge of saturation, then
$$\frac{1}{2}k_m ^'(\frac{W}{L})v_{OV}$$
However, when I manipulate this equation, I am unable to get to $$(\frac{W}{L})R_D=1.5 kΩ$$

Can anyone provide me some guidance on this?

Related Engineering and Comp Sci Homework Help News on Phys.org
Thanks anyways, but I figured it out.

Hi, I'm bumping this old post because I am currently trying to work through the same problem but can't quite figure it out. I have the same equations that were mentioned in the original post.

Any guidance would be appreciated.


text:
Notes On Definite Article - Usage - CBSE Class 9 English Grammar
Use of the Definite Article or “The” when we talk about a particular person or thing we use the definite article “the”. Let’s go to the park. Which one we mean the park in this town The book you want is out of print. Which book? The one you want. The girl cried. Which girl? The girl already talked about. When a singular noun is meant to represent a whole class; as,       The cow is a useful animal.       The horse is a noble animal.       The cat loves comfort. The two nouns man and woman can be used in general sense without either article.         Man is mortal. Before the name of rivers, oceans, seas, canals, deserts, groups of islands and mountain-ranges. e.g. The black sea. , The British island. Before the name of religious, certain books and classical books. e.g. The holy book. Before names of things unique of their kind; as,        The sun, the sky, the earth. Before superlative degree; as,           Best, darkest. With ordinals; as,           He was the first man to arrive.           The ninth chapter of the book is very interesting. Before musical instruments; as,         He can play the flute. Before words denoting natural phenomenon; as,         The day, the night, the sunset, the rainbow. Before the name of directions; as The east, The west.

#### Summary

Use of the Definite Article or “The” when we talk about a particular person or thing we use the definite article “the”. Let’s go to the park. Which one we mean the park in this town The book you want is out of print. Which book? The one you want. The girl cried. Which girl? The girl already talked about. When a singular noun is meant to represent a whole class; as,       The cow is a useful animal.       The horse is a noble animal.       The cat loves comfort. The two nouns man and woman can be used in general sense without either article.         Man is mortal. Before the name of rivers, oceans, seas, canals, deserts, groups of islands and mountain-ranges. e.g. The black sea. , The British island. Before the name of religious, certain books and classical books. e.g. The holy book. Before names of things unique of their kind; as,        The sun, the sky, the earth. Before superlative degree; as,           Best, darkest. With ordinals; as,           He was the first man to arrive.           The ninth chapter of the book is very interesting. Before musical instruments; as,         He can play the flute. Before words denoting natural phenomenon; as,         The day, the night, the sunset, the rainbow. Before the name of directions; as The east, The west.
Previous
Next


text:
# Tag Info

18

The idea is quite simple: Since any great circle can be parametrized as $\cos(\theta)u + \sin(\theta)v$ where $u$ and $v$ are two orthonormal vectors. One can start with $u=\{1,0,0\}, v=\{0,1,0\}$ and use RotationTransform to get out of the xy plane, then use RotationTransform again to spin around the z-axis to get all great circles with desired inclination. ...

16

This is just a quick sketching out of an answer (rescales galore!) textOnCurve[text_, f_, n_, p_: 0.01] := Text[Rotate[text, ArcTan @@ (f[Rescale[n + p, {0, 1}, {p, 1 - p}]] - f[Rescale[n - p, {0, 1}, {p, 1 - p}]])], f[n]] textCurve[string_, f_, stylef_: (# &), range_: {0, 1}] := With[{chars = ...

13

Here's a simple method that seems to work. Call the grid above img. Find the best/strongest line in the image: lines = ImageLines[img, MaxFeatures -> 1] We'll need the slope of this line - here's a function to do that slope[s_, e_] := ArcTan@@(e - s); (shorter version thanks to nikie). This can be applied as slopeLine = First[slope @@@ lines] For ...

13

Here is a static solution to the problem. It shows a mesh on the sphere that represents the normal lat-long coordinate system. A function representing the equator. equator[θ_] := {Cos[θ], Sin[θ], 0} A function and a plot representing the inclined circle. Note that the inclination is accomplished by a rotation of the equator about the x-axis. ...

11

Here's another way...Text[] has a direction argument, so ArcTan is not necessary. txt1 = "Now we can follow" // Characters; txt2 = "an arbitrary path" // Characters; f[t_] := {Cos[2 \[Pi] t], Sin[6 \[Pi] t]}; totalarclength = NIntegrate[Sqrt[f'[\[Tau]].f'[\[Tau]]], {\[Tau], 0, 1}]; invarclength = First@NDSolve[{D[$t[s], s] == 1/Sqrt[f'[$t[s]].f'[$t[s]]], ... 9 Great answers have already appeared. In the spirit of demonstrating multiple solutions to a problem with Mathematica, I would like to offer one using a different approach. First, some geometric analysis. This great circle bounds a hemisphere lying in a half-space determined by a normal direction to the circle's plane. Letting$\theta$be the latitude at ... 9 AbsoluteOptions is known as very buggy function and the bug in determining the true PlotRange has very long history... You could try my Ticks-based workaround for getting the complete PlotRange (with PlotRangePadding added): completePlotRange[plot:(_Graphics|_Graphics3D)] := Quiet@Last@ Last@Reap[ Rasterize[ Show[plot, Axes -> True, ... 8 If you have v9, here's an alternative solution: first I calculate the gradient and gradient orientation for each pixel gray = ColorConvert[img, "Grayscale"]; orientation = GradientOrientationFilter[gray, 3]; gradient = GradientFilter[gray, 3]; then I create a weighted histogram from those: wd = WeightedData[Flatten[ImageData[orientation]], ... 6 Surely a better solution exists! Assuming m your matrix. m = RandomReal[1, {1000, 1000}]; pat = Array[(-1)^# &, First@Dimensions[m]]; B1 = (pat #) & /@ Reverse[m, {1, 2}]; // AbsoluteTiming {0.124800, Null} Though Table is intuitive but will be pretty slow for big lists. u = Length[m]; B = Table[ m[[u - r, u - s]]*(-1)^(s + 1), {r, 0, u - ... 5 As an addition to @bills's answer you can rotate by the mean of the slope of all the detected lines. slopeLine = slope @@@ lines meanslope = Mean@Join[Select[slopeLine, # > -1 &], Select[slopeLine, # < -1 &] + Pi/2] ImageRotate[img, -meanslope] 5 On many platforms, matrix operations are really fast, so using them is a good idea. (You have to get their dimensions correct, though!) SparseArray objects are likely to be efficient in RAM and time usage. All we have to do is code the rules used to generate the right and left matrices: arrange[c_] := Block[{m, n, sa}, {m, n} = Dimensions[c]; ... 4 If the problem is that the transformation function is slow to compute, a simple way to create and use a look-up table is to memoize the function: (* create an example image *) image = RandomImage[1, {30, 20}, ColorSpace -> "RGB"] ~ ImageResize ~ Scaled[10] (* define the transformation function with memoization *) mem : func[{x_, y_}] := mem = {x + 0.01 ... 4 A completely stupid workaround that perhaps someone knows how to automate: Create a Graphics object Graphics[{GeometricTransformation[Rectangle[], RotationTransform[1.]]}] Right click the Graphics and select Get Coordinates Drag around a bit in the graphics AbsoluteOptions[< Put the object here >, PlotRange] gives the correct PlotRange It also ... 3 You could use Reverse for the first part and define a helper function to do the rest : rM[avector_, {m1_, m2_}] := Module[{nc, local, rules}, nc = Length[avector]/2; local = {m1, m2} # & /@ Partition[avector, 2]; Flatten[ReplacePart[local, (# -> local[[ nc + 1 - #]]) & /@ Range[nc]], 1] ] The argument {m1, m2} will be used to multiply ... 3 ImageTransformation works with functions, not tables. It should be straightforward to define a function that carries out the same transformation as the table, but you will need to be aware that the #[[1]] and #[[2]] arguments go from 0 to 1 (across the image) so you will need to design the function to handle this input range. For example, you might want a ... 3 arrngF1 = MapAt[-1 # &, #[[Range[Dimensions[#][[1]], 1, -1], Join @@ Reverse@Partition[Range[Dimensions[#][[2]]], {2}]]], {;; , 2 ;; ;; 2}] &; arrngF2 = Module[{temp = #[[Range[Dimensions[#][[1]], 1, -1], Join @@ Reverse@Partition[Range[Dimensions[#][[2]]], {2}]]]}, temp[[;; , 2 ;; ;; 2]] = (-1) temp[[;; , 2 ;; ;; 2]]; temp] &; ... 2 I think you have to make sure that your transformation function always handles input cleanly. Here's a test you can do to see what goes into your function. (And I think you can use real coordinates if you use the DataRange option.) i = ImageResize[ExampleData[{"TestImage", "Mandrill"}], {20, 20}]; The function: f[pt_] := (Print[pt]; {pt[[1]], pt[[2]]}); ... 1 There is a Wolfram Blog post that explains this as a subproblem: Mapping GPS Data, by Robert Raguet-Schofield. That was published in 2009 and I think is pretty nifty. But I'd recommend looking into out new URLFetchAsynchronous and perhaps updating the code. Below you see parts in the blog where he seamlessly goes from patches to a single map: 1 Ok, I feel sorry for myself by now... This was easier than I thought... So here's my proposition for a solution : Given matrix$\mathbf A$written in mathematica as : A = {{a, b, i, j}, {c, d, k, l}, {e, f, m, n}, {g, h, o, p}} To obtain matrix$\mathbf B\$ I did this : u = Length[A]; B = Table[A[[u - r, u - s]]*(-1)^(s + 1), {r, 0, u-1}, {s, 0, u-1}] ...

1

I don't know why Normal does not work, but you can perform at least the transformation shown like this: pts = {{-0.36551249999999996, -0.29021463333333336}, \ {-0.36509784999999995, -0.2812481916666667}, {-0.3619309499999999, \ -0.2645122083333334}, {-0.3592788999999999, -0.25668636666666667}, \ {-0.3520880999999999, -0.2419782333333334}, ...

Only top voted, non community-wiki answers of a minimum length are eligible


text:
Virtual Machines#

What are Virtual Machines?#

Virtual Machines (VMs) essentially package a whole computer as an app that can be run. As an example, the figure below shows a windows laptop (note the windows search button in the lower-left corner) running a virtual ubuntu machine (note the terminal outputting the operating system). The machine running the VM is called the host machine.

Using software like VirtualBox or Vagrant, a user can create and run any number of VMs. As you could probably guess, having several VMs running at once can be a drain on memory. So just because you can run several VMs does not mean you should.

Users can download, install, backup and destroy VMs at will, which is why they are an attractive tool for sharing reproducible research. Research often requires specific pieces of software or system settings. If a researcher wishes to reproduce another’s work on their computer, making the necessary changes to their environment to run the project may impact their work. For example, in the Why This is Useful section of this chapter, we described how using a different version of Python can lead to unexpected changes in the results of an analysis. Say a researcher installs an updated version of Python to replicate an analysis because the analysis requires features only present in the updated version. By doing so, they put their own work at risk. VMs remove that risk; any tools downloaded or settings changed will only impact the VM, keeping the reproducer’s research safe. If they do inadvertently break something in the VM, they can delete it and make another one. VMs are effectively a quarantined area.

Using Virtual Machines for Reproducible Research#

Virtual machines can be shared by exporting them as single files. Another researcher can then import that file using their own virtualisation software like VirtualBox and open up a copy of the VM which will contain all the software files and settings put in place by the person that made the VM. Therefore in practice, they will have a working version of the project without the pain of setting it up themselves.

Setting up a Virtual Machine#

First, choose a tool for generating VMs. Here the widely-used VirtualBox is chosen. Download and install it on your system. To create a new machine, click “New” in the top left. A window will pop up where you can enter a name for the machine and select what operating system (and version) to use. In the figure below, a machine called demo_VM running Ubuntu is being created:

As you click through, you can adjust other features of the machine to be created, such as how much memory it should have access to. The default options are suitable for most purposes, but this process permits customisation.

Starting a Virtual Machine#

To start a virtual machine, select the machine from the list of VMs on the left, and click the green Start arrow at the top:

Sharing Virtual Machines#

A researcher can do work on their VM, and then export it. To export a VM, click File in the top left and then Export. This will export the VM as a single file which can be shared.

Someone that has access to this file and VirtualBox installed just needs to click File in the top left, then Import to select that file. Once it is imported, they can start the VM as described before, by selecting it from the menu clicking the green start arrow at the top.

Declarative Virtual Machines with Vagrant#

Vagrant is a tool which “enables users to create and configure lightweight, reproducible, and portable development environments”. In this context, an environment is a virtual machine (its CPUs, RAM, networking and so on) and the machines state (operating system, packages). Vagrant can set up virtual machines using text scripts, instead of pointing and clicking through a graphical user interface. This makes it particularly useful for automating the process of setting up virtual machines and making that process reproducible.

How Vagrant Works#

Unlike some other tools you may use to create or manage virtual machines, like VirtualBox and QEMU, Vagrant does not have its own hypervisor. Instead, Vagrant uses providers to interact with other virtualisation tools. Vagrant has built in providers for VirtualBox, Hyper-V and Docker. Other providers can be supported by plugins. In particular, the Vagrant developers maintain an official plugin for VMWare. For Linux users there is also a community supported provider for libvirt.

Note

A hypervisor is software which allows virtual machines to interact with host machines hardware at a low level. This article from Red Hat gives a good overview.

Vagrant environments can be packed into boxes. When using Vagrant you will most likely start from an existing box and build your environment on top of it. You can browse and search for public boxes here.

After deploying a box, Vagrant can also use provisioners to apply further configuration. This is useful to adapt a generic box to a specific purpose, for example by installing packages. Provisioning can be as simple as a shell script but can also incorporate powerful configuration management tools like Ansible, Puppet and Chef.

The Vagrantfile#

With Vagrant, users can define the configuration of a virtual machine (or group of virtual machines) in a declarative configuration language stored in a Vagrantfile. This configuration is written in the Ruby programming language. However, it is not necessary to know Ruby as the syntax is simple and the documentation explains all of the available options.

Attention

For Vagrant to recognise a Vagrantfile file, it must be called Vagrantfile.

Defining the virtual machines in plain text has a number of advantages over distributing full virtual machine images:

• The files can be checked into version control

• Small size makes them fast and easy to share

• Users can reproducibly build environments

• A single definition can potentially work across multiple hypervisors (like VirtualBox, VMWare, libvirt)

In combination these qualities support Vagrant’s goals of lightweight, portable and reproducible environments. A project can maintain its development environment alongside the source code and every contributor can use the environment with minimal barriers.

The Vagrant CLI#

You will most likely use vagrant through the command line interface (CLI). The CLI can be used to:

• manage machines with commands like vagrant up, vagrant halt and vagrant destroy

• connect to machines with vagrant ssh and vagrant powershell

• get, package and publish boxes

• create minimal a Vagrantfile with vagrant init

Full documentation for all commands can be found here.

Syncing Data#

Vagrant can help sharing data between the host and the virtual machine by syncing directories. By default, the directory containing the Vagrantfile is mounted at /vagrant on the guest. Therefore, if you keep a Vagrantfile in the root of a git repository, when you use the Vagrant environment you will find your project at /vagrant. This makes it convenient to develop, build and test your project within the environment.

Additional shared directories can be declared as explained in the documentation.

Attention

Some boxes may not have any shared directories, so it is best to explicitly define any that you want in your Vagrantfile. In particular, the ‘generic’ images built by Roboxes do not have any mounts by default. These boxes are popular as they cover a wide variety of distributions and support a multiple hypervisors.

A Virtual Machine for The Turing Way#

Here we will walk through some important part of a Vagrantfile by designing an environment to build The Turing Way. Building the book this way might help keep your host system clean from build dependencies. It could also help debug problems as multiple people can better ensure they are using the same environment to work on the book.

The Vagrantfile#

You can find the full Vagrantfile in the root of The Turing Way git repository. We will then use some of the Vagrant CLI commands to provision the machine and use it to build the book.

The top level block of the Vagrantfile specifies the Vagrant configuration version. This will help maintain backwards compatibility if new versions are released. All other configuration is contained within this block.

Vagrant.configure("2") do |config|
...
end

Next the box to build our environment from is specified.

config.vm.box = "generic/fedora36"

This is a box for version 36 of the Fedora Workstation Linux distribution. The generic org creates boxes of many Linux distributions for multiple hypervisors. This makes them useful for creating environments which can be run by users on different operating systems.

The virtual machine’s hostname is defined, and The Turing Way project directory is mounted at /vagrant inside the virtual machine.

config.vm.hostname = 'theturingway'

config.vm.synced_folder "./", "/vagrant"

The number of virtual CPUs and amount of memory are set in provider specific blocks. In this example two virtual CPUs and 2048MB of RAM are allocated for the VirtualBox and libvirt providers.

Provider specific overrides can also be specified in provider blocks. In this example the synced directory settings are changed for libvirt to improve NFS compatibility. NFS is the default method to sync folders for libvirt.

config.vm.provider "virtualbox" do |vb|
vb.cpus = 2
vb.memory = 2048
end

config.vm.provider "libvirt" do |lv, override|
lv.cpus = 2
lv.memory = 2048

override.vm.synced_folder "./", "/vagrant", nfs_udp: false
end

The shell provisioner is used to install the packages necessary to build the book. First a script is defined to install pip, then use pip to install the python requirements as explained in the book README. The script is then passed to the provisioner.

$script = <<-'SCRIPT' dnf install -y python3-pip sudo -u vagrant pip install --no-warn-script-location -r /vagrant/book/website/requirements.txt SCRIPT config.vm.provision "shell", inline:$script

Building the book#

Here we will show how to use The Turing Way Vagrant machine to build the book. First you will need to make sure you have installed Vagrant and a compatible provider. VirtualBox will probably be the easiest provider to use as it is supported on Linux, MacOS and Windows. Windows users can also try Hyper-V, which is included in some editions of Windows 10 and Windows 11.

If you haven’t already, clone The Turing Way repository and change to the projects root directory.

$git clone https://github.com/alan-turing-institute/the-turing-way.git$ cd the-turing-way

Now create the virtual machine. The output will show Vagrant creating the machine as well as the provisioner script installing the build dependencies. Windows users can modify this command to vagrant up --provider hyperv to use Hyper-V.

$vagrant up You can now connect to the machine with SSH. Vagrant has a convenient wrapper to make this simple.$ vagrant ssh

The project directory has been mounted at /vagrant on the guest. We can change to the book/website directory and build the book like in the README.

[vagrant@theturingway ~]$cd /vagrant/book/website/ [vagrant@theturingway website]$ jupyter-book build .

As the directory is shared with the host system, you will be able to see the built book on your computer and view it in your browser.

When you are done you can exit the virtual machine, and halt it. You can also destroy the virtual machine to clean up all storage associated with it.

[vagrant@theturingway ~]$exit$ vagrant halt
\$ vagrant destroy


text:
Rectangles

How many different rectangles can be made from 60 square tiles of 1 m square? Find the dimensions of these rectangles.

Result

n =  6

Solution:

$S = ab = 60 \ \\ a>b \ \\ 60 = 2 \times 2 \times 3 \times 5 = 2^2 \times 3 \times 5 \ \\ \ \\ a_{ 1 } = 10, b_{ 1 } = 6 \ \\ a_{ 2 } = 12, b_{ 2 } = 5 \ \\ a_{ 3 } = 15, b_{ 3 } = 4 \ \\ a_{ 4 } = 20, b_{ 4 } = 3 \ \\ a_{ 5 } = 30, b_{ 5 } = 2 \ \\ a_{ 6 } = 60, b_{ 6 } = 1 \ \\ \ \\ n = 6$

Our examples were largely sent or created by pupils and students themselves. Therefore, we would be pleased if you could send us any errors you found, spelling mistakes, or rephasing the example. Thank you!

Leave us a comment of this math problem and its solution (i.e. if it is still somewhat unclear...):

Be the first to comment!

Following knowledge from mathematics are needed to solve this word math problem:

Do you solve Diofant problems and looking for a calculator of Diofant integer equations?

Next similar math problems:

1. Trapezium 2
Trapezium has an area of 24 square cms. How many different trapeziums can be formed ?
2. Class 9A
On the final certificate have one quarter of the class 9A mark "C" of mathematics, seventh mark "C" from the Czech language and two students failed in chemistry. How many students attend class 9A?
3. The florist
The florist had 200 roses in the morning. During the day, more than half sold it. From the remaining roses, it will tie the bouquet. If a bouquet of 3, 4, 5 or 6 roses are bound, one always remains. How many roses from the morning shipment sold?
4. Girls
The boys and girls in the class formed without the rest of the fives, 2 girls and 3 boys. There are 6 girls missing to create mixed pairs (1 boy and 1 girl). How many girls are in the classroom?
5. Factory
In the factory workers work in three shifts. In the first inning operates half of all employees in the second inning and a third in the third inning 200 employees. How many employees work at the factory?
6. Digit sum
Determine for how many integers greater than 900 and less than 1,001 has digit sum digit of the digit sum number 1.
7. Window
Peter demolish box hole in the wall for window frame 147×51 cm. When they came masters fitted frame and window will be found that glass is 13.3 cm from the hole in each direction. Calculate how much percent less light enters the window than hole?
8. Tiles path
A rectangular park measures 24mX18m. A path 2.4m wide is constructed all around it. Find the cost of paving the path with cement tiles of size 60cm X 40cm at the rate of \$5.60 per tile ?
9. Rectangular field
One dimension of the rectangular field is 56 m greater than second dimension. If each side of the rectangle increases by 10 m, increases the surface field is 1480 m2 . Determine dimencions of the field.
10. Lawns
Before a sports hall are two equally large rectangular lawns, each measuring 40 m and 12 m. Maintenance of 10m² lawn cost 45 CZK yearly. On each lawn is circular flowerbed with a diameter 8 meters. How much money is needed each year to take on lawn care?.
11. Raffle
In the pool is numbers from 1 to 115. What is the probability that a randomly selected number is not a prime number?
12. Solve 2
Solve integer equation: a +b+c =30 a, b, c = can be odd natural number from this set (1,3,5,7,9,11,13,15)
13. Summands
Find two summands of the number 42, so that its product is minimized.
14. Z7-I-4 stars 4949
Write instead of stars digits so the next write of product of the two numbers to be valid: ∗ ∗ ∗ · ∗ ∗ ∗ ∗ ∗ ∗ ∗ 4 9 4 9 ∗ ∗ ∗ ∗ ∗ ∗ 4 ∗ ∗
15. Tissues
The store got three kinds of tissues - 132 children, 156 women and 204 men. Tissues each species were packed into boxes after the number of pieces the same for all three types (and greatest). Determine the number, if you know that every box has more than 6
16. Equation
Solve the equation: 1/2-2/8 = 1/10; Write the result as a decimal number.
17. Cable
Cable consists of 8 strands, each strand consists of 12 wires with diameter d = 0.5 mm. Calculate the cross-section of the cable.