Rust "error: moving out of immutable field" |
While the error does tell you where you're trying to move the value from it
doesn't indicate where you're trying to move it to which might help make it
a bit clearer why it doesn't work.
The problem is that you have a unique pointer
(Option<~HTTPRequestHeader>) which means you either need to take a
reference to it or make a copy. Since they can only have a single owner
they are moved by default. Which is what is happening in the Some(next_hdr)
branch of your match.
So what you probably want is something like this:
fn print_headers(hdr: &HTTPRequestHeader) {
println(fmt!("%s: %s", hdr.name, hdr.data));
match hdr.next {
Some(ref next_hdr) => print_headers(*next_hdr),
None => {}
}
}
Also, a side note: if you want to access a field of some struc
|
Chrome: How to solve "Maximum call stack size exceeded" errors on Math.max.apply( Math, array ) |
To me the error shouldn't come from the call into Math.min / max it looks
like the result of using recursion which I cannot beleive Chrome would use
to implement those functions.
Are they embeded in recursive code?
You can roll your own min / max code trivially to avoid the problem in
Chrome.
|
error in pow from math.h |
Your factor is (int)1 / (int)9 which is (int)0; Almost anything raised to
the zeroth power is one
you could do something like this
double factor = 1/9.0; // make sure the 9 is a floating point
|
javascript Math.atan( Math.tan() ) useless? |
atan(tan(x)) is a periodic "sawtooth" function:
for -pi/2 < x < pi/2, atan(tan(x)) = x
for pi/2 < x < 3pi/2, atan(tan(x)) = x - pi
for 3pi/2 < x < 5pi/2, atan(tan(x)) = x - 2pi
...
You can plot it and see other details about it on Wolfram Alpha.
|
Math.pow(0.0, 0.0) returns 1; should be undefined or error ? |
Because that's exactly what the Javadocs say it will do:
public static double pow(double a, double b)Returns the value of the
first argument raised to the power of the second argument. Special cases:
* If the second argument is positive or negative zero, then the result is
1.0.
|
tkinter math program type error |
From what I can see, config[user]['right'] is a string. If so, you can't
add 1 to it because 1 is an integer and strings and integers cannot be
added together. The + operator only puts together two things of the same
type. So, if you want to add 1 to config[user]['right'], you have to first
convert it to an integer like this:
int(config[user]['right']) + 1
or, if you want to put the character 1 on the end of config[user]['right'],
you have to first make 1 a string like this:
config[user]['right'] + '1'
|
How to handle "Error in function boost::math::cyl_bessel_k(d,d): numeric overflow" |
Well the obvious answer seems to be to not pass 0, but if that is not
feasible, and you are ok with the function failing, you can catch the
exception and handle it in a way that seems right. The program wont crash
then.
This tutorial might help explain deeper what you should do.
|
Lifetimes in Rust |
Update 2015-05-16: the code in the original question applied to an old
version of Rust, but the concepts remain the same. This answer has been
updated to use modern Rust syntax/libraries. (Essentially changing ~[] to
Vec and ~str to String and adjusting the code example at the end.)
Is my understanding vaguely accurate?
[...]
What is the difference between a parameter of type &str and a
parameter of type &'a str in the example above?
Yes, a lifetime like that says essentially "no restrictions", sort of.
Lifetimes are a way to connect output values with inputs, i.e. fn
foo<'a, T>(t: &'a T) -> &'a T says that foo returns a
pointer that has the same lifetime as t, that is, the data it points to is
valid for the same length of time as t (well, strictly, at le
|
Rooting managed value in Rust |
Take a look at https://github.com/mozilla/rust/issues/5723 (and also at the
source of std::io::with_str_reader).
Basically, with_str_reader is fundamentally unsound at present, and what
you're doing is tripping it up badly, because letting the value escape from
the closure like that isn't supposed to be permitted—the with_foo pattern
means you can use that inside and inside only.
|
interfacing Rust with Berkeley DB |
Given the sheer size and complexity of the DB struct, there doesn't appear
to be a "clean" way to expose the whole thing to Rust. A tool similar to
C2HS to generate the FFI from C headers would be nice, but alas we don't
have one.
Note also that the Rust FFI can't currently call into C++ libraries, so
you'll have to use the C API instead.
I'm not familiar with the DB APIs at all, but it appears plausible to
create a small support library in C to actually create an instance of the
DB struct, then expose the public members of the struct __db via getter and
setter functions.
Your implementation might look something like this:
[#link_args = "-lrust_dbhelper"]
extern {
fn create_DB() -> *c_void;
fn free_DB(db: *c_void);
}
struct DB {
priv db: *c_void
}
impl Drop for DB {
|
How do I compile a multi-file crate in Rust? |
You just need to put the use at the top of the file:
use thing::asdf::*;
mod thing;
fn main() {}
This looks very strange, but
It's what the error message says (anything that you can put at the top
level that is not use or extern mod is an "item", including mods), and
It's how Rust name resolution works. use is always relative to the top of
the crate, and the whole crate is loaded before name resolution happens, so
use thing::asdf::*; makes rustc look for thing as a submodule of the crate
(which it finds), and then asdf as a submodule of that, etc.
To illustrate this last point better (and demonstrate the two special names
in use, super and self, which import directly from the parent and current
module respectively):
// crate.rs
pub mod foo {
// use bar::baz; // (an error,
|
Rust inheritance: call parent method |
It's not quite the same under the hood, but something like
trait DoThings {
fn do_something(&self);
}
struct Parent;
impl DoThings for Parent {
fn do_something(&self) { println("doing something"); }
}
struct Child {
parent: Parent
}
impl DoThings for Child {
fn do_something(&self) {
self.parent.do_something();
println("child");
}
}
fn main() {
let c = Child { parent: Parent };
c.do_something();
}
There are a few proposals for making parts of this automatic (e.g. if we
wanted to just call the parent's method directly, i.e. don't override the
method in the child, then currently one has to explicitly call the parent's
method oneself).
|
How do I manage optional owned pointers in rust? |
Rust is sufficiently different to C++ that a straight line by line
translation will give non-idiomatic code. This isn't really a full answer,
just a collection of bits and pieces:
When returning information from inside a structure, writing the function as
fn foo<'a>(&'a self) -> &'a SomeInformation is the normal
way (with str's and []'s treated specially): so
pub fn get_file_name<'a>(&'a self) -> &'a str {
match self._include_data {
Some(ref data) => &data.file_name,
_ => fail!("No FileData")
}
}
pub fn getIncludeData<'a>(&'a self) -> &'a FileData {
match self._include_data {
Some(ref data) => &*data,
_ => fail!("No FileData")
}
}
The 'a marker is a named lifetime,
|
Sharing Mutable Variables Between Threads In Rust |
In the case of sharing the string "Hello, World!", you'd just need to move
the variable back into an immutable location (e.g., "let mut msg = .....;
let msg = msg;").
Probably you also want to avoid making a separate copy of the hashmap for
each thread that's receiving it, though, in which case you'll want to also
put it inside an ARC (atomically reference counted wrapper), which you'll
find in extra::arc.
|
Does Rust have support for functions that return multiple values? |
In Rust you can return a tuple with more than one value:
fn my_func() -> (u8, bool) {
(1, true)
}
A language returning more than a value is probably emulating this with a
tuple or another data structure as in most calling conventions the return
value is in only one register.
Can not tell about Go, but there are high chances they are just emulating
the multiple values inside a tuple and compile-time forcing you to manage
the returns.
I don't see any problem with rust doing this as this is how ocaml or
haskell (and others) manages it, and they enforce type checking in the
return values (or tuple) so chances something goes bad are low. The most
common way to manage the return values are deconstructing the tuple in two
or more bindings (let a, b = tuple_2()).
Just my two cents, fe
|
What is the easiest way to determine if a character is in Unicode range, in Rust? |
The simplest way, assuming that they are not Unicode categories (in which
case you should be using std::unicode) is to use the regular comparison
operators:
(s >= 'x01' && s <= 'x08') || s == 'U0010FFFE' || s ==
'U0010FFFF'
(In case you weren't aware of the literal forms of these things, one gets
8-bit hexadecimal literals xXX, 16-bit hexadecimal literals uXXXX, and
32-bit hexadecimal literals UXXXXXXXX. Matter of fact, casts would work
fine too, e.g. 0x10FFFE as char, and would be just as efficient; just less
easily readable.)
|
Math.Pow() vs Math.Exp() C# .Net |
Math.Pow(Math.E,n) = Math.Exp(n) //of course this is not actual code, just
a human equation.
More info: Math.Pow and Math.Exp
|
Where clause with math |
You can define your "Contacted" column as int and then use PHP functions
like strtodate() and datetostr() ,... to convert that integer into any
format you want and do arithmetic operations on it.
for example you can user PHP date("u") function, this will return time as
an integer so you can easily save it into DB and manipulate it.
|
Golang, math/big: what is the max value of *big.Int |
Here are the structure definitions :
// A Word represents a single digit of a multi-precision unsigned integer.
type Word uintptr
type nat []Word
type Int struct {
neg bool // sign
abs nat // absolute value of the integer
}
type Rat struct {
// To make zero values for Rat work w/o initialization,
// a zero value of b (len(b) == 0) acts like b == 1.
// a.neg determines the sign of the Rat, b.neg is ignored.
a, b Int
}
There is no explicit limit. The limit will be your memory or,
theoretically, the max array size (2^31 or 2^63, depending on your
platform).
If you have practical concerns, you might be interested by the tests made
in http://golang.org/src/pkg/math/big/nat_test.go, for example the one
where 10^100000 is benchmarked.
And you can easily run this
|
qt returns bad math |
12 * 1000000 * 3800 = 45.6 billion.
This is out of range for a 4 byte signed integer, which is what int usually
is. Try using long long instead.
The default type of an integer literal is int, unless the number is too big
to fit in an int. As long as you are doing math operations between ints,
the results remain as ints. 12 is an int, 1000000 is an int, and 3800 is
an int. When you multiply them together, the result is still an int, even
though it no longer fits. Add the LL suffix to make the integer literal a
long long. i.e. 12LL, 1000000LL, 3800LL, etc...
|
How to fix my math class? |
You need to refer to self to access attributes on your class:
class pythagoras(math):
def __str__(self):
import math
return str(math.sqrt(self.x**2 + self.y**2))
A __str__ method must return a string value, so using __str__ for this is a
little.. weird. No need to override the __init__ method, you didn't do
anything new in it.
You may want to name your base class something other than math so you don't
mask the module (and not need to import it in your __str__ method). Best
practice is to use CamelCase names for classes; Math would be a better
choice.
For this kind of operation, I'd just use a function instead:
import math
def pythagoras(x, y)
return math.sqrt(x**2 + y**2)
At best, you'd make pythagoras a method on your math class:
import math
class Math()
|
Composition operator and pipe forward operator in Rust |
These operators do not exist in Rust as far as I know. So far I haven't
felt much of a need for them, and there is also an effort to keep the core
Rust syntax fairly small. For example, Rust used to have explicit message
passing operators, but these were removed.
You might be able to use operator overloading to come up with something
similar if you want, or just write your own compose or pipe forward
functions. I wouldn't be surprised if the Rust team were open to including
these in the standard library.
|
Strange math calculations in php |
If you want to do arithmetic on number, you can't have the thousands
separator (,). What's happening is 5,000.00 is being read as 5 (it stops
interpreting it as a number as soon as it hits the comma) and then you're
getting 5 - 100.10 which is -95.10 (I'm thinking you left off the .10 in
your example.
You'll need to convert first:
$value1 = floatval(str_replace(',', '', $original_value1))
$value2 = floatval(str_replace(',', '', $original_value2))
I'm assuming here that you have them as strings originally. These remove
the comma separator.
|
Putting math into the sql query |
SELECT fk_playerid, fname, lname, points, holes, points-2*holes diff
FROM (
SELECT SUM(ls.points) points
COUNT(ls.dk_playerid) holes,
ls.fk_playerid, u.fname, u.lname
FROM {$prefix}_livescore ls
INNER JOIN {$prefix}_users u
ON ls.fk_playerid = u.userid
WHERE fk_gameid = $gameid
GROUP BY fk_playerid) x
ORDER BY diff desc
|
JavaScript Math to PHP Page ID |
I'm guessing you're choosing a card from the major arcana based on the
birthday digits. If you don't care too much about how this is calculated,
here's a quick way to do it using modular arithmetic:
function getBirthCard() {
var month = document.getElementById("month").value;
var day = document.getElementById("day").value;
var year = document.getElementById("year").value;
var sum = parseInt(month) + parseInt(day) + parseInt(year);
var card = sum % 22 + 1; // this is always from 1 to 22
window.location.assign('http://arcanabazaar.com/results.php?id=' +
card);
return false;
}
The button to call this must be coded as:
<button type="submit" onclick="return getBirthCard();" class="btn
btn-large">What's My Card?</button>
The OnClick event must ret
|
Is the expression math.sqrt() necessary? |
Well, you can import a function directly like this:
from math import sqrt
# elsewhere
sqrt(n)
You can even import everything from the module:
from math import *
In that way you won't have to use the module prefix and say math.sqrt.
However, it's recommended that you do it, to avoid possible name clashes in
case two modules define a function with the same name (something that
happens quite often in practice). In short, this is the preferred way:
import math
# elsewhere
math.sqrt(n)
|
how to use decimal values in Math.pow() |
The first calculation should be:
(22.582d / 10.000d) * (1.0d/15.0d) - 1.0d
You use the "d" in literals to tell the compiler that the number should be
a double. If you don't use it the compiler thinks that 1/15 is two integers
divided resulting in 0.
So the last calculation should be:
double i = Math.Pow(2.2582d, 1.0d/15.0d) - 1.0d;
Response.Write(i);
This means that:
1/15 = 0
and
1.0d/15.0d = 0.06666667
|
JS Math.random doesn't get -9- |
If it is indeed only happening on item #9, it suggests to me some type of
number verses string problem.
First change the variable name of 'id' to something else, that name could
cause problems.
Then declare it at the top with a var, the same as you are doing with the
cobras array.
I would change 'id' to a string, and convert the result of the Math
function using parseInt.
Change the index values you are giving in the array to strings as well, so
they become keys instead.
Then add single quotes around the value given in the checkAnswer calls from
the area tags.
No guarantee that this would fix the problem, but at least you know for
sure that the random item, and the item chosen, are all strings.
|
Javascript Basic Math |
This $(this).find("#sqbTimestamp").html(tsInt + 1); code snippet change
amount of seconds in span container.
//Run countdown proecudure
countdownProcedure();
var runNo = 0;
function countdownProcedure(){
var interval = 10000;
var i = 0;
var seconds = null;
runNo++;
$(".rfqTbl tr").each(function(){
if(i > 0){
seconds = $(this).find("#sqbTimestamp").text();
var tsInt =
parseInt($(this).find("#sqbTimestamp").text());
$(this).find("#sqbTimestamp").html(tsInt + 1);
var days = Math.floor(seconds / (60*60*24));
seconds -= days * 60 * 60 * 24;
var hours = Math.floor(seconds / (60*60));
|
Working with math in javascript |
The period is the decimal point in the English language. If you want
"17.000" to be treated as seventeen-thousand and not seventeen, you have to
remove the period:
var pay = +document.getElementById("name").innerHTML.replace(/./g, '');
The unary plus (+) at the beginning converts the resulting string into a
number. This is not strictly necessary in your example but can avoid
problems in the long run.
Using parseFloat exposes the same problem as implicit type conversion.
If you want to format the number (i.e. convert it to a string with thousand
separators) again, have a look at How to print a number with commas as
thousands separators in JavaScript. Just use a period instead of a comma.
|
64-bit overflow math conversion |
Factorize your division:
r = 1000*(n/factor) + ((n%factor)*1000)/Factor
You could still run into problems if the remainder overflows (factor is
large) but if factor is less than MAX_UINT64/1000 you are ok.
|
Learning the math behind WebGL |
Specifically, I get what Math.tan(fovy / 2) is calculating, but why
take the inverse of it?
Because the focal distance d comes from the formula
Math.tan(fovy / 2) = y / d
to get the focal length you need to multiply by
1 / Math.tan(fovy / 2)
why take the inverse of the difference between the near boundary and
the far boundary? Also, why is out[11] set to -1 and what is the value
stored in out[14] for?
You can project (x,y,z) into (x*d/z, y*d/z) using the focal distance d.
This is enough but OpenGL requires a linear transformation to (x,y,z) such
as the projection gives coordinates in [-1,1]. Such normalized coordinates
simplify clipping and retain the z information used to remove hidden
surfaces.
out[11] is set to -1 because there's no linear transformation that giv
|
Rounding ** 0.5 and math.sqrt |
Both **0.5 and math.sqrt() perform the calculation using floating point
arithmetic. The input is converted to float before the square root is
calculated.
Do these calculations recognize when the input value is a perfect square?
No they do not. Floating arithmetic has no concept of perfect squares.
large integers may not be representable, for values where the number has
more significant digits than available in the floating point mantissa. It's
easy to see therefore that for non-representable input values, n**0.5 may
be innaccurate. And you proposed fix by adding a small value will not in
general fix the problem.
If your input is an integer then you should consider performing your
calculation using integer arithmetic. That ultimately is the right way to
deal with this.
|
What should I do to import math.py that is not stdlib |
Edit:
Sorry my mistake... This will never work. You can choose either to give
your top level package a name that doesn't conflicts with a name in the
standard library. Or the main script cannot be in the package directory. So
basically you can either:
Rename your module to my_math.py and then main.py can be in the same
directory and you can just do:
from my_math import c
c()
Or you make a package, for example folder name test (or any other name that
doesn't conflict with a standard library package) with files: __init__.py
and math.py, and in the same level as the test you create a main.py and
then the code will look like:
from test.math import c
c()
Folder structure:
.
|-- test
| |-- __init__.py
| `-- math.py
`-- main.py
|
PHP Eval Math Function for Bot |
As I stated in the comment there is no ** operator in php, the pow function
should be used instead ... what you can do to emulate it though is to throw
another preg_replace at the input.
$input = rtrim($this->get_message()); // grabbing the user input
$input = preg_replace('/([0-9.]+)**([0-9.]+)/', 'pow($1, $2)', $input);
$sum = $this->do_math($input);
|
Input Math With JS or/and HTML5 |
MathML could be worth looking at - even though it is not yet supported by
all browsers.
Another possibility could be to use latex syntax, like it is done in many
wikis. There are latex-rendering libraries available for ruby.
Other solutions are presented here:
http://www.intmath.com/blog/wp-content/math-rendering-comparison.php
|
C: The Math Behind Negatives and Remainder |
Like Barmar's linked answer says modulus in a mathematical sense means that
numbers are the same class for a ring (my algebra theory is a bit rusty so
sorry the terms might be a bit loosely used:)).
So modulus 5 means that you have a ring of size 5. i.e. 0,1,2,3,4 when
you add 1 to 4 you are back at zero. so -9,-4,1,6,11,16 are all the same
modulo 5 because they are all equivalent. This is actually very important
for various algebra theorems but for normal programmers it's pretty much
useless.
Basically the standards were unspecified so the modulus returned for
negative numbers just has to be one of those equivalent classes of numbers.
It's not a remainder. Your best bet in situations like this is to operate
on absolute values when doing modulo operators if you want basic integer
|
Math help for pseudo 3D in HTML |
Well, you have a projection from the cylinder to the plane. Since the y
dimension is uniform, we are only concerned about calculating the x
dimension.
You need to get, for a given x, what is the x coordinate of the background,
that wraps around a circle. if r is the radius or the circle, for an angle
a,the x coordinate of the projection, is r cos(a). And the coordinate of
the background is r a if a is expressed in radians. This means that for the
x coordinate (in the plane) the coordinate of the background is acos (x/r).
The datum that you need to set correctly the background for a given x is
the offset, and so acos(x/r)-x.
Now, in a spreadsheet, set all the x values from 0 to r in the a column. In
the b column, put the formula acos(x/r)-x.
And now, the last step, the optimization: all
|
math lib native Visual c++ |
What exactly do you mean when you refer to the "math library"? Do you mean
those parts of the standard C library that are defined and/or declared in
the math.h header file?
If so, then:
1) The C library is usually provided by the OS for runtime dynamic linking.
The compiler implementation usually provides any necessary libraries and
headers for use by developers.
2) Usually the compiler implementation will provide all standard libraries
and headers. On Windows, some compilers may be set up to use the standard
libraries provided by the OS instead of providing their own implementation.
Visual Studio is provided by the same vendor as the OS, so from that
perspective it's all the same thing, pretty much.
3) By referencing the documentation provided by Microsoft
4) Does what follow a stand
|
Math calculations in MySql WHERE |
You might try something like this...
SELECT
employee_id,
max_hours,
SUM(hours)
FROM
some_table
GROUP BY
employee_id
HAVING
SUM(hours) < (max_hours * 1.5)
|