text stringlengths 49 10.4k | source dict |
|---|---|
php, html, pdo
Of course, there are a few tradeoffs. Nothing too bad, but still:
PDOStatement::execute(array $bind) binds all of the values as PDO::PARAM_STR (ie string values). This implies you can't use array binding if you are using placeholders in, for example, LIMIT clauses. In those cases, a loop + $stmt->bindValue(':offset', $value, PDO::PARAM_INT); is required. Writing a wrapper that does this for you is not uncommon, and in some cases desirable.
re-use of placeholders is only supported if you're using PDO's emulated prepared statements:
Because you seem to be re-using the same placeholders here, you cannot disable emulated prepares. MySQL does not support the re-use of named placeholders. If you do disable emulated prepares, you will need to add a loop:
//create vals as before
$in = array_keys($vals);
$query = 'SELECT b.name,a.users
FROM `table1` a
INNER JOIN `table2` b
ON a.id = b.id
WHERE a.id IN ('.implode(','$in).')
GROUP BY a.id
ORDER BY FIELD(a.id, ';
foreach ($in as $idx => $key) {
$vals[$key.$idx] = $vals[$key];//add value a second time, using a different key
$in[$idx] .= $idx;//change values in $in
}
$query .= implode(',', $in).')';//add new placeholders to query
$stmt = $pdo->prepare($query);
$stmt->execute($vals);//should work now | {
"domain": "codereview.stackexchange",
"id": 9301,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, html, pdo",
"url": null
} |
Now we have to prepare set of inequalities:
eq = (List @@ B111[x, y])[[1, ;; , 2]] /. Or -> Sequence
points = DeleteCases[pointExtract /@ eq, {Repeated[{_, _}, 2]}];
(*we only take those with 3 or more points since we are not interested in lines and points*)
Graphics[{Hue@RandomReal[], Polygon[#]} & /@ points] (*domains plot*)
Below I have assumed that additional point is {1, 1, 1} (from B111 form) but it can be easily generalised.
Graphics3D[With[{len = Length@#},
GraphicsComplex[
({##, 0} & @@@ #)~Join~{{1, 1, 1}},
{Hue@RandomReal[], Thickness@.01,
Line[{##, len + 1} & @@@ Partition[{Sequence @@ Range[len], 1}, 2, 1]]}]
] & /@ points
, Boxed -> False]
First, not accurate approach
The question is: how much do you need to know about those borders.
If you just want to plot the regions the following method is simple enough:
eq = (List @@ B111[x, y])[[1, ;; , 2]]
RegionPlot[eq, {x, -.1, 2.2}, {y, -.1, 2.2}, PlotPoints -> 50, PlotStyle -> None,
BoundaryStyle -> Blue] | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9559813501370535,
"lm_q1q2_score": 0.8087051914999303,
"lm_q2_score": 0.8459424353665381,
"openwebmath_perplexity": 1780.0915471947997,
"openwebmath_score": 0.31127727031707764,
"tags": null,
"url": "http://mathematica.stackexchange.com/questions/28731/plot-the-boundaries-of-each-piece-of-a-piecewise-function"
} |
newtonian-mechanics, classical-mechanics, friction
& 1 & 1 & 1 & 1\\
& & \ddots & \vdots & \vdots\\
& & & 1 & 1\\
& & & & 1
\end{bmatrix}\begin{pmatrix}m_{1}g\\
m_{2}g\\
\vdots\\
m_{k-1}g\\
m_{k}g
\end{pmatrix} $$
So all together
$$ P - \left( A\,\mu A^{-1}\right) m\, g=m\ddot{x} $$
or with $ \mu_{SYS}=A\,\mu A^{-1} $
$$ \mu_{SYS}=\begin{bmatrix}1 & -1\\
& 1 & -1\\
& & \ddots & \ddots\\
& & & 1 & -1\\
& & & & 1
\end{bmatrix}\begin{bmatrix}\mu_{1}\\
& \mu_{2}\\
& & \ddots\\
& & & \mu_{k-1}\\
& & & & \mu_{k}
\end{bmatrix}\begin{bmatrix}1 & 1 & 1 & 1 & 1\\
& 1 & 1 & 1 & 1\\
& & \ddots & \vdots & \vdots\\
& & & 1 & 1\\
& & & & 1
\end{bmatrix} \\
\mu_{SYS}=\begin{bmatrix}\mu_{1} & \mu_{1}-\mu_{2} & \cdots & \mu_{1}-\mu_{2} & \mu_{1}-\mu_{2}\\
& \mu_{2} & \cdots & \mu_{2}-\mu_{3} & \mu_{2}-\mu_{3}\\
& & \ddots & \vdots & \vdots\\ | {
"domain": "physics.stackexchange",
"id": 9643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "newtonian-mechanics, classical-mechanics, friction",
"url": null
} |
c++, template, classes, stl, knapsack-problem
}
int main(int argc, char *argv[])
{
int knapsacksize = strtol(argv[1], nullptr, 0);
int seed = strtol(argv[2], nullptr, 0);
int objsize = 0;
// set capacity, will not be changed
int capacity = knapsacksize;
std::vector<char> objlist;
std::cout << "===========================" << std::endl;
std::cout << "== C++ Knapsack problem ===" << std::endl;
std::cout << "============== ~Gh0u1Ss ===" << std::endl;
std::cout << "Knapsack Size: " << knapsacksize << std::endl;
Knapsack<int> thisknapsack(knapsacksize,seed);
// knapsacksize with decrease as objects are being added
while(knapsacksize > objsize)
{
char cresult = generate(seed);
//std::cout << knapsacksize << std::endl; | {
"domain": "codereview.stackexchange",
"id": 43979,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
density-functional-theory
Title: Dyson Schwinger equation given the Dyson equations
$ \frac{\delta S}{\delta \phi(x)}\left[-i \frac{\delta}{\delta J}\right]Z[J]+J(x)Z[J]=0 $
is true that they are a solution or differential representation of the Generating functional ?? $ Z[J]=\int d[\phi(x)]exp(iS[\phi(x)])-\int dxZ[J]\phi(x)$ ??
if i can solve these set of equation can i 'renormalize' a physical theory ??
How are the Schwinger dyson equation solved ?? , thanks.
are these set of equation similar to 'Schwinger's quantum action principle ' ??
$ \delta <A|B>_{J}=i<A|\delta S |B>_{J}$ the variation is made respect an external source $ J(x) $ This is not the right way to think about it, these are just the equations of motion in a different language. The right way is the path integral, and these equations give you differential identities in the path integral, but you renormalize the path integral itself, not the equations. You don't "solve equations" in quantum field theory, you sum over all possible states.
As explained on Wikipedia, Schwinger's action principle is just a formulation of the path integral which included fermions before Grassman integration was formulate by Candlin. It became obsolete in 1956, after Grassman integration defined the path integral for Fermi fields. There is no gain in thinking about the differential equations, since these equations are not classical things for classical functions, they are operator equations which give you constraints on operator correlations. | {
"domain": "physics.stackexchange",
"id": 4090,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "density-functional-theory",
"url": null
} |
robotic-arm, raspberrypi
Title: use chroot to rosmake
Hi everyone,
I read on multiple places about using chroot and qemu to compile ROS on a Raspberry Pi (the same will probably be done for other systems). There, it comes down to somehow map the calls of gcc to use the ARM-gcc and produce ARM binaries. Now what I want to do is compile new ROS nodes for ARM, actually using the convenient rosmake. Is that possible?
I went down some roads, none with actual success (for reference: http://www.raspberrypi.org/phpBB3/viewtopic.php?f=31&t=8478, http://sentryytech.blogspot.de/2013/02/faster-compiling-on-emulated-raspberry.html and also this: http://pastebin.com/4Jp1WPTb modified for ubuntu to my best belief - I apologize for the inconvenience, but I am not allowed to post links here). So instead of stating what I tried here right now and listing the errors I encountered (which would be cumbersome for everyone involved, as I don't really know what I am doing, but could be done) I wanted to ask if someone already managed to get ros commands running on an emulated system or has set up a cross-compile variant of rosmake? There might be a documented way out there, but I am lost right now.
All hints are appreciated :)
Edit: This one will not work for what I intend: http://www.ros.org/wiki/eros/Tutorials/Partial%20Cross. It says so explicitly: "No Nodes!" | {
"domain": "robotics.stackexchange",
"id": 14513,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "robotic-arm, raspberrypi",
"url": null
} |
) never holding between a pair of arguments x and y when it holds between... | Meaning, pronunciation, translations and examples Required fields are marked *. A symmetric relation is a type of binary relation.An example is the relation "is equal to", because if a = b is true then b = a is also true. More formally, R is antisymmetric precisely if for all a and b in X, (The definition of antisymmetry says nothing about whether R(a, a) actually holds or not for any a.). Based on the definition, it would seem that any relation for which (,) ∧ (,) never holds would be antisymmetric; an example is the strict ordering < on the real numbers. Hence, it is a … Hence, it is a … You should know that the relation R ‘is less than’ is an asymmetric relation such as 5 < 11 but 11 is not less than 5. Example 6: The relation "being acquainted with" on a set of people is symmetric. In a formal way, relation R is antisymmetric, specifically if for all a and b in A, if R(x, y) with x ≠ y, then R(y, x) must not hold, or, equivalently, if R(x, y) and R(y, x), then x = y. Example 6: The relation "being acquainted with" on a set of people is symmetric. Hence, as per it, whenever (x,y) is in relation R, then (y, x) is not. Symmetric or antisymmetric are special cases, most relations are neither (although a lot of useful/interesting relations are one or the other). (iii) R is not antisymmetric here because of (1,2) ∈ R and (2,1) ∈ R, but 1 ≠ 2 and also (1,4) ∈ R and (4,1) ∈ R but 1 ≠ 4. (ii) R is not antisymmetric here because of (1,3) ∈ R and (3,1) ∈ R, but 1 ≠ 3. Learn how and when to remove this template message, https://en.wikipedia.org/w/index.php?title=Antisymmetric_relation&oldid=996549949, Articles needing additional references from | {
"domain": "creeco.ca",
"id": null,
"lm_label": "1. Yes\n2. Yes",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9780517488441416,
"lm_q1q2_score": 0.8548927636655003,
"lm_q2_score": 0.8740772302445241,
"openwebmath_perplexity": 602.042196309764,
"openwebmath_score": 0.8256226181983948,
"tags": null,
"url": "https://www.creeco.ca/wildflower-information-jrdwb/7c6d4c-example-of-antisymmetric-relation"
} |
inorganic-chemistry, acid-base
Title: Questions on Neutral oxides Neutral oxides, are non metal oxides which are neither acidic nor basic.
I have noticed a pattern for neutral oxides which I am unsure actually holds true.
$\ce{CO}$, $\ce{H2O}$, $\ce{NO}$ and $\ce{N2O}$ are examples of neutral oxides. It seems that neutral oxides will always have 1 oxygen atom. While non metal oxides with more than 1 oxygen atom seems to always be acidic oxide. ($\ce{CO2}$, $\ce{SO3}$, $\ce{SO2}$ and $\ce{P4O10}$).
Is this a coincidence? Are there any neutral oxides with more than one oxygen atom? Cl2O has one oxygen atom and is an acidic oxide. Thus, not all non metal oxides with one oxygen atom are neutral oxide. Also, not all neutral oxides have only one oxygen atom. N2O2, a neutral oxide but has more than one oxygen atom. | {
"domain": "chemistry.stackexchange",
"id": 17043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "inorganic-chemistry, acid-base",
"url": null
} |
python, performance, python-3.x, json, csv
Title: Efficiently convert 60 GB JSON file to a csv file Description
Simply take a JSON file as input and convert the data in it into a CSV file. I won't describe the functionality in too much detail since I have reasonable docstrings for that. As you can see, my solution is not memory efficient since I'm reading all the file into memory.
I'd like to improve the performance of my solution as much as possible. (perhaps not load everything at once into memory -- even if it's gonna be slower).
The JSON file that I'm trying to convert is 60 GB and I have 64GB of RAM.
Code
import csv
import json
CSV_PATH = 'file.csv'
JSON_PATH = 'file.json'
def flattenjson(json_data, delim):
"""
Flatten a simple JSON by prepending a delimiter to nested children.
Arguments:
json_data (dict): JSON object
e.g: {
"key1": "n1_value1",
"key2": "n1_value2",
"parent1": {
"child_key1": "n1_child_value1",
"child_key2": "n1_child_value2"
}
}
delim (str): Delimiter for nested children (e.g: '.')
Returns:
Flattened JSON object.
e.g: {
'key1': 'n1_value1',
'key2': 'n1_value2',
'parent1.child_key1': 'n1_child_value1',
'parent1.child_key2': 'n1_child_value2'
}
"""
flattened_json = {}
for i in json_data.keys():
if isinstance(json_data[i], dict):
get = flattenjson(json_data[i], delim)
for j in get.keys():
flattened_json[i + delim + j] = get[j]
else:
flattened_json[i] = json_data[i]
return flattened_json | {
"domain": "codereview.stackexchange",
"id": 38116,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, json, csv",
"url": null
} |
c++, multithreading, thread-safety, callback
thread synchronization. Is it done properly? Do I cover any possible scenarios? You will notice a commented std::unique_lock in the stop function. If I comment this out the threadPool never ends. I debugged and the threads never return. I believe this is a deadlock. The main thread grabs the mutex there, in the meantime other threads are waiting when they get notified in the next statement by the main thread they don't seem to wake up.. I'm not sure about this.
The way I capture the arguments and the smartFunctionPointer in the lambda. I tried out different combinations, by ref etc. and I picked the one which works best (capturing by value). This is however not proper design, as I'm not sure I understand for example, why capturing by reference there causes an exception. Task task;
while (m_enabled)
{
{
std::unique_lock<std::mutex> lg{ m_mu };
while (m_tasks.empty() && m_enabled)
m_cond.wait(lg);
}
if (!m_tasks.empty())
{// there is a task available
std::unique_lock<std::mutex> lg{ m_mu };
task = std::move(m_tasks.front());
m_tasks.pop();
task();
}
}// while threadPool is enabled
This all seems a bit dodgy.
We acquire a lock for waiting, and checking if tasks is empty (ok).
Then when a task appears in the queue we dispose of the lock (?).
We then check for emptiness without a lock (!!), and acquire a new lock. The queue could well become empty between checking for emptiness, and acquiring the new lock (and more importantly the subsequent unchecked call to front()).
Then we take the task off the queue, and execute it while still holding the lock (!). So we are effectively executing tasks in a single-threaded fashion. | {
"domain": "codereview.stackexchange",
"id": 36030,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, thread-safety, callback",
"url": null
} |
the-moon, asteroids, natural-satellites
Title: Can we have a second moon? This question sounds like silly and rather fantasy filled. But can our earth's gravity capture a sizable asteroid and make it rotate around our earth like our moon which become visible from ground. Is there any theoretical possibility or practical probability? At this stage of our solar system it is impossible for something with size of moon to fall in inner orbit. But smaller things like asteroids do fall in, and become captured by earths gravity. but they aren't big enough to see with naked eye. For example 2006 RH120 is a near earth asteroid which orbited Earth from September 2006 to June 2007. | {
"domain": "astronomy.stackexchange",
"id": 1206,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "the-moon, asteroids, natural-satellites",
"url": null
} |
With some effort you can establish explicit bounds on the error, which is
what I want the poster to do if he cannot see that it is $O(1/n)$ which
is all we need to establish what the limit actually is.
Think of this as an illustration of how we really do these things.
RonL | {
"domain": "mathhelpforum.com",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9787126531738088,
"lm_q1q2_score": 0.8468057506462325,
"lm_q2_score": 0.8652240756264638,
"openwebmath_perplexity": 453.615396640862,
"openwebmath_score": 0.9110174775123596,
"tags": null,
"url": "http://mathhelpforum.com/calculus/20936-sequences.html"
} |
python
Title: Simple Countdown Timer Beginner level script for a countdown timer. Would appreciate if you could point the things I could do to be more efficient.
Basically, I would want to check if the current day is either a "workday"(Mon - Wed) or a "freeday"(Thur-Sun) and achieve the following:
If it's a workday, and the current hour is a working hour (7:00:00 AM - 5:00:00 PM), then count
how many hour(s) remaining till end of the shift (5PM) base on the current time.
If it's a workday, and the current hour is outside of working hours (5:00:01 PM to 6:59:59 AM), say that it is not yet a working hour.
If it's a freeday, count till the next Monday.
I wouldn't want to rely on the if statements if possible, but my understanding level for Python is at this point only. Is there a better way to do it?
Thank you in advance! Happy coding.
import time, datetime
# Add the value to get the next Monday
get_future_monday = {
0: 1,
1: 2,
2: 3,
3: 4
}
def time_state():
# Check what day of the week
# 0 == Monday, 6 == Sunday
check_day = datetime.datetime.today().weekday()
# Get future Monday
future_monday = 6 - check_day
# Check current time
check_time_now = datetime.datetime.now()
# Parse current time
# Get the year, month and day
get_year = check_time_now.year
get_month = check_time_now.month
get_day = check_time_now.day
# Define timespan for each routine
working_hours = datetime.time(7, 0, 0)
after_hours_am = datetime.time(6, 59, 59)
after_hours_pm = datetime.time(17, 0, 1) | {
"domain": "codereview.stackexchange",
"id": 38605,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
php, mysql
if(!$data || ($data && $data['timestamp'] < time()))
{
$data = fethRemote("https://kino.com/$vKey");
$SQL_QUERY = "INSERT INTO cache (id, timestamp, url, width, height, type) VALUES(:id, :timestamp, :url, :width, :height, :type) ON DUPLICATE KEY UPDATE timestamp = :timestamp, url = :url";
$queryStmnt = $PDO->prepare($SQL_QUERY);
$queryStmnt->execute($data);
}
echo buildBody($data);
//
//Helpers
function doSQL($con, $query, $values)
{
$queryStmnt = $con->prepare($query);
$queryStmnt->execute($values);
//uhh conditional return?
}
function buildBody($values)
{
$vStyle = 'style="width:' . $values['width']. 'px;height:' . $values['height'] . 'px;\"';
$vSrc = 'src="' . $values['url'] . '"';
$vType = 'type="' . $values['type'] . '"';
return "<video controls $vStyle <source $vSrc $vType></video>";
}
function fethRemote($url)
{
$html = file_get_contents($url);
if(!$html || empty($html)) { die("Failed to fetch any data"); }
$dom = new DOMDocument;
@$dom->loadHTML($html);
$metaTags = $dom->getElementsByTagName('meta');
$data = ['id' => $vKey, 'timestamp' => '', 'url' => '', 'width' => '', 'height' => '', 'type' => '']; | {
"domain": "codereview.stackexchange",
"id": 38828,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, mysql",
"url": null
} |
php, mysql
Not escaping SQL is the same concept as this. This isn't a security issue; it's just wrong. Escaping SQL is the same concept as doing:
$string = "The other day, someone said, \"Hello my name is Fred!\"";
The escaping is necessary so that the SQL server can parse the query correctly in the same way that escaping in PHP is necessary so that the PHP engine can parse the script correctly.
The reason that SQL injection is a security concern is user input. If you don't properly escape, users can change your code.
It's hard to make a brief PHP-injection example, but hopefully the concept is there. An attempt at an example:
eval("\$x = 5 + {$_POST['input']};");
That's all good and fine as long as $_POST['input'] === "5"; or some other kind of innocent value. However, consider if $_POST['input'] === "5; evilFunction()". Suddenly the eval is:
eval("\$x = 5 + 5; evilFunction();");
This is the broad concept of SQL injection. (Various articles on the internet will explain it much better than me though :p.)
(eval should very rarely [arguably, never] actually be used -- this is just to illustrate a point)
Anyway, the solution is very simple. Anything that is going to be a string needs to be run through mysql_real_escape_string before being interpolated into a query. Likewise, anything that is not a string should be handled as the proper type:
$query = "INSERT INTO tbl (stringField, intField) VALUES ('%s', '%d')";
$qry = sprintf($query,
mysql_real_escape_string($someString), //make sure the string field is properly escaped
(int) $someInt //make sure the int field is an int
); | {
"domain": "codereview.stackexchange",
"id": 1914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, mysql",
"url": null
} |
ros2, ros2-launch, foxy
Title: Awkward shell outputs for launching many nodes using a configuration file I'm launching multiple nodes of unknown count using a configuration file that I provide to the backend launcher. So far, I appear to have no issues accomplishing this.
However, calling ros2 node list and ros2 topic list afterwards makes it seem one of my nodes to "vanish". The node still runs on my screen, and manages to publish its associated topics. Should I be worried?
I'll post a screenshot, and the minimal working example constructed in Foxy using the talker.py example from the tutorials.
Let's begin with the file tree, which is quite straightforward:
└── dummy
├── config
│ └── talker.yml
├── dummy
│ ├── __init__.py
│ ├── __pycache__
│ └── talker.py
├── launch
│ ├── talker.launch.xml
│ ├── talker_mux.launch.py
│ └── talker_start.launch.xml
├── package.xml
├── resource
├── setup.cfg
├── setup.py
└── test
7 directories, 15 files
(I suppressed __pycache__, etc. folder contents)
Here, you can see 3 different launch files and a YAML file.
One little modification I've made to talker.py is to print its namespace rather than "Hello World".
talker.yml: just namespace and count
ns: "dummy"
count: 6
talker.launch.xml: simple xml launchfile for the node only
<launch>
<node pkg="dummy" exec="talker" name="talker"/>
</launch>
talker_start.launch.xml: calls the python backend launcher
<launch>
<!-- Run the python launcher for multi-robot setups -->
<include file="$(find-pkg-share dummy)/launch/talker_mux.launch.py"/>
</launch> | {
"domain": "robotics.stackexchange",
"id": 39003,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros2, ros2-launch, foxy",
"url": null
} |
graphs, regular-languages, regular-expressions, shortest-path
The vertices of $G^\prime$ are $(V \times M) \cup \{\#\}$, i.e. all pairs of a vertex of $G$ and a state of $M$, together with an extra vertex identified by the arbitrary symbol $\#$.
For each edge in $e \in E$ from $v_1$ to $v_2$, add an edge in $G^\prime$ from $(v_1, m_1)$ to $(v_2, m_2)$ with weight $w(e)$ if and only if there is an edge in $M$ from $m_1$ to $m_2$ that is labeled $\ell(e)$.
For each accepting state $m$ in $M$, add an edge in $G^\prime$ from $(t, m)$ to $\#$ with weight 0. | {
"domain": "cs.stackexchange",
"id": 15250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "graphs, regular-languages, regular-expressions, shortest-path",
"url": null
} |
fasta, python
Title: Python: How to write duplicate sequences removed from fasta file to new file I currently am using this code to remove duplicate sequences from the fasta file. However, I would also like to write a new file with only the removed duplicates as well as a count for how many times they appear. Please let me know if you have any suggestions, I am hoping to keep it written in one py file, but I am not opposed to running a second file to do so. I attended to write the appended strings to a new file but it looked slightly off...
from Bio import SeqIO
import time
start = time.time()
seen = []
records = []
for record in SeqIO.parse("b4r2.fasta", "fasta"):
if str(record.seq) not in seen:
seen.append(str(record.seq))
records.append(record)
#writing to a fasta file
SeqIO.write(records, "no_dupes_b4r2.fasta", "fasta")
end = time.time()
print(f"Run time is {(end- start)/60}")
``` Edit: user @RamRS has a more robust answer for actually using this. Please use that. Leaving answer up as OP appears to be interested in implementing as a learning activity.
Please let us know why this is not doing what you intend.
I haven't checked it, but something like this would work:
from Bio import SeqIO
import time
from collections import defaultdict
start = time.time()
seq_counts = defaultdict(0)
records = []
for record in SeqIO.parse("b4r2.fasta", "fasta"):
seq = str(record.seq)
if seq in seq_counts: # python is smart about dict keys
records.append(record)
seq_counts[seq] += 1
#writing to a fasta file
SeqIO.write(records, "no_dupes_b4r2.fasta", "fasta")
end = time.time() | {
"domain": "bioinformatics.stackexchange",
"id": 1480,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "fasta, python",
"url": null
} |
java, performance, graphics
}else{
if(SpriteManager.eventSpritesGet(currTile.getEventAlias()).pixels[tilePix] != 0xffff00ff) Game.pixels[screenPix] = SpriteManager.eventSpritesGet(currTile.getEventAlias()).pixels[tilePix];
}
continue; | {
"domain": "codereview.stackexchange",
"id": 15602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, graphics",
"url": null
} |
vba
Dim ExportFolder As String
ExportFolder = ThisWorkbook.Path & "\src"
With New Scripting.FileSystemObject
If Not .FolderExists(ExportFolder) Then
.CreateFolder ExportFolder
End If
End With
SourceControlH.ExportProjectComponents ThisWorkbook, ExportFolder
End Sub
Note that the {bool-expression} = False condition is redundant - comparing a Boolean expression to a Boolean literal is always redundant: Not {bool-expression} is more idiomatic, more concise, and more expressive.
Portability
VBA code that doesn't need to be tied to a particular specific VBA host application's object model library, should avoid such dependencies.
Public Sub ExportProjectComponents(ByVal Source As Workbook, ByVal Path As String)
The Source parameter should be a VBProject object, not a Workbook; by taking in an Excel.Workbook dependency, the module becomes needlessly coupled with the Excel object model: if you needed to reuse this code in the future for, say, a Word VBA project, you'd need to make changes.
Consistency
Qualifying members is nice! Consistently qualifying members is better :)
If Tools.Fso.FolderExists(Path) = False Then
Why is this Fso qualified with the module name, but not the one in ThisWorkbook? Without Rubberduck to help, a reader would need to navigate to the definition to make sure it's referring to the same object.
But, then again, I'd New up the FSO on the spot, and let VBA claim that pointer as soon as it's no longer needed:
With New Scripting.FileSystemObject
If Not .FolderExists(Path) Then
Exception.DirectoryNotFoundException "Path", ModuleName & "." & MethodName
End If
End With
Other notes
I like your centralized approach to error-raising very much! I find the term "exception" a bit misleading though (if it's an exception, where's my stack trace?), and the procedure names read like properties. I'd propose something like this:
Errors.OnDirectoryNotFound "Path", ModuleName & "." & MethodName | {
"domain": "codereview.stackexchange",
"id": 36735,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba",
"url": null
} |
ros, kinect, openni, ros-kinetic, freenect
/camera/ir/image_raw/compressedDepth/parameter_descriptions
/camera/ir/image_raw/compressedDepth/parameter_updates
/camera/ir/image_raw/theora
/camera/ir/image_raw/theora/parameter_descriptions
/camera/ir/image_raw/theora/parameter_updates
/camera/projector/camera_info
/camera/rgb/camera_info
/camera/rgb/image_raw
/camera/rgb/image_raw/compressed
/camera/rgb/image_raw/compressed/parameter_descriptions
/camera/rgb/image_raw/compressed/parameter_updates
/camera/rgb/image_raw/compressedDepth
/camera/rgb/image_raw/compressedDepth/parameter_descriptions
/camera/rgb/image_raw/compressedDepth/parameter_updates
/camera/rgb/image_raw/theora
/camera/rgb/image_raw/theora/parameter_descriptions
/camera/rgb/image_raw/theora/parameter_updates
/camera/rgb_rectify_color/parameter_descriptions
/camera/rgb_rectify_color/parameter_updates
/diagnostics
/rosout
/rosout_agg
/tf_static
I have been able to bring up a depthcloud, as opposed to a pointcloud, the latter of which is still blank when adding a pointcloud2 object as per the original ROS tutorial. Is there a difference between pointcloud and depth cloud, and should a pointcloud be available in the topics list?
I note that none of the freenect or openni launch files contain any reference to "points", has this functionality been removed? I have also looked in freenect-registered-xyzrgb and freenect-xyz, which the documentation says should give pointclouds.
The intermittent nature of it running all topics also seems to be perplexing, which may be down to a background process needing to stop. killall XsSensorServer does not help. | {
"domain": "robotics.stackexchange",
"id": 29702,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros, kinect, openni, ros-kinetic, freenect",
"url": null
} |
ros
Originally posted by Josh Whitley with karma: 1766 on 2021-05-26
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by kk2105 on 2021-06-08:
Thanks for the answer. Every time I enter inside the ade, I need to uninstall the vulkan-drivers. Is there a better way to remove so that it does not ask me everytime I enter ade?
Comment by Josh Whitley on 2021-06-08:
See https://gitlab.com/autowarefoundation/autoware.auto/AutowareAuto/-/issues/1140 for discussion about this issue. | {
"domain": "robotics.stackexchange",
"id": 36235,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros",
"url": null
} |
measurement
I also really like a lot of the features for dealing with expectation values in Pennylane, they automatically compile circuits depending on the set of observables you are trying to compute the expectation of. You can find some examples of that functionality here: https://pennylane.readthedocs.io/en/stable/code/qml_grouping.html. | {
"domain": "quantumcomputing.stackexchange",
"id": 3771,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "measurement",
"url": null
} |
c++, object-oriented, c++11, memory-management, constructor
TL;DR: Don't mix value semantics with polymorphism. You can't sensibly swap() two humans, because you can't sensibly swap an employee with a non-employee (even though both are humans). I say a lot more about this, far below, after we get through the basic copy-and-swap stuff.
Does this class [human] comply with the copy-swap idiom? Is anything missing or overlooked?
Your copy constructor for human is exception-unsafe.
Here are the members that need copying:
char *blood_type = nullptr;
std::string dob = "";
details *di = nullptr;
And here is your implementation, for ease of reference. I've adjusted the whitespace for readability, and removed redundant comments, but not changed any of the non-whitespace characters:
human(const human& f)
{
if (f.blood_type != nullptr) {
blood_type = new char[std::strlen(f.blood_type) + 1];
strcpy(blood_type, f.blood_type);
}
this->dob = f.dob; // may throw std::bad_alloc [1]
this->di = new details(*(f.di)); // may throw std::bad_alloc [2]
} | {
"domain": "codereview.stackexchange",
"id": 13502,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, c++11, memory-management, constructor",
"url": null
} |
javascript, object-oriented, ecmascript-6, extension-methods, helper
Feel free to use the utils if you like. For the most part, this looks good to me. Your api is clear and I really like that you have to activate the utility before the prototype is modified. However, there's always room for improvement :) | {
"domain": "codereview.stackexchange",
"id": 30596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, object-oriented, ecmascript-6, extension-methods, helper",
"url": null
} |
Seven draws
The first six draws are Others: . ${9\choose6}\text{ ways } \hdots\:P(\text{6 Others}) \:=\:\frac{{9\choose6}}{{15\choose6}}$
And the 7th is a 75w: . $\frac{6}{9}$
. . Hence: . $P(\text{7 draws}) \;=\;\frac{{9\choose6}}{{15\choose6}}\left(\frac{6 }{9}\right)$
Eight draws
The first seven draws are Others: . ${9\choose7}\text{ ways }\hdots\:P(\text{7 Others}) \:=\:\frac{{9\choose7}}{{15\choose7}}$
And the 8th is a 75w: . $\frac{6}{8}$
. . Hence: . $P(\text{8 draws}) \;=\;\frac{{9\choose7}}{{15\choose7}}\left(\frac{6 }{8}\right)$
Nine draws
The first eight draws are Others: . ${9\choose8}\text{ ways }\hdots\:P(\text{8 Others}) \:=\:\frac{{9\choose8}}{{15\choose8}}$
And the 9th is a 75w: . $\frac{6}{7}$
. . Hence: . $P(\text{9 draws}) \;=\;\frac{{9\choose8}}{{15\choose8}}\left(\frac{6 }{7}\right)$ | {
"domain": "mathhelpforum.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9597620585273153,
"lm_q1q2_score": 0.8437717204496361,
"lm_q2_score": 0.8791467770088163,
"openwebmath_perplexity": 2322.0345284433115,
"openwebmath_score": 0.8197942972183228,
"tags": null,
"url": "http://mathhelpforum.com/statistics/93987-more-probability.html"
} |
phylogeny
And I would like to calculate a phylogenetic tree for all the nodes in the list. I've seen phylip neighbor and similar options, but it seems like the length of the ids is a limit, which I rather not have to deal with. What would be a straightforward way of getting a newick tree output out of an input as above? I believe there are a number of ways to construct a tree metric from a distance metric. A very straightforward method, neighbor joining, is available in the Sciki-Bio package. A less straightforward option with more freedom is by using the scipy.cluster.hierarchy module to obtain a linkage matrix, then using the to_tree() method to obtain a scipy Tree object, and finally writing a script to convert a scipy Tree object to a newick string.
I've copied the example from scikit-bio below:
>>> from skbio import DistanceMatrix
>>> from skbio.tree import nj
>>>
>>> data = [[0, 5, 9, 9, 8],
... [5, 0, 10, 10, 9],
... [9, 10, 0, 8, 7],
... [9, 10, 8, 0, 3],
... [8, 9, 7, 3, 0]]
>>> ids = list('abcde')
>>>
>>> dm = DistanceMatrix(data, ids)
>>> # Or from a tsv file with header, no column 0
>>> reader = csv.reader(open(args.inputfile), delimiter="\t")
>>> x = list(reader)
>>> dm = DistanceMatrix(x[1:],x[0])
>>>
>>> newick_str = nj(dm, result_constructor=str)
>>> print(newick_str[:55], "...")
(d:2.000000, (c:4.000000, (b:3.000000, a:2.000000):3.00 ...
Note: Both methods require you to supply the input as a numpy distance matrix | {
"domain": "bioinformatics.stackexchange",
"id": 1918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "phylogeny",
"url": null
} |
Is the above reasoning correct? If not, could you point me in the right direction? Thank you in advance.
• Would this rephrasing of question c) help you ? "once I put my first ball somewhere what is the pobability that the second one ends up in the same box" – Robin Nicole Jan 31 at 23:36
• I will point out that you have your choice as to what to treat your sample space as for different parts of the same problem. Although it is convenient for the first or second parts to treat our sample space as size $n^n$ (the $n$-tuple corresponding to the boxes in which each respective ball is in), it may be much easier to treat the sample space for part (c) as simply $n^2$ (or with careful wording, just $n$) being the ordered pair describing the box in which the first and second ball are in respectively (or even just the distance to right from the first ball to the second modulo $n$) – JMoravitz Jan 31 at 23:50
• @JMoravitz That would reduce the problem to computing the probability of the pair having equal coordinates where the coordinates range from $1$ to $n$, correct? – G the Stackman Jan 31 at 23:58
• Effectively, yes. – JMoravitz Feb 1 at 0:01
• If you insist on looking at this indirectly, yes that is correct. I find it easier to do it directly however and just say it is $\frac{1}{n}$ (which is of course equal to the answer in your comment) – JMoravitz Feb 1 at 0:07
• The probability that there are no empty boxes is $\frac{n!}{n^n},$ so that the probability that there is at least one empty box is $1-\frac{n!}{n^n},$ right? – G the Stackman Jan 31 at 23:37 | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9899864273087513,
"lm_q1q2_score": 0.8116832743952955,
"lm_q2_score": 0.8198933359135361,
"openwebmath_perplexity": 153.29603079654095,
"openwebmath_score": 0.8567413091659546,
"tags": null,
"url": "https://math.stackexchange.com/questions/3095622/probability-question-about-n-balls-and-n-boxes"
} |
c++, performance, search, c++14
template <typename BidirIt, typename T>
BidirIt find(BidirIt first, BidirIt last, const T& value)
{
return impl::find(std::integral_constant<bool, std::is_nothrow_copy_assignable<std::remove_reference_t<decltype(*first)> >::value> {},
first, last, value);
//I'd like to allow T to be different from *first
}
#endif
Usage:
#include "fast_find.hpp"
#include "randomsequence.h"
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v(10'000'000);
random_int_generator<> gen(0, 10'000); //generate values in range
gen(v.begin(), v.end());
int n;
std::cin >> n;
auto it = find(v.begin(), v.end(), n);
if (it != v.end())
{
std::cout << "Found it!\n" << *it << '\n';
}
else
{
std::cout << "Sadness\n";
}
}
Here is the random_int_generator<>, do not review this, I posted it to make it easier for you to benchmark if needed:
#pragma once
#include <random>
template <typename T = int, class Engine = std::random_device>
class random_int_generator
{
Engine engine;
std::uniform_int_distribution<T> dist;
public:
random_int_generator(T begin = 0, T end = std::numeric_limits<T>::max()) :
dist(begin, end)
{
}
template <typename OutputIt>
void operator()(OutputIt first, OutputIt last)
{
while (first != last)
{
*first++ = dist(engine);
}
}
T operator()()
{
return dist(engine);
}
}; | {
"domain": "codereview.stackexchange",
"id": 22693,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, search, c++14",
"url": null
} |
ros
Title: [Nav2] Best way of alternating between autonomous navigation and assisted teleop using `follow_waypoints` action server
Hi everyone!
I'm currently using Nav2 on a robot that has to perform long navigation tasks (>1000m) across large environments (~5sqkm); I'm relying on the follow_waypoints action server for passing long sequences of sparse waypoints. I don't have a static 2d gridmap of the environment but rather a graph of sparsely interconnected nodes.
For different reasons there are small sections of the environment where the robot cannot drive autonomously. These sections are already pre-mapped in the edges between certain nodes on the aforementioned graph. See the below picture for a clearer explanation
On the picture above, considering the marked robot route (dotted arrow), what I would like to achieve is to tick the usual navigate_to_pose behavior tree for getting from node 2 to node 3 and from node 3 to node 4. When navigating from node 4 to node 5 I would like to trigger the assisted teleop behavior server to manually drive the robot. When reaching node 5 I would like to switch back to the navigate_to_pose bt to get to node_6 and so on.
I have thought of making a custom behavior tree node to switch between a navigate_to_pose branch and an assisted_teleop branch according to the goal_id that is to be reached. Also I would have to integrate a goal checker into the assisted_teleop server to SUCCEED the branch when the given goal is reached manually.
However I'm aware that some discussion has been held around this kind of "semantic navigation" to change the behavior of nav2 according to semantic labels defined on a sparse graph, so I wanted to ask the community about this beforehand.
Have someone faced the same problem? Would you recommend a different alternative? Is there any standard way of doing this?
Thanks in advance for your help and any insights you can provide :) | {
"domain": "robotics.stackexchange",
"id": 37990,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros",
"url": null
} |
statistical-mechanics, photons, poincare-recurrence
Case 2: A particle starts outside a closed box with an infinitesimally small hole in the corner. It has an initial velocity vector that lets it pass through the hole. Outside the box is an infinite universe.
In this case, the velocities are still bounded, but the positions are not. In principal, the particle could take any position at all. Poincaré recurrence does not apply. Whether or not the particle leaves the box is again determined by geometry and its initial state.
Case 3: Same as Case 2, but how the cube-plus-particle system sits inside another enclosure, maybe a laboratory.
Now the particle positions are bounded, so Poincaré recurrence at least applies. Furthermore, since the particle starts outside the cube, Poincaré recurrence says that it must somehow, someday end up in that same position with the same velocity. So in this case yes, recurrence predicts that the particle will exit the box. | {
"domain": "physics.stackexchange",
"id": 18697,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "statistical-mechanics, photons, poincare-recurrence",
"url": null
} |
quantum-field-theory, group-theory, representation-theory, symmetry-breaking, goldstone-mode
However, this large symmetry is explicitly broken by your gauging terms to SU(2) ~ O(3) in your lagrangian, and there is a way to see the $\phi$s separate from the $\xi$s in the bilinears through the gauging terms as follows.
You utilized the spherical basis for the (real) adjoint representation, but you may switch to the real antisymmetric basis, instead, utilized in classical rotations, which does not mix the real and imaginary components of Σ.
(The above vev corresponds to your "case" (a) which, as explained in the comment, is identical to your (b), and preserves ${\mathbb I} \otimes T^3$.)
In this basis, the covariant completion in (3) reads
$$-igA^a_\mu T^a=g \left(\begin{array}{ccc}0&-A^3_\mu &A^2_\mu \\ A^3_\mu &0&-A^1_\mu \\-A^2_\mu &A^1_\mu &0\end{array}\right) , $$
antisymmetric and so antihermitean, just like the gradient.
Plugging it into the bilinear terms in A in the Lagrangian, it yields the mass terms (6), as you observed, leaving $A^3_\mu$ massless, as the v.e.v. $\langle \Sigma\rangle= (0,0,v)^T/\sqrt 2$ is a null vector of the above completion: $T^3$ remains unbroken, and SU(2)/U(1) is two-dimensional. (As indicated, your case (b) is a mirage, and (7) is flat wrong.) | {
"domain": "physics.stackexchange",
"id": 97798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "quantum-field-theory, group-theory, representation-theory, symmetry-breaking, goldstone-mode",
"url": null
} |
_________________
Kudos [?]: 132612 [1], given: 12326
Math Expert
Joined: 02 Sep 2009
Posts: 42249
Kudos [?]: 132612 [1], given: 12326
### Show Tags
30 Apr 2010, 14:30
1
KUDOS
Expert's post
AloneAndInsufficient wrote:
Bunuel wrote:
NUMBER THEORY
• For GMAT it's good to memorize following values:
$$\sqrt{2}\approx{1.41}$$
$$\sqrt{3}\approx{1.73}$$
$$\sqrt{5}\approx{2.24}$$
$$\sqrt{7}\approx{2.45}$$
$$\sqrt{8}\approx{2.65}$$
$$\sqrt{10}\approx{2.83}$$
Anyone else notice that these are wrong?
They should be:
• For GMAT it's good to memorize following values:
$$\sqrt{2}\approx{1.41}$$
$$\sqrt{3}\approx{1.73}$$
$$\sqrt{5}\approx{2.24}$$
$$\sqrt{6}\approx{2.45}$$
$$\sqrt{7}\approx{2.65}$$
$$\sqrt{8}\approx{2.83}$$
$$\sqrt{10}\approx{3.16}$$
Thanks. Edited. +1 for spotting this.
_________________
Kudos [?]: 132612 [1], given: 12326
Math Expert
Joined: 02 Sep 2009
Posts: 42249
Kudos [?]: 132612 [1], given: 12326
### Show Tags
19 Nov 2010, 01:53
1
KUDOS
Expert's post
Araj wrote:
Hello Bunuel - thank you so much for this fantastic post!
with regards to checking for primality: | {
"domain": "gmatclub.com",
"id": null,
"lm_label": "1. Yes\n2. Yes\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9407897525789548,
"lm_q1q2_score": 0.8087628437607948,
"lm_q2_score": 0.8596637469145054,
"openwebmath_perplexity": 1505.8614363488412,
"openwebmath_score": 0.5919175148010254,
"tags": null,
"url": "https://gmatclub.com/forum/math-number-theory-88376-20.html?kudos=1"
} |
c++, beginner
int bat_ind = bat_index();
int pit_ind = pit_index();
int wump_index = wumpus_index();
Tunnel& t = tunnels[wump_index];
int new_wump_index = t[randint(t.size())];
//ensure wumpus does not move to a room w/ bat or pit
while (new_wump_index == bat_ind || new_wump_index == pit_ind) new_wump_index = t[randint(t.size())];
rooms[wump_index].set_room_type(Room::Empty);
rooms[new_wump_index].set_room_type(Room::Wumpus);
if (new_wump_index == player.current_room())
{
player_lose("The Wumpus has found you! Game over.");
}
}
void Cave::player_lose(const std::string& s)
{
std::cout << s << '\n';
game_state = Game_State::lose;
}
bool Cave::valid_move(const Player_move& pm)
{
if (pm.rooms.size() == 0) return false; //empty vector
Tunnel& t = tunnels[player.current_room()];
for (int i : pm.rooms)
{
if (i < 0 || i >(number_of_rooms - 1)) return false;
if (std::find(t.begin(), t.end(), i) == t.end()) return false; //room is not connected to players current room
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 28766,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner",
"url": null
} |
sam, samtools, sambamba
Title: samtools depth print out all positions I am trying to use samtools depth (v1.4) with the -a option and a bed file listing the human chromosomes chr1-chr22, chrX, chrY, and chrM to print out the coverage at every position:
cat GRCh38.karyo.bed | awk '{print $3}' | datamash sum 1
3088286401
I would like to know how to run samtools depth so that it produces 3,088,286,401 entries when run against a GRCh38 bam file:
samtools depth -b $bedfile -a $inputfile
I tried it for a few bam files that were aligned the same way, and I get differing number of entries:
3087003274
3087005666
3087007158
3087009435
3087009439
3087009621
3087009818
3087010065
3087010408
3087010477
3087010481
3087012115
3087013147
3087013186
3087013500
3087149616
Is there a special flag in samtools depth so that it reports all entries from the bed file?
If samtools depth is not the best tool for this, what would be the equivalent with sambamba depth base?
sambamba depth base --min-coverage=0 --regions $bedfile $inputfile
Any other options? You might try using bedtools genomecov instead. If you provide the -d option, it reports the coverage at every position in the BAM file.
bedtools genomecov -d -ibam $inputfile > "${inputfile}.genomecov"
You can also provide a BED file if you just want to calculate in the target region. | {
"domain": "bioinformatics.stackexchange",
"id": 67,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sam, samtools, sambamba",
"url": null
} |
beginner, c, ascii-art, fractals, c99
fprintf(stream, "%s\n", formatted);
free(formatted);
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include "display.h"
#define OUTPUT_PATH "./mandelbrot_output.txt"
void save_view_at(double lower_real,
double upper_real,
double lower_imag,
double upper_imag,
size_t image_width) {
FILE* file = fopen(OUTPUT_PATH, "w+");
if (file) {
print_mandelbrot_view(file,
lower_real, upper_real,
lower_imag, upper_imag,
// Halving the height because it looks best when
// width is 2 * height.
image_width, (size_t)(image_width / 2));
fclose(file);
} else {
printf("Cannot open file at %s", OUTPUT_PATH);
}
}
int main() {
save_view_at(-2, 1, -1.5, 1.5, 500);
printf("Saved...\n");
return 0;
} The "terminating" allocators work well for small programs like this; in larger projects or libraries, we want to do something better than terminate the program when allocation fails. A common naming scheme (perhaps taken from Perl) is malloc_or_die() - that's slightly clearer about the behaviour. It's usual to end your error message (and indeed program output generally) with a newline:
fprintf(stderr, "Could not allocate space for %s.\n", allocation_reason); | {
"domain": "codereview.stackexchange",
"id": 35949,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, ascii-art, fractals, c99",
"url": null
} |
molecular-biology, dna, lab-techniques
Title: How to measure quality and quantity of DNA? I would like to mesure DNA. I quantify the concentration with Qubit fluorometer, but I would like to know also quality of DNA. I try BioAnalyzer (Agilent),but without success. Bioanalyzer measure DNA samples from 100 to 7 000 bp (12 000 bp). Problem is that my DNA is not sheared, I would like to quantify whole mouse DNA. Have you any idea? Thanks! You can run your DNA sample on agarose gel to see, whether you have significant degradation.
If you are interested in contamination, you can make a standard photometric analysis to assess the 260/280 and 260/230 ratios and absorbance at 320 nm on NanoDrop or even something similar to Eppendorf's BioPhotometer.
In case RNA may be an obstacle for some down-stream procedures, with Qubit you can also measure separately DNA and RNA concentrations and then decide if you have too much RNA and it's worth treating your sample with RNase. | {
"domain": "biology.stackexchange",
"id": 2032,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "molecular-biology, dna, lab-techniques",
"url": null
} |
physical-chemistry, thermodynamics, water, reference-request, free-energy
Title: Discrepancies in calculating free energy values listed in Stumm and Morgan I am hoping someone can help me with a clarifying a calculation on a fundamental thermodynamic understanding of reactions. Below is Table 2.5 from Stumm and Morgan's Aquatic Chemistry.
Table 2.5. Influence of Pressure and Temperature on the Energies of Water Ionization a
$$
\begin{array}{rrr}
\hline
p (\pu{bars}) &\log K_\mathrm{w} &\Delta G_\mathrm{w}^\circ (\pu{kJ mol-1})\\
\hline
&T = \pu{298.17 K} &\\
1 &-14.00 & 79.94\\
200 & -13.92 & 79.48\\
400 & -13.84 & 79.02\\
600 & -13.77 & 78.63\\
800 & -13.70 & 78.22\\
1000 & -13.63 & 77.83\\
\hline
T (\pu{^\circ C}) &\log K_\mathrm{w} &\Delta G_\mathrm{w}^\circ (\pu{kJ mol-1})\\
\hline
&p = \pu{1 bar} &\\
0 & -14.93 & 85.25\\
10 & -14.53 & 82.97\\
20 & -14.17 & 80.91\\
30 & -13.83 & 78.97\\
50 & -13.26 & 75.71\\
\hline
\end{array}
$$
aData from Harned and Owen (1958). | {
"domain": "chemistry.stackexchange",
"id": 8777,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "physical-chemistry, thermodynamics, water, reference-request, free-energy",
"url": null
} |
c++, game, c++11, proxy, mediator
struct Monster : LivingBeing {
using LivingBeing::LivingBeing;
virtual ~Monster() {std::cout << name << " destroyed.\n";}
};
struct SummonedMonster : Monster {
Monster* monster; // Proxy Pattern
LivingBeing* summoner;
SummonedMonster (Monster* m, LivingBeing* s) : monster(m), summoner(s) {
allBeingsPresent.emplace_back(this);
}
~SummonedMonster() {delete monster;}
void receiveAttackCommand() {std::cout << monster->name << " will follow " << summoner->name << "'s order to attack.\n";}
void receiveShieldMeCommand() {std::cout << monster->name << " will follow " << summoner->name << "'s order to shield him.\n";}
virtual inline void dies() override;
};
struct CharacterClass : LivingBeing {
using LivingBeing::LivingBeing;
};
struct Fighter : CharacterClass {
using CharacterClass::CharacterClass;
}; | {
"domain": "codereview.stackexchange",
"id": 11313,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, c++11, proxy, mediator",
"url": null
} |
java, console, authentication
Title: Diary Application with accounts (v.2) Folow up of diary-applications-with-accounts
Diary Class
AccountLogin objAccountLogin = new AccountLogin();
AccountRemover objAccountRemover = new AccountRemover();
AccountCreator objAccountCreator = new AccountCreator();
Accounts objAccounts = new Accounts();
Exit objExit = new Exit();
public static void main(String[] args) {
Diary d = new Diary();
d.startDiary();
}
public void startDiary(){
objAccounts.loadAccounts();
while(true){
showMainMenu();
usersChoice();
}
}
public void showMainMenu(){
System.out.println("");
System.out.println("Welcome to Diary!");
System.out.println("1- New Account");
System.out.println("2- Login To Your Account");
System.out.println("3- Remove Account");
System.out.println("4- Exit");
System.out.println("");
}
public void usersChoice(){
int choice = 0;
Scanner scan = new Scanner(System.in);
while(true){
try{
scan = new Scanner(System.in);
System.out.print("Choose an option: ");
choice = scan.nextInt();
break;
}
catch(Exception e){
System.out.println("Invalid Input!\n");
}
}
switch (choice){
case 1:
choiceNewAccount(scan);
break;
case 2:
choiceLogin(scan);
break;
case 3:
choiceRemoveAccount(scan);
break;
case 4:
exit(scan);
break;
default:
System.out.println("Invalid Input!\n");
break;
}
}
public void choiceNewAccount(Scanner scan){
objAccountCreator.createAccount(scan);
}
public void choiceLogin(Scanner scan){
objAccountLogin.login(scan);
} | {
"domain": "codereview.stackexchange",
"id": 15256,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, console, authentication",
"url": null
} |
## Get answers to practical, detailed questions
Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.
• Understanding mathematical concepts and theorems
• History and development of mathematics
• Solving mathematical puzzles
• Software that mathematicians use
Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.
Questions that need improvement may be closed until someone fixes them.
• Anything not directly related to math
• Questions that are primarily opinion-based
• Questions with too many possible answers or that would require an extremely long answer
• Physics, engineering and financial questions.
• Numerology questions
## Tags make it easy to find interesting questions
All questions are tagged with their subject areas. Each can have up to 5 tags, since a question might be related to several subjects.
Click any tag to see a list of questions with that tag, or go to the tag list to browse for topics that interest you.
# linear map $f:V \rightarrow V$, which is injective but not surjective
I am trying to find a linear map $f:V \rightarrow V$, which is injective but not surjective.
I always thought that if the dimension of the domain and codomain are equal and the map is injective it implies that a map is surjective. Maybe we need an infinite basis of the vector space $V$? What can be an example of that?
Thank you!
## You earn reputation when people vote on your posts
+5 question voted up
+2 edit approved
As you earn reputation, you'll unlock new privileges like the ability to vote, comment, and even edit other people's posts.
Reputation Privilege
15 Vote up
125 Vote down (costs 1 rep on answers)
At the highest levels, you'll have access to special moderation tools. You'll be able to work alongside our community moderators to keep the site focused and helpful.
2000 Edit other people's posts Vote to close, reopen, or migrate questions Access to moderation tools
see all privileges
## Improve posts by editing or commenting
Our goal is to have the best answers to every question, so if you see questions or answers that can be improved, you can edit them.
Use edits to fix mistakes, improve formatting, or clarify the meaning of a post. | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9732407106053677,
"lm_q1q2_score": 0.8438345106934815,
"lm_q2_score": 0.8670357718273068,
"openwebmath_perplexity": 677.4271316478614,
"openwebmath_score": 0.4757276475429535,
"tags": null,
"url": "http://math.stackexchange.com/tour"
} |
quantum-mechanics, homework-and-exercises, harmonic-oscillator, hilbert-space
Let's define $N=a^\dagger a$ and write $n$ its eigenvalues and $|n\rangle$ the corresponding eigenvectors. The eigenvalues $n$ of $N$ are positive since, for a given eigenstate $|n\rangle$,
$$ n=\langle n|a^\dagger a |n\rangle = \lVert a |n\rangle \rVert^2$$
and a norm is positive.
For $n=0$ one has
$$ n=0 \quad\Longrightarrow\quad \lVert a |0\rangle \rVert^2 = 0 \quad\Longrightarrow\quad a |0\rangle = 0 \quad .$$
From the commutation relation, for any eigenvector $|n\rangle$ or $N$,
$$ N a |n\rangle = a^\dagger a a|n\rangle=\left(a^\dagger a-1\right)a| n\rangle=aN|n\rangle - a |n\rangle=(n-1)a|n\rangle \quad .$$
Hence $a|n\rangle$ is an eigenvector of $N$ with eigenvalue $n-1$. | {
"domain": "physics.stackexchange",
"id": 10259,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "quantum-mechanics, homework-and-exercises, harmonic-oscillator, hilbert-space",
"url": null
} |
java, repository
unlink(node);
linkLast(node);
}
private static class Node<K, V> extends SimpleEntry<K, V> {
private static final long serialVersionUID = 1L;
private Node<K, V> prev = null;
private Node<K, V> next = null;
private long expirationTime;
private Node(K key, V value, long liveTime) {
super(key, value);
updateExpirationTime(liveTime);
}
private Node(Node<K, V> prev, Node<K, V> next, K key, V value, long liveTime) {
this(key, value, liveTime);
setLinks(prev, next);
}
private void setLinks(Node<K, V> prev, Node<K, V> next) {
this.prev = prev;
this.next = next;
}
private long timeTillExpiraton() {
return expirationTime - System.currentTimeMillis();
}
private boolean isExpired() {
return expirationTime - System.currentTimeMillis() <= 0;
}
public void updateExpirationTime(long liveTime) {
expirationTime = System.currentTimeMillis() + liveTime;
}
}
private static class Cleaner<K, V> implements Runnable {
private ExpiringKeyValueRepository<K, V> rep;
private boolean stopped = true;
private Lock writeLock;
private Condition checkCondition;
private Cleaner(ExpiringKeyValueRepository<K, V> repository) {
this.rep = repository;
this.writeLock = repository.writeLock;
this.checkCondition = repository.checkCondition;
}
@Override
public void run() {
writeLock.lock();
try {
while (!stopped) {
while (rep.first != null && rep.first.isExpired()) {
rep.removeNoLock(rep.first.getKey());
}; | {
"domain": "codereview.stackexchange",
"id": 39822,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, repository",
"url": null
} |
ros, qtcreator
Title: qtcreator Could not find 'share/std_msgs/cmake/std_msgs-msg-paths.cmake'
error info:
/opt/ros/indigo/share/genmsg/cmake/genmsg-extras.cmake:271: error: Could not find 'share/std_msgs/cmake/std_msgs-msg-paths.cmake' (searched in '/home/westeast/git/enmodel/devel'). trajectory/CMakeLists.txt:72 (generate_messages)
I add some .msg file in my package
but the qtcreator IDE can not build the msg .
I can build the package with msg in cmd by catkin_make
Is anyone know the reason?
Originally posted by westeast on ROS Answers with karma: 51 on 2017-05-12
Post score: 0
Seems to me you are running into this problem: #q202401
Can you see if sourcing your environment has the desired effect? If not, please post your complete CMakeLists.txt and the output of echo $CMAKE_PREFIX_PATH
Originally posted by rbbg with karma: 1823 on 2017-05-12
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by westeast on 2017-05-12:
thanks so so much . I solve the problem by add CMAKE_PREFIX_PATH: /home/westeast/git/enmodel/devel;/opt/ros/indigo in my qt build config. At the begining my $CMAKE_PREFIX_PATH is empty.
and emember click the apply button when you change the config. | {
"domain": "robotics.stackexchange",
"id": 27877,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros, qtcreator",
"url": null
} |
# Convergent Sequence with Finite Number of Terms Deleted is Convergent
## Theorem
Let $\left({X, d}\right)$ be a metric space.
Let $\left\langle{x_k}\right\rangle$ be a sequence in $X$.
Let $\left\langle{x_k}\right\rangle$ be convergent.
Let a finite number of terms be deleted from $\left \langle {x_k} \right \rangle$.
Then the resulting subsequence is convergent.
## Proof
Suppose the sequence $\left \langle {x_k} \right \rangle$ converges to $x \in X$.
That is for every $\epsilon > 0$ there is some index $N$ such that $d \left({x_n, x}\right) < \epsilon$ for all $n \ge N$.
The same $N$ will work for the new sequence with finitely many terms removed, so the new sequence converges to the same point $x$ as the original sequence.
For the second part note that also adding finitely many terms to a convergent sequence will still result in a convergent sequence.
This implies that removing finitely many terms from a divergent sequence will still result in a divergent sequence (if it were convergent then the original sequence must already have been convergent).
## Lemma 1
Let $\left({X, d}\right)$ be a metric space.
Let $\left\langle{x_k}\right\rangle$ be a sequence in $X$.
Let $\left\langle{x_{n_k} }\right\rangle$ be a subsequence of $\left\langle{x_k}\right\rangle$.
Then:
$\forall k \in \N: k \le n_k$
### Proof of Lemma 1
Note that $1 \le n_1 < n_2 < \ldots < n_k < \ldots$ by definition of a subsequence.
We will proceed with induction on $k$ to prove our claim.
By definition of a subsequence:
$1 \le n_1$
This is the basis for the induction | {
"domain": "proofwiki.org",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9793540677542981,
"lm_q1q2_score": 0.8096435542022516,
"lm_q2_score": 0.8267117898012104,
"openwebmath_perplexity": 120.11915809321874,
"openwebmath_score": 0.9913161396980286,
"tags": null,
"url": "https://proofwiki.org/wiki/Convergent_Sequence_with_Finite_Number_of_Terms_Deleted_is_Convergent"
} |
homework-and-exercises, quantum-field-theory, greens-functions, propagator
Title: Propagator of massive spin-1 particle I am currently working on an exercise where I need to derive the propagator, in momentum space, of a massive spin-1 particle. The image included is the solution to it, and I am having trouble understanding parts of it.
Namely, how do they go from eq. (80) to eq. (81)?
As I see it, eq. (80) is summed over $\mu$ and $\nu$ and is therefore a scalar equation. How can we extract information about the terms in the sum?
My second problem is that eq. (86) looks wrong, as the left part should be a scalar again, and the right part still has the uncontracted indices. Technically this is no problem, but something seems fishy to me.
It appears I don't really understand how they go from the tensorial equations to scalar ones, the rest of the solution is ok for me. Take the Fourier transform of both sides of equation $80$ with respect to $x$ and $y$, the right hand side will become $\delta^{(4)}(k_1-k_2)$, the left hand side will pick up a $\delta^{(4)}(k_1-k_2)\,\delta^{(4)}(k_1-q)$. After evaluating the $q$ integral on the left hand side you can replace $k_1$ with $q$ and drop the delta functions on both sides.
There is, technically, a mistake in the very first equation that gets corrected in the transition to $81$. Equation $78$ should read something like
$$\left[g^{\mu\nu}\left(\Box + M^2\right) - \partial^\mu\partial^\nu\right]G^F_{\nu\lambda} = i\delta^{4}(x-y)\,\delta^\mu_{\hphantom{\mu}\lambda}.$$
There is a way to argue the opening up of the summation that takes place in the initial work, I'm sure, I just can't think of how it's done right now. | {
"domain": "physics.stackexchange",
"id": 45866,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework-and-exercises, quantum-field-theory, greens-functions, propagator",
"url": null
} |
# Thread: probability of 52 card deck
1. ## probability of 52 card deck
I have a few simple probability questions regarding draws from a deck of cards.
1) If two cards are drawn face down, what is the probability that the second card is an ace?
2) If it is known the first card draw is an ace, how would that change the answer to (1)?
3) What is the probability that 2 randomly drawn cards are both aces?
4) If two cards are drawn from a deck, how many different combinations of the two cards are possible if the order is not considered and if the order is considered?
For (1), I think the answer is 4/51, but do I need to include the probability that the first card is not an ace?
For (2), I think it's 3/51.
For (3), I think it's: 4/52 * 3/51 = 1/221
For (4) - no idea
2. 1. You didn't learn anything about the 1st card since it's face down. So this is like choosing 1 card from 52, your probability is 4/52.
2. Correct
3. Correct
4. Order doesn't count - 52 choose 2.
Order does count - 52 x 51
3. Hello, chemekydie!
1) If two cards are drawn from a standard deck,
what is the probability that the second card is an ace?
I'll do this the Long Way.
There are 4 Aces and 48 Others.
We must consider both possibilities:
[1] The first card is an Ace: . $p(\text{1st Ace}) \:=\:\frac{4}{52}$
. . The second card is an Ace: . $P(\text{2nd Ace}) \:=\:\frac{3}{51}$
. . Hence: . $P(\text{Ace, then Ace}) \:=\:\frac{4}{52}\cdot\frac{3}{51} \:=\:\frac{12}{2652}$
[2] The first card is not an Ace: . $P(\text{1st not-Ace}) \:=\:\frac{48}{52}$ | {
"domain": "mathhelpforum.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9835969708496457,
"lm_q1q2_score": 0.8436981026071028,
"lm_q2_score": 0.8577680977182186,
"openwebmath_perplexity": 361.5042912679153,
"openwebmath_score": 0.7115872502326965,
"tags": null,
"url": "http://mathhelpforum.com/statistics/124739-probability-52-card-deck.html"
} |
homework-and-exercises, newtonian-mechanics, kinematics
Title: Methods to use in problems with equations of motion, where is required to determine a particular acceleration I've a doubt on problems with manipulation of equations of motion. I'll make an example of a situation I'm confused about.
Let $A$ and $B$ be two points that move on a line with constant speed,
$A$ is behind $B$ but it can reach $B$ since $v_A>v_B$. At $t=0$, when
the distance between the two points is $d$, $A$ is slowed by $-a$
deceleration. Determine the relation between $v_A,v_B,d,a$ such that
$A$ and $B$ do not collide (i.e. $A$ get $B$ with speed equal to $v_B$
and not greater). | {
"domain": "physics.stackexchange",
"id": 27714,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework-and-exercises, newtonian-mechanics, kinematics",
"url": null
} |
The value for $\theta$ must be solved for in this manner because for all values of $\theta$, $\tan\theta$ is only defined for $-\frac{\pi}{2}<\theta<+\frac{\pi}{2}$, and is periodic (with period $\pi$). This means that the inverse function will only give values in the domain of the function, but restricted to a single period. Hence, the range of the inverse function is only half a full circle.
Note that one can also use
$r=\sqrt{x^2 + y^2}$
$\theta = 2 \arctan \frac{y}{x+r}$
### To Cartesian coordinates from log-polar coordinates
$\begin{cases}x = e^\rho\cos\theta, \\ y = e^\rho\sin\theta.\end{cases}$
By using complex numbers $(x,y)=x+iy'$, the transformation can be written as
$x + iy = e^{\rho+i\theta} \,$
i.e. it is given by the complex exponential function.
### To log-polar coordinates from Cartesian coordinates
$\begin{cases} \rho = \log\sqrt{ x^2 + y^2}, \\ \theta = \arctan \frac{y}{x}. \end{cases}$
### To Cartesian coordinates from bipolar coordinates
$x = a \ \frac{\sinh \tau}{\cosh \tau - \cos \sigma}$
$y = a \ \frac{\sin \sigma}{\cosh \tau - \cos \sigma}$
### To Cartesian coordinates from two-center bipolar coordinates[1]
$x = \frac{r_1^2-r_2^2}{4c}$
$y = \pm \frac{1}{4c}\sqrt{16c^2r_1^2-(r_1^2-r_2^2+4c^2)^2}$
### To polar coordinates from two-center bipolar coordinates | {
"domain": "wikipedia.org",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9904406020637528,
"lm_q1q2_score": 0.8210146502950978,
"lm_q2_score": 0.828938806208442,
"openwebmath_perplexity": 1032.7566102935496,
"openwebmath_score": 0.9637818336486816,
"tags": null,
"url": "http://en.wikipedia.org/wiki/List_of_canonical_coordinate_transformations"
} |
molecular-biology, proteins
Title: What does ΔC and ΔN mean with regards to a protein sequence? I am reading a paper about the regulation of the nuclear export of the protein GSK3 and I have come across the following statement:
Full-length FLAG epitope-tagged mFrat1 (FLAG-Frat) and the
amino-terminal half of Frat (ΔC Frat) localized predominantly to the
cytoplasm of transfected MDCK cells (Fig. 1, A and B, i and iii).
Unexpectedly, the carboxyl-terminal half of Frat (ΔN Frat) accumulated
preferentially in the nuclei of transfected cells (Fig. 1B, iv). | {
"domain": "biology.stackexchange",
"id": 11119,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "molecular-biology, proteins",
"url": null
} |
ros, ros2, node
Thanks for the suggestions, and I will try out those changes. I should share the original code I had, which is the following:
class WizardNode(Node):
def __init__(self):
super(WizardNode,self).__init__('wizard')
self.get_logger().info('Initializing Wizard Node!')
self.app = Flask(__name__)
self.cors = CORS(self.app)
self.wizard = Wizard(self)
self.socketio = SocketIO(self.app, cors_allowed_origins="*")
self.socketio.on_namespace(self.wizard)
self.socket_thread = Thread(target=lambda:self.socketio.run(self.app),daemon=True)
self.socket_thread.start()
self.process_timer = self.create_timer(.1,self.process)
self.get_logger().info('Initialized!')
self.printer = PrettyPrinter()
def process(self):
time = self.get_clock().now()
self.wizard.timestep()
def main(args=None):
rclpy.init(args=args)
node = WizardNode()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
node.destroy_node()
rclpy.shutdown()
In this version, it seems that the socket.io thread fails to do any sort of broadcasting/emitting, which was why I tried restructuring in the ways above. I should also say that in this example, using eventlet's monkey_patch() basically broke everything.
Originally posted by AndrewJSchoen on ROS Answers with karma: 50 on 2020-02-27
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 34510,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros, ros2, node",
"url": null
} |
cell-biology, reproduction
Title: A program for cell motility assessment with a batch process function? Cell motility assessment is a branch of experimental biology or medical science. One example could be an assessment of treatment effects on sperm motility of an animal. The standard procedure involves taking film clips of sperm (or any other moving objects) through a microscope and measuring average linear velocity of particles on these film clips. The program used for measuring these linear velocities is important, and there are not too many choices to my knowledge. However, my knowledge might be limited.
I have previously used CellTrak for measuring sperm swimming speeds. The program works well, but lacks a batch processing function. As the assessment bases on a considerable number of replicates, I end up with 1000-2000 film clips to be analyzed and clicking my way through CellTrak is a tedious and irritating process. Also CellTrak licence costs a lot of money for such a poorly written program.
Therefore, my question is: Is someone aware of a similar program to CellTrak, which includes batch processing option, or even better, which works through command line and can be looped? Are there open source options or extensions to widely used open source programs (ImageJ, Bioconductor, etc.)? Please give a short tutorial/personal experience to the usage of the suggested program (if any). ImageJ has several tracking plugins, a good one being TrackMate. Most of it's functions can be scripted in various languages and the Fiji distribution can also run in headless mode. It's open source and won't cost you any mony for a much lager feture set.
I personally have used ImageJ in headless mode scripted with its own macro language because it is relatively easy to learn.
TrackMate also should output average speeds for the tracks, if I remember correctly. Otherwise you would have to write a script to measure those from the tracking data. You can use the IJ macro language, Python, Java or one of the other supported languages.
In combination with a bash script wrapper for its headless mode I even use it in Makefiles to convert my tiff stacks to avi and put scale bars and time stamps on everything.
Hope this helps. | {
"domain": "biology.stackexchange",
"id": 6853,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "cell-biology, reproduction",
"url": null
} |
This isn’t exactly a programming post, but it does demonstrate the same kind of problem solving that is often found in devising efficient algorithms.
I decided to represent each islander with a letter from A to L. This makes it easy to unambiguously and concisely represent combinations of islanders. I show each trial with the seesaw as a column. The “Test” column shows what islanders are put on the seesaw as left vs. right. The “Result” column shows “=” if both sides were equal, “<” if the left side weighed less than the right, or “>” if the left side weighed more than the right. Then the “Possibilities” column shows what possible solutions remain given the result of the trial. As we move from the 1st trial towards the 3rd we can see the remaining possibilities reduce as more results eliminate solutions.
When solving this puzzle we know right away that we cannot rely on the seesaw always tilting to the left or right. This seems to be people’s initial attempt at solving this problem. Just put six on one side and six on the other and work your way down. However, 3 trials and only 2 possible results would only give us up to 8 solutions because 2 x 2 x 2 = 8. So we know that we have to rely some trials being balanced to find all the solutions. Therefore, it is probably not a good idea to put six vs. six because there is no way that seesaw could be balanced since the different islander would always be on the seesaw giving only two possible results which doesn’t tell us which side the different islander is on.
The first trial that gives the most information is to do four vs. four (ABCD vs. EFGH). No matter what the result we have reduced the possible solutions from 24 to 8. | {
"domain": "josiahdev.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.988668248138067,
"lm_q1q2_score": 0.8363564198395739,
"lm_q2_score": 0.8459424295406088,
"openwebmath_perplexity": 1418.1227835708082,
"openwebmath_score": 0.6284764409065247,
"tags": null,
"url": "http://josiahdev.com/blog/"
} |
# Prove that there is a multiple of 2009 that ends with the digits 000001
Prove that there is a multiple of 2009 that ends with the digits 000001.
May one generalise this to: There exists a multiple of $x$ that ends with the digits $y$ (where $y$ consists of $n$ digits) if $x$ and $10^n$ are relatively prime?
The proof may be constructive, or non constructive.
Any help would be greatly appreciated.
I figured the multiple has to end in a $9$: $2009 \cdot 889$ gives $001$ as the three ending digits. I then tried to see if I could get the $4$th last digit to be a zero, but I must admit I am clearly missing something at that point.
• Write down a few multiples of $2009$. Maybe try the first $246889$ :P Mar 29 '15 at 17:22
• Well it needs to end in a one, so I figured the multiple has to end in a 9. 2009 * 889 gives 001 as the three ending digits. I then tried to see if I could get the 4th last digit to be a zero, but I must admit I am clearly missing something at that point. Mar 29 '15 at 17:24
• @flabby99 Well, both hints in the answer work and boil down to the same. Another answer is hidden somewhere here ;) Mar 29 '15 at 17:26
• @AlexR Yes I see that there is some magical number within these comments. However, I would like to understand better how to obtain such a magic number :P Mar 29 '15 at 17:27
• @flabby99 It's from the extended euclidean algorithm to $\gcd(1000000,2009) = 1$. Mar 29 '15 at 17:28
## 3 Answers
Here is a short proof using modular arithmetic.
Consider $m=1000000$. The numbers $2009$ and $m$ are relatively prime to each other, so
$$2009^{\phi(m)}\equiv 1\pmod m$$ | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9817357221825193,
"lm_q1q2_score": 0.8529582859561454,
"lm_q2_score": 0.8688267796346599,
"openwebmath_perplexity": 240.18195927182714,
"openwebmath_score": 0.6910312175750732,
"tags": null,
"url": "https://math.stackexchange.com/questions/1211713/prove-that-there-is-a-multiple-of-2009-that-ends-with-the-digits-000001"
} |
orbitals, molecular-orbital-theory, hybridization
Title: What is the origin of the differences between the MO schemes of O₂ and N₂? Here are the MO schemes of $\ce{N2}$ (left) and $\ce{O2}$ (right).
Why is the $\sigma$-MO formed by the $p$ AOs energetically above the $\pi$-MO for $\ce{N2}$ but not for $\ce{O2}$?
Can it be explained this way:
In second period elements with more than a half filled $\ce{p}$ orbitals, the energy pattern of the MOs is regular.
In second period elements with less than or half filled $\ce{p}$ orbitals, as the $\ce{s}$ and $\ce{p}$ atomic orbitals have similar energies, so the formed $\ce{\sigma_{g}}$ MO would have similar energy as $\ce{\sigma_{u}}$, but because of electron cloud repulsion it has a big increase in energy, hence it is above the $\pi$ orbitals? And this phenomenom is known as sp mixing.
Or am I wrong somewhere? Is my reasoning corret? This phenomenon is explained by s-p mixing. All the elements in the second period before oxygen have the difference in energy between the 2s and 2p orbital small enough, so that s-p mixing (combination) can occur lowering the energy of the σ(2s) and σ*(2s) and increasing the energy of the σ(2p) and σ*(2p) molecular orbitals. By moving towards right in a period, the s orbital gets more stabilized than the p orbital and the difference in their energies increases, making the s-p mixing for oxygen much smaller. | {
"domain": "chemistry.stackexchange",
"id": 2499,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "orbitals, molecular-orbital-theory, hybridization",
"url": null
} |
python, pyqt
def select_convert(self, convert_choice):
match convert_choice:
case ConvertChoice.wgs84_psd93:
dlg = self.dlg_class_geog_proj(
self, convert_choice, 'WGS84 to PSD93', 'Longitude', 'Latitude',
'Easting', 'Northing'
)
case ConvertChoice.psd93_wgs84:
dlg = self.dlg_class_proj_geog(
self, convert_choice, 'PSD93 to WGS84', 'Easting', 'Northing',
'Longitude', 'Latitude'
)
case ConvertChoice.psd93_utm40:
dlg = self.dlg_class_proj_proj(
self, convert_choice, 'PSD93 to UTM 40N', 'Easting', 'Northing',
'Easting', 'Northing'
)
case ConvertChoice.utm40_psd93:
dlg = self.dlg_class_proj_proj(
self, convert_choice, 'UTM 40N to PSD93', 'Easting', 'Northing',
'Easting', 'Northing'
)
case ConvertChoice.lon_lat:
dlg = self.dlg_class_geog_geog(
self, convert_choice, 'DMS to Degrees', 'Longitude', 'Latitude',
'Longitude', 'Latitude'
)
case _:
assert False, (
f'Check {convert_choice} in {__class__.__name__} / '
f'{__class__.select_convert.__name__}'
)
dlg.exec_()
def action_quit(self):
self.close()
sys.exit()
class QtMixinMeta(type(QtWidgets.QDialog), ABCMeta):
pass | {
"domain": "codereview.stackexchange",
"id": 43853,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pyqt",
"url": null
} |
c#, beginner, object-oriented, playing-cards
if (HandRank == other.HandRank) //if the hand rank is equal, sort the cards by face value and compare the two biggest
{
Hand sortThisHand = Program.sortHandbyFace(this);
Hand sortOtherHand = Program.sortHandbyFace(other);
if (sortThisHand.Cards[4].Face > sortOtherHand.Cards[4].Face)
return 1;
else if (sortThisHand.Cards[4].Face < sortOtherHand.Cards[4].Face)
return -1;
else
return 0;
}
else if (HandRank > other.HandRank)
return 1;
else if (HandRank < other.HandRank)
return -1;
else
throw new Exception("Hand rank is not initiated");
}
}
public class Card
{
public Face Face { get; }
public Suit Suit { get; }
public Card(Suit suit, Face face)
{
Face = face;
Suit = suit;
}
public override string ToString()
{
string card = "(" + Face + " of " + Suit + "s) ";
return card;
}
}
public enum Face
{
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace
}
public enum Suit
{
Club, Diamond, Heart, Spade
}
public enum PokerHandsRank
{
HighCard,
Pair,
TwoPair,
ThreeOfKind,
Straight,
Flush,
FullHouse,
FourOfKind,
StraightFlush,
RoyalFlush
}
note: I had a lot trouble with initializing the handrank by using the checkHandRank Method(stack overflow exception) so I had to leave it at the minimum enum of highcard and run the checkhand method in main program class but its definitely not right in my opinion.
CheckHandRank and sortHandByFace Methods
public static PokerHandsRank CheckHandRank(Hand hand)
{
PokerHandsRank flushCheck = CheckHandForFlush(hand);
PokerHandsRank pairCheck = CheckHandForPairs(hand);
PokerHandsRank straightCheck = CheckHandForStraight(hand); | {
"domain": "codereview.stackexchange",
"id": 23904,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, object-oriented, playing-cards",
"url": null
} |
catkin-make
# 7. Libraries/Executables to build (add_library()/add_executable()/target_link_libraries())
include_directories(src/include)
add_executable(candump src/candump.c
src/lib.c
src/lib.h
src/terminal.h
src/include/linux/can.h
src/include/linux/can/bcm.h
src/include/linux/can/error.h
src/include/linux/can/gw.h
src/include/linux/can/isotp.h
src/include/linux/can/netlink.h
src/include/linux/can/raw.h
)
target_link_libraries(candump ${catkin_LIBRARIES})
add_definitions(-D_LINUX -D__STDC_FORMAT_MACROS -DUSE_INTTYPES__ -DHAVE_PCAP -D_FILE_OFFSET_BITS=64 -DSO_RXQ_OVFL=40 -DPF_CAN=29 -DAF_CAN=PF_CAN)
# 8. Tests to build (catkin_add_gtest())
# 9. Install rules (install())
#### END OF FILE #####
`
Originally posted by bjem85 on ROS Answers with karma: 163 on 2014-05-28
Post score: 0
The INCLUDE_DIRS directive to catkin_package is not intended to add include directories to your package; you should use include_directories for that, as you've found.
The catkin_package function specifies which dependencies your package exports to its dependencies. In particular, INCLUDE_DIRS specifies which directory in your package contains the header directory that should be on the include path for any packages that compile against your package.
Originally posted by ahendrix with karma: 47576 on 2014-05-28
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 18089,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "catkin-make",
"url": null
} |
rust
Title: Zero the excess digits of an array I wrote some code that set the last few elements of an array to zero. I call these last elements the "excess":
const MAX_DIGITS: usize = 20;
pub fn zero_excess_digits(digits: &mut [u8; MAX_DIGITS], n_digits: usize) {
for i in n_digits..MAX_DIGITS {
digits[i] = 0;
}
}
However, Clippy considers this a needless_range_loop and suggests I write the code like this:
const MAX_DIGITS: usize = 20;
pub fn zero_excess_digits_iter_for(digits: &mut [u8; MAX_DIGITS], n_digits: usize) {
for d in digits.iter_mut().take(MAX_DIGITS).skip(n_digits) {
*d = 0;
}
}
Usually when I've used Clippy, it's given me solid advice. But in this case, I just don't see it. I've tried both versions in Godbolt/Compiler Explorer: https://godbolt.org/z/7G8McseKs
it optimizes my original version to a call to memset (12 lines of asm);
for the .iter_mut() version, it generates code for the loop (30 lines of asm! Unacceptable!)
I tried using a .for_each() instead of for ... and it went down to 24 lines of asm.
Is there some deep insight from Clippy that I'm missing? Is there a more idiomatic way of writing this "zero the excess" code? There's a simpler and more idiomatic solution:
digits[n_digits..].fill(0);
You could also do:
for d in &mut digits [n_digits..MAX_DIGITS] {
*d = 0;
}
However, these work slightly differently then your original. If n_digits is > MAX_DIGITS, the slice versions will panic on the slice. But your original version will do nothing, because the range is considered empty. | {
"domain": "codereview.stackexchange",
"id": 43718,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
astrophysics, asteroids, comets, orbital-mechanics
Title: How do comets and other solar system bodies gain energy to exit the solar system? I recently learnt that some comets like C/1980 E1 (Bowell) interacted with objects like gas giants in the solar system and gained enough energy to exit the solar system. But from Physics, I know that only if the total mechanical energy of a body is positive, can the body exit the solar system. An interaction with a gas giant should merely convert some of the potential energy of the body to kinetic energy and the total energy of the body should remain unchanged. If so, how can such bodies achieve positive mechanical energy to exit the solar system? The mechanism by which the path, speed and energy of a celestial object or an artificial spacecraft is altered by massive planets and bodies is Swing-by or gravity assist. Any encounter between a comet and a gas-giant like Jupiter is almost an elastic mechanical collision (though no physical contact occurs) and in any mechanical collision, energy exchange between the bodies undergoing collision takes place. In this case, when the comet C/1980 E1 passed closed to Jupiter, Jupiter passed on some of its mechanical energy to the comet, rendering its total mechanical energy positive and hence setting the comet free and no longer bounded to the solar system. It is the total mechanical energy of the Jupiter+C/1980 E1 that was conserved, not just that of the comet. But the small decrease in the mechanical energy of Jupiter would not have a significant impact on the massive planet. | {
"domain": "astronomy.stackexchange",
"id": 2593,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "astrophysics, asteroids, comets, orbital-mechanics",
"url": null
} |
ros, urdf, tutorial, robot-state-publisher
Found 1 error(s).
ERROR The following packages have rpath issues in manifest.xml:
* r2d2: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* rosconsole: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* roscpp: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* std_msgs: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* sensor_msgs: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* tf: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* rostest: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* geometry_msgs: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib"
* message_filters: found flag "-L/opt/ros/fuerte/lib", but no matching "-Wl,-rpath,/opt/ros/fuerte/lib" | {
"domain": "robotics.stackexchange",
"id": 11472,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros, urdf, tutorial, robot-state-publisher",
"url": null
} |
quantum-computing, quantum-information
Write out the binary gcd algorithm as a loop:
def gcd(a, b):
let shift = 0
while a != 0 or b != 0:
let pa = a & 1
let pb = b & 1
let pc = a >= b
if pa == 0 and pb == 0:
a >>= 1
b >>= 1
shift++
elif pa == 0:
a >>= 1
elif pb == 0:
b >>= 1
elif pc:
a -= b
a >>= 1
else:
b -= a
b >>= 1
return (a | b) << shift
Keep track of any intermediate values so you can uncompute them instead of leaking them. Also switch to a fixed number of iterations to avoid leaking the size of the inputs.
def gcd(a, b, len_a, len_b):
let shift = 0
# Note: >> and << are now bit rotations instead of bit shifts
for i in range(len_a + len_b):
let g = a > b
let pa = (a & 1) == 0
let pb = (b & 1) == 0
if pa and pb and a != 0 and b != 0: shift++
if pa: a >>= 1
if pb: b >>= 1
if not pa and not pb:
if g:
a -= b
a >>= 1
else:
b -= a
b >>= 1
# We can't clear these yet, so just set them aside until later
push g, pa, pb
let result = (a | b) << shift
# Uncompute intermediate values
for i in range(n + m):
pop pb, pa, g
if not pa and not pb:
if g:
a <<= 1
a += b
else:
b <<= 1
b += a
if pb: b <<= 1
if pa: a <<= 1
if pa and pb and a != 0 and b != 0: shift--
unlet pb = (b & 1) == 0
unlet pa = (a & 1) == 0
unlet g = a > b
unlet shift = 0
return result | {
"domain": "cstheory.stackexchange",
"id": 3709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "quantum-computing, quantum-information",
"url": null
} |
java, object-oriented, minecraft
/**
* Gets a nation from the given uuid
*
* @param uuid The nations uuid
* @return Returns a Nation if a nation with the given uuid exists, null otherwise
*/
@Nullable
public static Nation getNation(@NotNull UUID uuid) {
Validate.notNull(uuid);
return getNations().getOrDefault(uuid, null);
}
/**
* Check if a nation with the given uuid exists
*
* @param uuid The nations uuid
* @return Return true if a nation with the given uuid exists, false otherwise
*/
public static boolean nationExists(@NotNull UUID uuid) {
Validate.notNull(uuid);
return getNations().containsKey(uuid);
}
/**
* Sets the nation and rank of the given town, and updates it in the database
*
* @param town The town to set
* @param rank The rank to give the town, if this is NationRank.CAPITAL, there must not already be a nation capital
*/
public void setTown(@NotNull Town town, @NotNull NationRank rank) {
Validate.notNull(town);
Validate.notNull(rank);
if (rank == CAPITAL)
Validate.isTrue(getCapital() == null);
towns.put(town, rank);
town.setNation(this);
NationManager.setNation(town, this, rank);
}
/**
* Accepts an invite to a nation
*
* @param town The town to join, this town must be invited
*/
public void acceptInvite(@NotNull Town town) {
Validate.isTrue(town.isInvited(this));
NationInviteManager.removeInvite(town.getNationInvites().get(this));
town.getNationInvites().remove(this);
setTown(town, MEMBER);
} | {
"domain": "codereview.stackexchange",
"id": 21061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, minecraft",
"url": null
} |
python, genetic-algorithm
numActivities = 8
popSize = 500
eliteSize = 4
mutationRate = 0.08
generations = 200
numDurationGenes = 8 # This should be equal to number of ST genes
Thus far, these have been the values with which have most reliably produced good schedules. To test it using more than eight activities, first delete all line featuring the word "custom" then run as normal. Those modules which aren't called directly are included because they are very useful for debugging or analysing populations of candidate solutions.
Representing Activities, Time, and How They Interact
quantaDuration = 5 # each block of time is equal to 5 mins long
hoursPerDayToSchedule = 12
dailyQuanta = int(60 * 24 * (hoursPerDayToSchedule / 24) / quantaDuration)
The algorithm divides a time period into 5 minute quanta, so named because they are the fundamental unit of time. However, unlike the vast majority of scheduling algorithms I've seen, this algorithm's computerational complexity scales nicely with the number of quanta so one can efficiently achieve a high granularity of time.
activitiesInteractionList = []
for i in range(0, numActivities**2):
activitiesInteractionList.append(random.randint(1, 10))
activitiesInteractionMatrix = np.array(activitiesInteractionList).reshape(
[numActivities, numActivities])
activitiesInteractionMatrix
array([[ 1, 4, 5, 7, 7, 5, 2, 8],
[ 9, 8, 5, 5, 2, 7, 10, 5],
[ 4, 4, 4, 9, 4, 2, 3, 6],
[ 5, 8, 1, 8, 8, 8, 7, 10],
[10, 5, 1, 8, 8, 8, 8, 2],
[ 2, 8, 7, 2, 8, 5, 3, 7],
[ 6, 2, 5, 10, 4, 2, 8, 7],
[ 5, 9, 2, 9, 1, 7, 5, 5]]) | {
"domain": "codereview.stackexchange",
"id": 35993,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, genetic-algorithm",
"url": null
} |
homework-and-exercises, newtonian-gravity
One very obvious approach is to consider the spherical empty regions as a superposition of two spherical regions of densities $\rho$ and $-\rho$. From this one can easily deduce that the spherical regions will move towards each other. However, I am not satisfied with this because the theory of negative mass is not defined in reality. Also, what would happen if the density varied according to some law? Will the same approach work? The method of superposition you suggested in your question is sound. Knowing that gravity obeys an inverse square law we describe the force (per test mass) at point $\vec{x}$ as
$$\vec{F}(\vec{x})=\int_V \frac{-(\vec{x}-\vec{x}')}{|\vec{x}-\vec{x}'|^3} \rho(\vec{x}')d^3x'$$
where $\vec{x}'$ describes positions within a massive volume $V$ with corresponding densities $\rho(\vec{x}')$ that contribute to the gravity force felt at $\vec{x}$ (and the negative ensures attraction). Now I define a cavity volume $\bar{V}$ that describes everywhere that isn't $V$ (loosely, $\bar{V}\equiv\infty \setminus V$). Then the force is equivalently:
$$\vec{F}(\vec{x})=\int_\infty \frac{-(\vec{x}-\vec{x}')}{|\vec{x}-\vec{x}'|^3} \rho(\vec{x}')d^3x' - \int_{\bar{V}}\frac{-(\vec{x}-\vec{x}')}{|\vec{x}-\vec{x}'|^3} \rho(\vec{x}')d^3x'$$ | {
"domain": "physics.stackexchange",
"id": 36235,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework-and-exercises, newtonian-gravity",
"url": null
} |
newtonian-mechanics, classical-mechanics, chaos-theory, fractals
With that, let’s turn to your individual questions:
This makes me question whether there is a critical point of total energy which would transform the system into being chaotic and everything outside of the basic solution state becomes entirely non-differentiable, or whether the mapping actually always maintains pockets of local differentiability, just on such a small scale it appears to be totally chaotic.
As elaborated above, you always have finitely sized regions that map to the same basin; they just become smaller.
It seems apparent in this computational solution that there are large swaths which have constant (therefore differentiable) solutions outside of the base local minimum. I wonder if this is physical or a remnant of the computational method not being truly continuous or if there are consistent solutions we can look to in these systems.
These larger areas correspond to something like the pendulum taking swinging through the middle, taking a left turn, swinging through the middle again, taking the right turn and then settling on the blue magnet.
The more of these swings (or similar) you have, the more smaller the area usually becomes.
Would a true physical system actually show more of a probability density rather than a guaranteed final solution?
Sure, at some point you have things like the movement of individual air molecules affecting the behaviour of the pendulum near the separatrix, possibly pushing it to the other side. At this point, you only have probabilities and very quickly the final state is completely random.
This is the classical butterfly effect: At some point tiny changes to the system change the system’s long-term behaviour completely. | {
"domain": "physics.stackexchange",
"id": 90397,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "newtonian-mechanics, classical-mechanics, chaos-theory, fractals",
"url": null
} |
-> [0,0,0] , [0,1,4] -> [0,0,2] xÈ Sum the resulting array Scala All approaches are implementations of the rule shown by tsh. 109 l.zipWithIndex.foldLeft(1>0){case(r,(v,i))=>r&l.zip(l.tail).slice(i+1,l.size).forall(x=>l(i)>x._1|l(i)<x._2)} 101 (for(i<-l.indices)yield l.zip(l.tail).slice(i+1,l.size).forall(x =>l(i)>x._1|l(i)<x._2)).forall(x=>x) 98 l.indices.foldLeft(1>0)((r,i)=>r&(l.zip(l.tail).slice(i+1,l.size).forall(x=>l(i)>x._1|l(i)<x._2))) 78 (for(i<-l.indices;j<-i+1 to l.size-2)yield l(i)>l(j)|l(i)<l(j+1)).forall(x=>x) If it must be a function and not just an expression then each line have to start with (17 bytes) def%(l:Seq[Int])= Oracle SQL, 177 bytes with r(i,v)as(select rownum,value(t)from table(a)t) select nvl(min(case when r.v<p.l and r.v>p.v then 0end),1)from r,(select i,lag(v)over(order by i)l,v from r)p where r.i+1<p.i Since there is no boolean type in Oracle SQL, query returns either 1 or 0. Oracle SQL 12c, 210 bytes with function f(n ku$_objnumset,i int)return int as begin return | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9808759674419192,
"lm_q1q2_score": 0.8064655545473448,
"lm_q2_score": 0.8221891261650247,
"openwebmath_perplexity": 3474.962121090979,
"openwebmath_score": 0.30547282099723816,
"tags": null,
"url": "https://codegolf.stackexchange.com/questions/174293/is-this-a-bst-pre-order-traversal"
} |
noise, frequency, bandwidth
Title: Detection Bandwidth for Noise Power Calculation I am trying to calculate the $P_{noise}$ in an experimental setup, such as given
below. The DUT is excited at a predefined frequency, $f$ , with
power $P_\text{in}$. The total power is measured by the RF digitizer. We
can assume that the generator and the sample are ideal so that only noise in the
system , $N_{a1}$, is originating from the Low Noise Amplifier (LNA).
Now, I know that $P_{Na1} = kT_e \Delta f$ and $T_e$ can be found in LNA
specs. What confuses me is the choice of bandwidth.
If we look at the RF front end of the detector;
We see that RF input is first shifted to IF band, then adjusted (to cover ADC full range I suppose) and filtered before ADC.
ADC has $f_{sample} = 250\,\text{MHz}$. Also, the device allows $f_{sample}$ down to 10 kHz.
In view of these informations, here are my questions: | {
"domain": "dsp.stackexchange",
"id": 8561,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "noise, frequency, bandwidth",
"url": null
} |
python, beginner, object-oriented, email
Title: Quick email program using Python classes I've just learned about using classes and I have this constant feeling that I'm just writing things inefficiently or wrong.
Could I get some advise on this quick "email" program? How would you have set this program up, more classes? methods outside of User class? Should I be using Global differently? Is my commenting structured well? I'm entirely self-taught so I want to know if I've developed any bad habits or something like that.
To get it to run, all you need is to replace the inboxLocation variable with a location on your station.
import os
class User:
# Domain name for emails and location for inboxes
global emailDomain
emailDomain = "@test.local"
global inboxLocation
inboxLocation = "E:/Users/Dylan/Desktop/Inboxes/"
# User Creation
def __init__(self, firstName, lastName, password):
self.firstName = firstName
self.lastName = lastName
self.userName = firstName[0] + lastName
self.address = self.userName + emailDomain
self.password = password
self.inbox = inboxLocation + self.address
# Create user inbox if it doesn't exist
if not os.path.exists(self.inbox):
os.mkdir(self.inbox)
# Creates a header at the top of every page with the menu title and username
def getHeader(self, currentMenu):
header = (currentMenu + " | " + self.userName + "\n")
print(header)
# Display information about a user
def getInfo(self):
print("User Information for %s\n" % self.address)
print("First Name: %s" % self.firstName)
print("Last Name: %s" % self.lastName)
print("Email Address: %s" % self.address)
print("Inbox Location: %s\n" % self.inbox)
input("\n[Enter to Continue...]\n")
self.mainMenu() | {
"domain": "codereview.stackexchange",
"id": 27513,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, email",
"url": null
} |
quantum-field-theory, hilbert-space, scattering, vacuum, s-matrix-theory
Title: Asymptotic states in the Heisenberg and Schrödinger pictures One can show that, in the interacting theory, the operators that create single-particle energy-momentum eigenstates from the vacuum are
\begin{align}
(a_p^{\pm\infty})^\dagger=\lim_{t\to\pm\infty}(a_p^t)^\dagger\tag*{(1)}
\end{align}
where
\begin{align}
(a_p^t)^\dagger=i\int{\rm d}^3x\,e^{-ipx}\overleftrightarrow{\partial_0}\phi(x)=\int{\rm d}^3x\,e^{-ipx}\left(\omega_{\boldsymbol{p}}\phi(x)-i\pi(x)\right).\tag*{(2)}
\end{align}
(see e.g. Srednicki QFT or this answer; I'm using superscript $t$ to emphasise that this operator does not undergo the usual unitary time evolution, but is instead redefined at each $t$). These are used to create the asymptotic states that go into the calculation of the $S$-matrix. For example, in $2\to n$ scattering, the "in" and "out" states would be
\begin{align}
|i\rangle&=|k_1k_2\rangle=(a_{k_1}^{-\infty})^\dagger (a_{k_2}^{-\infty})^\dagger|\Omega\rangle\tag*{(3)}\\
|f\rangle&=|p_1\cdots p_n\rangle=(a_{p_1}^{\infty})^\dagger\cdots (a_{p_n}^{\infty})^\dagger|\Omega\rangle,\tag*{(4)}
\end{align} | {
"domain": "physics.stackexchange",
"id": 96695,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "quantum-field-theory, hilbert-space, scattering, vacuum, s-matrix-theory",
"url": null
} |
renormalization, integration, approximations
Title: Approximation of an integral on a certain limit In Peskin & Schroeder - Chapter 6 - the authors make the following approximation when $-q^2\rightarrow\infty$
$$\int_0^1 \!\!d\xi\, \frac{-q^2/2}{-q^2\xi(1-\xi)+m^2} \simeq \frac{1}{2}\int_0d\xi\, \frac{-q^2}{-q^2\xi+m^2} + \begin{pmatrix}\!\text{equal contribution}\!\\ \text{from } \xi\approx 1 \end{pmatrix}.\tag{6.64} $$
It might be silly but I don't 'get' all the steps. It is clear to me that the function goes as $\frac{1}{2\xi(1-\xi)}$ in the $-q^2\rightarrow\infty$ limit and the dominant contributions are then about $\xi=0$ and $\xi=1$, but... I don't see clearly what they did in the right hand side. It doesn't seem like a Taylor expansion, then , what is it?
For context: this is a relevant integral for the analysis of IR divergences. Here's what I could conjure up. I don't like it cause of sweeping infinities under the rug so feel free to downvote/not accept.
Let
\begin{align}
f\left(\frac{m^2}{-q^2} \right) = \frac{1}{2} \int_0^1 d\xi\; \frac{1}{\xi(1-\xi)+\frac{m^2}{-q^2}}.
\end{align}
Then
\begin{align} | {
"domain": "physics.stackexchange",
"id": 91849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "renormalization, integration, approximations",
"url": null
} |
c++, memory-management, c++20
all_chunks_ is a one-off thing, so I wouldn't try to force it to deallocate itself using RAII. But if you do want that, consider using a std::unique_ptr<unsigned char[], Deleter>, where Deleter is taking care of deallocating the mapped file. | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, memory-management, c++20",
"url": null
} |
c#, .net, validation
Then you can use it with the following:
// FirstName may not be null and must be between 1 and 5
// LastName may be null, but when it is defined it must be between 3 and 10
// Age must be positive and below 200
record Person(string FirstName, string? LastName, int Age, Guid Id)
{
private readonly bool _valid = Validation.NotNull(FirstName).LengthBetween(1, 5).IsValid() &&
(LastName?.LengthBetween(2, 10).IsValid() ?? true) &&
Age.RangeWithin(0, 200).IsValid();
}
The ?? true is VERY important, it is to ensure validation continues in case the nullable LastName was indeed null, otherwise it would short-circuit.
Perhaps it would be better (safer) to use another static AllowNull method to wrap the entire validation of that variable in, like so:
public static class Validation
{
public static bool IsValid<T>(this T _)
{
return true;
}
public static bool AllowNull<T>(T? _)
{
return true;
}
public static T NotNull<T>(T @value, [CallerArgumentExpression("value")] string? thisExpression = default)
{
if (value == null) throw new ArgumentNullException(thisExpression);
return value;
}
public static string LengthBetween(this string @value, int min, int max, [CallerArgumentExpression("value")] string? thisExpression = default)
{
if (value.Length < min) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have less than {min} items");
if (value.Length > max) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have more than {max} items");
return value;
} | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, validation",
"url": null
} |
particle-physics, symmetry, standard-model, group-theory, representation-theory
\end{equation}
This Lagrangian is not invariant under the flavor $ SU(3) $ transformation,
\begin{equation}
\psi _i \rightarrow U _{ ij} \psi _i
\end{equation}
since the mass term in not invariant. But if we work well above the strange mass (but still below the charm mass) then we approximately have,
\begin{equation}
{\cal L} _{ QCD} \approx \sum _{ i = u,d ,c }\bar{\psi} _i ( i D _\mu \gamma ^\mu ) \psi _i - \frac{1}{4} G _{ \mu \nu } ^a G ^{ \mu \nu } _{ a}
\end{equation}
which is approximately invariant under the flavor symmetry.
Hadrons obtain their masses primarily due to non-perturbative interactions between the quarks. It turns out that QCD becomes non-perturbative around,
\begin{equation}
\Lambda _{ QCD} \approx 200 \mbox{MeV}
\end{equation}
while the charm mass is $ \approx 1000 \mbox{MeV} $ and the strange mass is $ 100 \mbox{MeV} $. Thus hadrons masses can be approximately described the massless Lagrangian above. Since the Lagrangian has an additional symmetry, the particles must form multiplets of the symmetry. While we can't calculate their masses directly, they should approximately exhibit such a symmetry in their masses. This is why we expect the hadron masses to be arranged into flavor multiplets. | {
"domain": "physics.stackexchange",
"id": 14899,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "particle-physics, symmetry, standard-model, group-theory, representation-theory",
"url": null
} |
Now, the first sum here simplifies to $$\sum_{k\geq 0} \frac{(x^2+1) - (2k+1)(x^2-1)}{x^{2k+1}+1} = \sum_{k\geq 0} \frac{(2k+2)-2k x^2}{x^{2k+1}+1}$$ $$=\sum_{k\geq 1} \left( \frac{2k}{x^{2k-1}+1} - \frac{2k x^2}{x^{2k+1}+1}\right)=(1-x^2)\sum_{k\geq 1} \frac{2k}{(x^{2k-1}+1)(x^{2k+1}+1)}.$$ Hence $$\frac{S}{x^2-1} = \sum_{k\geq 0}\frac{2k+1}{(x^{2k+1}+1)^2} - \sum_{k\geq 1} \frac{2k}{(x^{2k-1}+1)(x^{2k+1}+1)}$$ $$\geq \sum_{k\geq 0}\frac{2k+1}{(x^{2k+1}+1)^2} - \sum_{k\geq 1} \frac{2k}{(x^{2k}+1)^2} = \sum_{k\geq 1} \frac{(-1)^{k-1}k}{(x^{k}+1)^2}.$$ Here we used AM-GM inequality $x^{2k-1}+x^{2k+1}\geq 2x^{2k}$ and thus | {
"domain": "mathoverflow.net",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9828232930001333,
"lm_q1q2_score": 0.8058102769619352,
"lm_q2_score": 0.8198933447152498,
"openwebmath_perplexity": 348.78043502526896,
"openwebmath_score": 0.9168937802314758,
"tags": null,
"url": "https://mathoverflow.net/questions/217711/curious-inequality"
} |
Example 5. Calculate ${\int_{{0}}^{{2}}}\frac{{{{x}}^{{2}}}}{{{\left({{x}}^{{2}}+{4}\right)}}^{{\frac{{5}}{{2}}}}}{d}{x}$
Since ${{\left({{x}}^{{2}}+{4}\right)}}^{{\frac{{5}}{{2}}}}={{\left(\sqrt{{{{x}}^{{2}}+{4}}}\right)}}^{{5}}$ then make substitution number 3: ${x}={2}{\tan{{\left({u}\right)}}}$. In this case ${d}{x}={2}{{\sec}}^{{2}}{\left({u}\right)}{d}{u}$. | {
"domain": "emathhelp.net",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9901401464421569,
"lm_q1q2_score": 0.8000997914505411,
"lm_q2_score": 0.8080672158638527,
"openwebmath_perplexity": 280.83517356967593,
"openwebmath_score": 0.993171215057373,
"tags": null,
"url": "https://www.emathhelp.net/en/notes/calculus-2/integration-techniques/trigonometric-substitutions/"
} |
python, python-3.x, pandas
Title: How to better process csv file with pandas and further dealing with set I have below working code with pandas and python, i'm looking if there is an improvement or simplification which can be done.
Can we Just wrap this up into a definition.
$ cat getcbk_srvlist_1.py
#!/python/v3.6.1/bin/python3
from __future__ import print_function
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
import pandas as pd
import os
##### Python pandas, widen output display to see more columns. ####
pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)
##################### END OF THE Display Settings ###################
################# PANDAS Extraction ###########
df_csv = pd.read_csv(input("Please input the CSV File Name: "), usecols=['Platform ID', 'Target system address']).dropna()
hostData = df_csv[df_csv['Platform ID'].str.startswith("CDS-Unix")]['Target system address']
hostData.to_csv('host_file1', header=None, index=None, sep=' ', mode='a')
with open('host_file1') as f1, open('host_file2') as f2:
dataset1 = set(f1)
dataset2 = set(f2) | {
"domain": "codereview.stackexchange",
"id": 32858,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
ngs, phylogenetics
Title: What i5 index should I use on the Illumina sample sheet for an unindexed p5 primer? I have an upcoming run on a HiSeq X and most of the libraries in the pool have both i5 and i7 indices. However, some of the libraries were made with the IS4 p5 oligo and it is unindexed.
The IS4 indexing oligo is from the following paper. The sequence is below.
Meyer, Matthias, and Martin Kircher. "Illumina sequencing library
preparation for highly multiplexed target capture and sequencing."
Cold Spring Harbor Protocols 2010.6 (2010): pdb-prot5448.
miseq index
5' TCTTTCC 3'
>>>>>>>
5' AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTT 3'
^------------------^ ^--------------------^
flowcell binding seq adapter-binding seq
When we sequence these libraries dual-indexed on the MiSeq, the machine reads into the adapter and returns the index sequence TCTTTCC.
Question
What will the index sequence be when the HiSeq reads it?
The more fundamental question is: How exactly do MiSeq and HiSeq machines read index sequences?
side note
Here is what an index p5 and unindexed p5 molecule look like: | {
"domain": "bioinformatics.stackexchange",
"id": 754,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ngs, phylogenetics",
"url": null
} |
machine-learning, dataset, machine-learning-model
Title: Understanding features vs labels in a dataset I am in the process of splitting a dataset into a train and test dataset. Before I start, this is all relatively new to me. So, from my understanding, a label is the output, and a feature is an input. My model will detect malware, and so my dataset is filled with malware executables and non-malware executables (which I think is known as benign?).
I have started some code that splits the dataset, although I want to clarify the difference between labels and features. So my dataset is pretty large and contains many rows and many columns. I am dropping the 'Malware' column from my dataset. I have done this by using the code below:
y = data.Malware
X = data.drop('Malware', axis=1)
which I believe is the label in my code as that is what I what my model to predict (malware or not malware). My features are all the other columns within the dataset. Would this be correct?
The link to the dataset is below for reference in case anyone needs it to help understand my question:
https://1drv.ms/x/s!AqFNg8FC48SSgtZSObDmmGHs3utWog The features are the input you want to use to make a prediction, the label is the data you want to predict. The Malware column in your dataset seems to be a binary column indicating whether the observation belongs to something that is or isn't Malware, so if this is what you want to predict your approach is correct. | {
"domain": "datascience.stackexchange",
"id": 9216,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "machine-learning, dataset, machine-learning-model",
"url": null
} |
deep-neural-networks, comparison, architecture
Title: Are there any learning algorithms as powerful as "deep" architectures? This article suggests that deep learning is not designed to produce the universal algorithm and cannot be used to create such a complex systems.
First of all it requires huge amounts of computing power, time and effort to train the algorithm the right way and adding extra layers doesn't really help to solve complex problems which cannot be easily predicted.
Secondly some tasks are extremely difficult or impossible to solve using DNN, like solving a math equations, predicting pseudo-random lists, fluid mechanics, guessing encryption algorithms, or decompiling unknown formats, because there is no simple mapping between input and output.
So I'm asking, are there any alternative learning algorithms as powerful as deep architectures for general purpose problem solving? Which can solve more variety of problems, than "deep" architectures cannot? Have you read the book The Master Algorithm: by Pedro Domingos?
He discusses the present day machine learning algorithms... Their strengths, weaknesses and applications...
Deep Neural Network
Genetic Algorithm
Bayesian Network
Support Vector Machine
Inverse Deduction | {
"domain": "ai.stackexchange",
"id": 37,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "deep-neural-networks, comparison, architecture",
"url": null
} |
quantum-mechanics, electromagnetism, operators, gauge-theory, gauge
In all of the derivations I found the authors use: $\mathbf{A}\cdot\mathbf{p}=\mathbf{p}\cdot\mathbf{A}$. Is there some reason for which $[A_i,p_i]=0$ for all $i$, or is it just the extension of the Coulomb gauge (i.e. $\nabla\cdot\mathbf{A}=0$) to the QM case? Could it be that this is an approximation in the spirit of the dipole approximation?
There're some references to the "radiation gauge" in multiple sources. According to my understanding this is just the Coulomb gauge with the addition of $\phi=0$. Is it a different gauge altogether, or is it just the Coulomb gauge with the additional requirement of no charge distribution. This question can actually be phrased in a more general way: Is it possible to gauge out $\phi$ without use of Lorenz gauge? The Coulomb gauge and the radiation gauge are essentially the same thing. The radiation gauge is generally open to having a nonzero scalar potential $\phi$, but this is restricted only to the electrostatic fields of any particles present: in the typical case you will have a bunch of charged particles (like, say, electrons and nuclei in a molecule) interacting with each other through their usual electrostatic interactions (plus any relativistic effects you need to bring in), which are then subjected to an external radiation field. Working in the radiation gauge means that this external radiation field is described exclusively via a divergence-free vector potential.
The vector potential $\mathbf A(\mathbf r,t)$ and the momentum $\mathbf p$ commute, in their inner product, if and only if the vector potential is in this gauge - or, more specifically, if and only if it obeys $\nabla \!\cdot\! \mathbf A(\mathbf r,t)=0$. To see this, you just calculate:
\begin{align}
\mathbf A(\mathbf r,t)\cdot\mathbf p -\mathbf p\cdot\mathbf A(\mathbf r,t) | {
"domain": "physics.stackexchange",
"id": 33747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "quantum-mechanics, electromagnetism, operators, gauge-theory, gauge",
"url": null
} |
density-matrix, linear-algebra, cq-states, trace-distance
Suppose $X$ is a random bit string of length $n$ such that the first bit $x_1$ is chosen uniformly at random and then $x_2, \dots, x_n$ are all $0$. Now the min-entropy is $- \log \max_{(x_1,\dots,x_n)} p(x_1,\dots, x_n) = 1$. Using, for example, Lemma 1 from [1] there is a hashing procedure such that we can extract 1 bit (i.e. $F(X)$ is a single bit) and
$$
\frac12 \| F(X) - U_1\|_1 \leq 1/2
$$
where $U_k$ denotes a uniformly distributed random variable over $k$ bits.
But now we can calculate
$$
\begin{aligned}
\frac12 \| X - U_n\|_1 &= \frac12\sum_{(x_1,\dots, x_n) \in \{0,1\}^n} |p(x_1,\dots,x_n) - 2^{-n}| \\
&= \frac12\left(2 |\frac12 - 2^{-n}| + 2(2^{n-1} - 1)|2^{-n}| \right) \\
&= 1 - 2^{1-n}.
\end{aligned}
$$
Thus as $n\rightarrow \infty$ we get $\frac12 \| X - U_n\|_1 \rightarrow 1$ but it can always be hashed down to a single bit that is distance $1/2$ away from uniform. By considering larger uniform sequences at the beginning of $X$ you should be able to make this distance grow even further, i.e. the hashed tends to perfectly uniform but the non-hashed is almost perfectly distinguishable. | {
"domain": "quantumcomputing.stackexchange",
"id": 2090,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "density-matrix, linear-algebra, cq-states, trace-distance",
"url": null
} |
cc.complexity-theory, graph-theory
In summary, if $G$ has a dominating set of size $k$, then $G'$ has a dominating set of size at most $k + |E|$, and if $G'$ has a dominating set of size $k + |E|$, then $G$ has a dominating set of size at most $k$.
Edit: Added an illustration. Top: the original graph $G$; middle: graph $G'$ with a "normalised" dominating set; bottom: graph $G'$ with an arbitrary dominating set. | {
"domain": "cstheory.stackexchange",
"id": 312,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "cc.complexity-theory, graph-theory",
"url": null
} |
special-relativity, fluid-dynamics, resource-recommendations
Many approaches to evolving fluids deal with the equations in flux-conservative form. Here, the conserved variables are
\begin{align}
D & = \gamma\rho && \text{(lab-frame density),} \\
M & = Dh\gamma v && \text{(relativistic momentum),} \\
E & = Dh\gamma - p && \text{(relativistic energy).}
\end{align}
Here I define
\begin{align}
\gamma & = \frac{1}{\sqrt{1-v^2}} && \text{(standard Lorentz factor),} \\
h & = 1 + \frac{\Gamma}{\Gamma-1} \left(\frac{p}{\rho}\right) && \text{(enthalpy),}
\end{align}
where the ratio of specific heats $\Gamma$ is assumed to be constant. These are often combined as $\vec{U} = (D, M, E)^\mathrm{T}$.
Along with the vector of conserved quantities, we can define the vector of fluxes
$$ \vec{F} =
\begin{pmatrix}
Dv \\ Mv + p \\ M
\end{pmatrix}. $$
Then we have the relation
$$ \partial_t \vec{U} + \partial_x \vec{F} = 0, $$
which is used as the basis for most Riemann solvers and many fluid codes in general. Essentially, you want to solve the Riemann problem for the conservative system of RHD. For a general equation of state this is pretty tricky. For a general equation of state there are two real methods of doing this, both are described in An upwind numerical scheme for relatavistic hydrodynamics with a general equation of state.
This is one of many papers which I studied in great depth when creating some of my own schemes for General Relativistic Magnetohydrodynamics. S. S. Komissarov is a leading guy in this area (and was my Ph.D. supervisor) so I would check out some of his other works on numerical schemes for relativistic fluids. | {
"domain": "physics.stackexchange",
"id": 10233,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "special-relativity, fluid-dynamics, resource-recommendations",
"url": null
} |
homework-and-exercises, particle-physics, energy-conservation, mass-energy
The total energy-momentum in the lab frame, stationary target, is (measuring momenta along direction of motion),
$$
(E +m, p), \implies W^2= ((E + m)^2 - p^2).
$$
This is invariant: the same in all frames, and most notably in the center of momentum frame of all products. In that frame, hugely significant, you correctly inferred the energy/momentum of the reaction written (beam? what are you up to?) is
$$
(4 m, 0), \implies W^2= 16 m^2.
$$
Equating the two, then, yields, given the initial $E^2=m^2+p^2$,
$$
E^2 + 2Em + m^2 -(E^2-m^2) -16 m^2 =0,
$$
solved to yield $E=7m$.
What is the problem? Remember, E is not a relativistic invariant, but W is. Initially, you are in the lab frame, but, finally, you are in the center of momentum frame. | {
"domain": "physics.stackexchange",
"id": 67608,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework-and-exercises, particle-physics, energy-conservation, mass-energy",
"url": null
} |
slam, navigation
Title: rgbdslam error: gsl/gsl_linalg.h not found
when i run the command roslaunch rgbdslam rgbdslam.launch
it shows the error:
ERROR: cannot launch node of type [rgbdslam/rgbdslam]: Cannot locate node of type [rgbdslam] in package [rgbdslam]
And when run the command "rosmake --rosdep-install rgbdslam" ,showing the error:
In file included from /home/lihaiyang/ros/rgbdslam/external/gicp/bfgs_funcs.cpp:37:0:
/home/lihaiyang/ros/rgbdslam/external/gicp/optimize.h:44:28: fatal error: gsl/gsl_linalg.h:not have the file or directory
Compiler interrupt
make[3]: *** [CMakeFiles/gicp.dir/external/gicp/bfgs_funcs.o] error 1
make[3]:leaving the directory /home/lihaiyang/ros/rgbdslam/build' make[2]: *** [CMakeFiles/gicp.dir/all] error 2 make[2]:leaving the directory /home/lihaiyang/ros/rgbdslam/build'
make[1]: *** [all] error 2
make[1]:leaving the directory `/home/lihaiyang/ros/rgbdslam/build'
Thank you very much!!!
Originally posted by Ocean on ROS Answers with karma: 66 on 2012-04-25
Post score: 0
Original comments
Comment by Steven Bellens on 2012-04-25:
Please specify ROS version and platform details. The gsl_linalg.h header is included in the gsl-dev package
Comment by Ocean on 2012-05-07:
ROS version is electric,Linux for Ubuntu11.10
http://answers.ros.org/question/12911/rgdbslam-installation-missing-gslgsl_linalgh | {
"domain": "robotics.stackexchange",
"id": 9135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "slam, navigation",
"url": null
} |
order x² ⁵! Squared to eliminate the roots, 4th roots, 4th roots, 5th roots we... To both the top of the expression as circles, triangles, trapezoids, boxes, cylinders, cones pyramids. Happy with the following is 1. a 0 = 1 could be among the most Important career decisions you make. Solve this Powers Class 8 Maths with Answers were prepared based on the latest pattern. Xa/Xb ] a-b * [ xb/xc ] b-c * [ xc/xa ] c-a also have cube,... We need to apply a square root, we applied the formula am+n = am.an writing. Learning resources to compliment our website content perfectly from top universities: ©. Most popular … practice evaluating Powers of ten online courses from top universities: Copyright © MBA Ball...: Problem 1 laws for multiplication and division with BBC Bitesize KS3 Maths trouble! This kind of expression also means that the denominator should be rationalized laws of indices tell us papers! To write and use many multiplications and { b, c } and c! * 1/âx the conjugate of 5+3â2 and vice versa formulae used to solve Questions on roots are: 22 4! Reception brings the core concepts of mastery to your Questions general, any number a, ( x² ) can... View all Products, Not sure what you 're looking for squared eliminate. The latest exam pattern hence we are left with a simple calculation of, 4... | {
"domain": "mindwink.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9511422241476943,
"lm_q1q2_score": 0.8453360155732369,
"lm_q2_score": 0.888758793492457,
"openwebmath_perplexity": 2291.824743193545,
"openwebmath_score": 0.6109035611152649,
"tags": null,
"url": "https://mindwink.com/morris-college-zxzz/power-questions-maths-0f51b3"
} |
sql, sql-server, stackexchange
Consistency
DECLARE @username as NVarchar(60) = RTRIM(LTRIM(##DisplayName:string? ##));
DECLARE @userId as int = ##UserId:int?-1##;
DECLARE @limit as int = ##Limit:int?100##;
Would be better as:
DECLARE @userName AS NVARCHAR(60) = RTRIM(LTRIM(##DisplayName:string? ##));
DECLARE @userId AS INT = ##UserId:int?-1##;
DECLARE @limit AS INT = ##Limit:int?100##;
Aliases
I think your aliases mostly obfuscate the query. It's also recommended to explicitly state the type of join, e.g.:
FROM Posts AS posts
INNER JOIN Users AS users ON p.OwnerUserId = u.Id
INNER JOIN Posts AS questions ON p.ParentId = q.Id
Trim
Your left and right trim operations don't really achieve anything. Do you expect a user name to have a bunch of white space before or after it? I'm not sure SE would even allow that. I removed them and got identical results.
Everything combined:
DECLARE @username AS NVARCHAR(60) = ##DisplayName:string? ##;
DECLARE @userId AS INT = ##UserId:int?-1##;
DECLARE @limit AS INT = ##Limit:int?100##;
SELECT TOP 100
users.Id AS [User Link],
posts.Id AS [Post Link],
posts.CreationDate
FROM Posts AS posts
INNER JOIN Users AS users ON posts.OwnerUserId = users.Id
INNER JOIN Posts AS questions ON posts.ParentId = questions.Id
WHERE
(@username = '' OR users.DisplayName = @username)
AND (@userId = -1 OR users.Id = @userId)
AND posts.Score = 0
AND posts.Id = questions.AcceptedAnswerId
ORDER BY posts.CreationDate DESC | {
"domain": "codereview.stackexchange",
"id": 11782,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql, sql-server, stackexchange",
"url": null
} |
ruby, adventure-game
# Behind-the-scenes stuff -- neither maker-editable nor -viewable
# Only in here so that it's in the same place as everything else about the game
location_changed: false,
}
#Since we need something to start the game, aside from a blank screen
LOCATIONS[GAME_PROPS[:location]][:on_enter].call(GAME_PROPS)
until GAME_PROPS[:dead]
print '>' # Inspired by Zork, like everything else
command = gets.chomp
# A state variable to keep track of whether or not we should keep executing handlers.
# This way, (for example) the universal handler can force the player to die, and an
# item can't keep him alive despite that.
continue_execution = true
# We haven't moved yet this turn (since the turn just started)
GAME_PROPS[:location_changed] = false
# The universal command listener is the highest priority, so it gets executed first
continue_execution = GAME_PROPS[:on_command].call(command, GAME_PROPS) unless GAME_PROPS[:on_command].nil?
# Execute the current room's listener if...
continue_execution = LOCATIONS[GAME_PROPS[:location]][:on_command].call(command, GAME_PROPS) if
# execution of more listeners wasn't canceled by the ones before AND the room has a listener to execute
continue_execution && !LOCATIONS[GAME_PROPS[:location]][:on_command].nil?
# Then, if the room and universal don't mind, execute each item's command listener (in order)
GAME_PROPS[:inventory].each do |item|
# We stop caring about continue_execution because the order of the items is arbitrary (though predictable)
# so it's up to the gamemaker to make sure they don't clash.
# Item listeners are executed last so that an item can revive the player
item[:on_command].call(command, GAME_PROPS) unless item[:on_command].nil?
end if continue_execution | {
"domain": "codereview.stackexchange",
"id": 13911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ruby, adventure-game",
"url": null
} |
algorithms, approximation, greedy-algorithms
Title: Optimal solution for Weighted points problem Problem:
Fix a constant $k$. Given a set of $2d$-dimensional points $N = \{N_1, N_2, N_3, \dots, N_n\}$, each associated with an arbitrary weight, find a set of points $X = \{X_1, X_2, X_3, \dots, X_k\} \subseteq N$ such that the pairwise distance between any two points in $X$ is at least $D$, and $\sum_{i=1}^k \mathit{Weight}(X_i)$ is maximized.
It would be nice if I could get the exponential solution and then an efficient heuristic so that I can relate to why and how the problem reduces.
The greedy way to do it would be to sort the points by weight and exclude points which are at distance $D$ from the current point that is being processed. Is there a better way to do it? This problem is a variation of the Maximal Independent Set (MIS) problem in graph theory. To understand that you need to convert your point set $N$ into a graph $G=(N,E)$, where any two vertices $N_1,N_2 \in N$ are connected by an edge if and only if the distance between $N_1$ and $N_2$ is less than the threshold $D$. So the set $X$ you are looking for will be one of independent sets in the graph $G$. However your case is different, because here:
Each vertex in $G$ has a numerical weight, and you are trying to maximize the total weight of the independent set instead of its size - this problem is called Maximal Weighted Independent Set (MWIS) problem.
You are looking for an optimal independent set with exactly $k$ vertices. | {
"domain": "cs.stackexchange",
"id": 14853,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithms, approximation, greedy-algorithms",
"url": null
} |
javascript, html, hash-map, react.js, jsx
weatherData.validTime.length - 4
);
if (TIMES_TO_SHOW.indexOf(time) === -1) return null;
return (
<p key={"weather-data-" + _index}>
{time}
</p>
);
})}
</td>
<td className="values">
{weather[weatherDate].map((weatherTime, index_) => {
const time = weatherTime.validTime.slice(
weatherTime.validTime.indexOf("T") + 1,
weatherTime.validTime.length - 4
);
if (TIMES_TO_SHOW.indexOf(time) === -1) return null;
return (
<React.Fragment key={index_}>
Temperature: {weatherTime.parameters.t.values}°
Windspeed: {weatherTime.parameters.ws.values} m/s
Gusts: {weatherTime.parameters.gust.values} m/s
Vind direction: {weatherTime.parameters.wd.values}°
</React.Fragment>
);
})}
</td>
</tr>
</React.Fragment>
) : null;
})}
</tbody>
</table> | {
"domain": "codereview.stackexchange",
"id": 42454,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, hash-map, react.js, jsx",
"url": null
} |
filters, transfer-function, fixed-point
Title: Calculate the Gain of a fixed-point filter As the title already says, I would like to know how to calculate the Gain and Phase of a given fixed-point filter at a given frequency.
What I've achieved so far:
Let's say for example that I have a filter with the following difference equation, which corresponds to a Direct Form I biquad structure:
$$
y[k] = b_0 \cdot x[k] + b_1 \cdot x[k-1] + b_2 \cdot x[k-2] + a_1 \cdot y[k-1] + a_2 \cdot y[k-2]
$$
From this difference equation, I can set up the transfer function in the z-Domain, which is:
$$
H(z) = \frac{b_1 \cdot z^2 + b_2 \cdot z + b_3}{z^2 - a_1 \cdot z - a_2}
$$
To turn this back into frequency-domain, I will simply substitute $z$ with $e^{2 \cdot \pi \cdot \frac{f}{f_s}}$, which will give me $H(f)$.
Finally, I can calculate my filter gain by evaluating my function $H(f)$ at the frequency $f$ of interest (assuming the sampling frequency $f_s$ and all coefficients $a_x,b_x$ are known).
The filter gain $G(f)$ is then:
$$
G(f) = \sqrt{Re(H(f))^2 + Im(H(f))^2}
$$
And the phase $\varphi(f)$ of the filter is:
$$
\varphi(f) = atan2(Im(H(f)), Re(H(f)))
$$
If multiple stages are cascaded together, then
$$
G_{tot} = G_1(f) \cdot G_2(f) \cdot ...
$$
and
$$
\varphi_{tot} = \varphi_1(f) + \varphi_2(f) + ...
$$ | {
"domain": "dsp.stackexchange",
"id": 11089,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "filters, transfer-function, fixed-point",
"url": null
} |
Therefore $$k=5$$
Please check my solution, Is it correct?, Thank you
• $a_n=2\cos\frac{\pi}{2^{n+1}}$. – Riemann Dec 18 '19 at 8:06
You have given a lower & upper bound for $$a_n$$. With this, you've determined a possible value for $$k$$, but you haven't shown it's necessarily the smallest such value of $$k$$.
Instead, note that $$a_{n+1} = \sqrt{2 + a_n}$$. Thus, you have
\begin{aligned} \frac{3-a_{n+1}}{7-a_n} & = \frac{3-\sqrt{2 + a_n}}{7-a_n} \\ & = \frac{(3-\sqrt{2 + a_n})(3 + \sqrt{2 + a_n})}{(7-a_n)(3 + \sqrt{2 + a_n})} \\ & = \frac{9-(2 + a_n)}{(7-a_n)(3 + \sqrt{2 + a_n})} \\ & = \frac{7 - a_n}{(7-a_n)(3 + \sqrt{2 + a_n})} \\ & = \frac{1}{3 + \sqrt{2 + a_n}} \end{aligned}\tag{1}\label{eq1A} | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.977022630759019,
"lm_q1q2_score": 0.8589462922559571,
"lm_q2_score": 0.8791467722591728,
"openwebmath_perplexity": 255.4639680597133,
"openwebmath_score": 0.9999126195907593,
"tags": null,
"url": "https://math.stackexchange.com/questions/3480467/find-the-smallest-positive-number-k"
} |
asymptotics, big-o-notation
Title: How does $Θ(\log(n!))=Θ(\log(n^n)$? How does $Θ(\log(n!))=Θ(\log(n^n)$?
I understand why $Θ(\log(n!))=Θ(n\log(n))$ and $Θ(\log(n^n))=Θ(n\log(n))$, therefore $Θ(\log(n!))=Θ(\log(n^n)$. But I am having trouble reconciling this with the following:
$$\lim_{x\to \infty}\left(\frac{\log_2(x^x)}{\log_2(x!)}\right)=\infty. $$
So how could there be constants such that $Θ(\log(n!))=Θ(\log(n^n))$?
Where has my understanding gone wrong? As a matter of fact,
$$\lim_{x\to \infty}\frac{\log_2(x^x)}{\log_2(x!)}=1.$$
So there is no problem to reconcile.
Looking at the first revision of the question, it seems to me that you are confused about the fact that $\frac{n^n}{n!}$ has different behaviour from $\frac{\log n^n}{\log n!}$:
$$\lim_{n\to+\infty}\frac{n^n}{n!}=+\infty,\qquad\text{while}\qquad\lim_{n\to+\infty}\frac{\log(n^n)}{\log(n!)}=1<+\infty.$$
There is no problem with this. Unboundedness of ratios of functions is not preserved by applying arbitrary functions such as $\log$, because $\exp$ (the inverse of $\log$) is not polynomially bounded. For a simpler example, | {
"domain": "cs.stackexchange",
"id": 18884,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "asymptotics, big-o-notation",
"url": null
} |
Paul Erdős liked to talk about The Book, in which God maintains the perfect proofs for mathematical theorems, following the dictum of G. H. Hardy that there is no permanent place for ugly mathematics.
JOEL SPENCER: “Paul talks about The Book. The Book has all the theorems of mathematics. Theorems can be proven in a lot of different ways, but in The Book there is only one proof and it is the one that is the clearest proof, the one that gives the most insight, the most aesthetic proof. It’s what he calls The Book proof. And sometimes when there’s a problem and somebody solves it and the proof is not so beautiful, then he’ll say, “Well okay, but let’s look for The Book proof; let’s try to find The Book proof.” And this is the sense of mathematics, that…that The Book is there, the theorems have an existence of their own. And what we’re doing is we’re just trying to uncover. We’re trying to read the pages of The Book. We don’t create mathematics. What we do is we read the pages of The Book. We discover the pages of The Book. So when he goes from university to university, and he talks about problems, and he asks everybody to try to solve these problems, it doesn’t matter who solves the problem. It really doesn’t matter to him, because all of us are in the same venture. We’re all just trying to uncover the pages. And sometimes we succeed. Sometimes we find these beautiful theorems.”
View the video of Joel Spencer describing The Book here.
Proofs from THE BOOK is an effort by Martin Aigner and Günter Ziegler to reveal an approximation to a portion of The Book | {
"domain": "wordpress.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9893474888461862,
"lm_q1q2_score": 0.8018452685268236,
"lm_q2_score": 0.8104789040926008,
"openwebmath_perplexity": 422.660230283421,
"openwebmath_score": 0.8390799164772034,
"tags": null,
"url": "https://luisrguzmanjr.wordpress.com/tag/gunter-ziegler/"
} |
qiskit, programming, quantum-gate
~\anaconda3\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
887 result = self._slow_forward(*input, **kwargs)
888 else:
--> 889 result = self.forward(*input, **kwargs)
890 for hook in itertools.chain(
891 _global_forward_hooks.values(),
<ipython-input-6-f66b87fe8d6c> in forward(self, input)
42
43 def forward(self, input):
---> 44 return HybridFunction.apply(input, self.quantum_circuit, self.shift)
<ipython-input-6-f66b87fe8d6c> in forward(ctx, input, quantum_circuit, shift)
8 ctx.quantum_circuit = quantum_circuit
9
---> 10 expectation_z = ctx.quantum_circuit.run(input[0].tolist())
11 result = torch.tensor([expectation_z])
12 ctx.save_for_backward(input, result)
<ipython-input-4-39b4287471c5> in run(self, thetas)
30 result = job.result().get_counts()
31
---> 32 counts = np.array(list(result.values()))
33 print('counts', counts)
34 print('result.values', result.values())
AttributeError: 'list' object has no attribute 'values' | {
"domain": "quantumcomputing.stackexchange",
"id": 4151,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "qiskit, programming, quantum-gate",
"url": null
} |
complexity-theory, turing-machines
Title: Is the leapfrog automata problem in P?
My question is whether a specific decision problem—finding a computation path through a "leapfrog automaton"—is in P or not. It's straightforwardly in NP, and it resembles the hamiltonian path problem in some respects, but it also seems a little easier and I haven't been able to find a reduction.
Definition. A leapfrog automaton is a special kind of machine. A leapfrog automaton consists of a finite number of registers each of which contains a nonempty word from $\Sigma^*$. There is also a special start register containing the empty word. At any given point, exactly one of the registers is marked as active; initially, it is the special start register.
Like a DFA or NFA, a leapfrog automaton can consume words, accepting or rejecting them. Given a word $w$, if the word is empty, the automaton accepts. Otherwise, the automaton consumes the next symbol $\alpha$ in the word: if there is a register other than the active register whose word contains $\alpha$, the automaton nondeterministically picks one such register and sets it to active. It also nondeterministically picks one instance of the symbol $\alpha$ in the register and marks it as "visited". On the other hand, if none of the other registers have $\alpha$ in their word, the automaton rejects the word $w$.
Path problems. If a leapfrog automaton $M$ accepts a word $w$, we can examine all of the symbols that were marked as visited in all the registers during the computation. Suppose the machine maintains a record of which symbols in which registers were visited, in which order; this is called a computation path.
The Blackout Decision Problem is: "Given a leapfrog automaton $M$ and a word $w$, is there an accepting computation path for $w$ which visits every symbol in every register at least once?" (Alternatively: exactly once?) | {
"domain": "cs.stackexchange",
"id": 16563,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "complexity-theory, turing-machines",
"url": null
} |
control-engineering, transfer-function
Let me try to clarify that ;)
Let $P_s = \frac{1}{(s+15)(s+20)}$ denote the second order part you do understand. I don't know what you mean by type 2 system, but this can represent any mass-spring-damper system as you already stated.
Where you go wrong is that you view the integrator $I = \frac{1}{s}$ as a controller. You recognized that $P = IP_s$, which is true. A controller, however, would introduce (negative) feedback, which is not present here.
Controller interpretation - wrong!
Let $Y$ denote the Fourier transform of the output of your plant and $E$ that of the error. (Without loss of generality we set the reference $R=0$).
Then: $$Y = P E = P(R-Y),$$ from which we can derive the well-known expression for the complementary sensitivity: $$T = \frac{Y}{R} = \frac{P}{1+P}.$$ (In literature, often $L$ is used instead to denote the open-loop transfer function $CP$, where $C$ is the controller, but let's keep using your notation instead.)
$T = \frac{1}{s^3 + 25s^2 + 150s+1}$, is the real transfer function of your second order system with your integrator as negative feedback controller from input $R$ to output $Y$. Note that this system indeed has no steady state error as you correctly noted.
Correct interpretation
Back to your system and the correct interpretation: the integrator is nothing more than a ''multiplier'' as you stated. A physical interpreation could be a valve controlling a water flow into a vat on an old-fashioned mechanical scale. | {
"domain": "engineering.stackexchange",
"id": 2209,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "control-engineering, transfer-function",
"url": null
} |
Just as an alternative solution to the qbert answer.
Note that $$|x|$$, $$|y|$$ are not strictly less than $$r$$, but instead $$|x| \leq r$$, $$|y| \leq r$$. This can still insure that $$r^2 \geq y^2$$ and so $$\sqrt{r^2-y^2}$$ is real.
After the first integral
$$\int_{-r}^r\int_{-\sqrt{r^2-y^2}}^{\sqrt{r^2-y^2}}\mathrm dx\mathrm dy= \int_{-r}^r2\sqrt{r^2-y^2}\mathrm dy$$
Instead of the change of variable, you can remember the known integral:
$$\int \sqrt{r^2 - y^2} = \frac{1}{2} \left( r^2 \arcsin \frac{y}{r} + y \sqrt{r^2 - y^2} \right) + C$$
whose condition $$|y| \leq |r|$$ has just been mentioned and it is satisfied. The result follows almost immediately:
$$\int_{-r}^r 2 \sqrt{r^2 - y^2} \mathrm{d} y = \left[ r^2 \arcsin \frac{y}{r} + y \sqrt{r^2 - y^2} \ \right]_{-r}^r = r^2 \arcsin (1) - r^2 \arcsin (-1) = \\ = r^2 \frac{\pi}{2} + r^2 \frac{\pi}{2} = \pi r^2$$
So, using the cartesian coordinates, the only important observation is simply to consider the right extreme values for each variable. | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.976669234586964,
"lm_q1q2_score": 0.8432480194288275,
"lm_q2_score": 0.8633916064586998,
"openwebmath_perplexity": 150.753538043128,
"openwebmath_score": 0.9771931171417236,
"tags": null,
"url": "https://math.stackexchange.com/questions/1863305/area-of-circle-double-integral-and-cartesian-coordinates"
} |
Equality of complex numbers Consider two complex numbers z1 = a+ib, z2 = x+iy Two complex numbers are said to be equal, if their corresponding real parts and imaginary parts are equal. z1 = z2, if a = x and b = y Ex: Find the values of x and y, if the complex numbers 3x+(2x+y)i, 9+7i are equal. Sol: 3x+(2x+y)i = 9+7i Real parts are equal ⇒ 3x = 9 ∴ x = 3 Imaginary parts are equal ⇒ 2x+y = 7 Putting, x = 3 (2x3)+y = 7 ∴ y = 1 | {
"domain": "nextgurukul.in",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9919380101400316,
"lm_q1q2_score": 0.8350388613559071,
"lm_q2_score": 0.8418256512199033,
"openwebmath_perplexity": 325.04847399196285,
"openwebmath_score": 0.8407259583473206,
"tags": null,
"url": "https://www.nextgurukul.in/wiki/concept/cbse/class-11/maths/complex-numbers-and-quadratic-equations/introduction-to-complex-numbers/3960926"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.