text stringlengths 49 10.4k | source dict |
|---|---|
lab-techniques, photosynthesis, chromatography
At the beginning, both cars (solutes) S1 and S2 are even with the solute front car (SF) because the race (chromatography) has just begun. However, over time, the SF car outpaces S1 and S2 because it is moving faster.
_______
/____/SF\___
|_,._____,._)
---`'-----`'--
_______
/____/S1\___
|_,._____,._)
---`'-----`'--
_______
/____/S2\___
|_,._____,._)
---`'-----`'--
And at the end, you get great separation:
_______
/____/SF\___
|_,._____,._)
---`'-----`'--
_______
/____/S1\___
|_,._____,._)
---`'-----`'--
_______
/____/S2\___
|_,._____,._)
---`'-----`'--
(Thanks to retrojunkies.com for the ASCII car) | {
"domain": "biology.stackexchange",
"id": 3790,
"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": "lab-techniques, photosynthesis, chromatography",
"url": null
} |
Now, consider a discrete random variable $X$ with $n$ possible values $x_1$, $x_2$,...,$x_n$. In Equation 6.4, we can choose $\alpha_i=P(X=x_i)=P_X(x_i)$. Then, the left-hand side of 6.4 becomes $g(EX)$ and the right-hand side becomes $E[g(X)]$ (by LOTUS). So we can prove the Jensen's inequality in this case. Using limiting arguments, this result can be extended to other types of random variables.
Jensen's Inequality:
If $g(x)$ is a convex function on $R_X$, and $E[g(X)]$ and $g(E[X])$ are finite, then \begin{align}%\label{} E[g(X)] \geq g(E[X]). \end{align}
To use Jensen's inequality, we need to determine if a function $g$ is convex. A useful method is the second derivative.
A twice-differentiable function $g: I \rightarrow \mathbb{R}$ is convex if and only if $g''(x) \geq 0$ for all $x \in I$.
For example, if $g(x)=x^2$, then $g''(x) =2 \geq 0$, thus $g(x)=x^2$ is convex over $\mathbb{R}$.
Example
Let $X$ be a positive random variable. Compare $E[X^a]$ with $(E[X])^{a}$ for all values of $a\in \mathbb{R}$.
• Solution
• First note $E[X^a]=1=(E[X])^{a},$ $\textrm{ if }a=0$, $E[X^a]=EX=(E[X])^{a},$ $\textrm{ if }a=1.$ | {
"domain": "probabilitycourse.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9933071496700977,
"lm_q1q2_score": 0.8121025770060928,
"lm_q2_score": 0.8175744806385542,
"openwebmath_perplexity": 177.1992641456026,
"openwebmath_score": 0.9936075210571289,
"tags": null,
"url": "https://www.probabilitycourse.com/chapter6/6_2_5_jensen's_inequality.php"
} |
roslaunch
Any suggestions? Thanks.
Originally posted by Orhan on ROS Answers with karma: 856 on 2016-04-27
Post score: 0
Original comments
Comment by mgruhler on 2016-04-27:
It works for me in both hydro and indigo. Could you check your code that you are not doing something wrong while retrieving the parameter?
Comment by naveedhd on 2016-04-27:
kindly also post the line from your source file where you are loading this param.
Comment by Orhan on 2016-04-27:
My roslaunch's version is 1.11.19 in indigo. And there is only 3 lines: double INC; and ros::param::get("parameter_analyzer/increment", INC); and ROS_INFO("INCREMENT VALUE: %lf", INC);
Comment by naveedhd on 2016-04-27:
By using ros::param::get() I am also recieving 0 (very small value in exponent). Using:
ros::NodeHandle n("~"); double increment; n.param<double>("increment", increment, 5.0);
you can receive negative values.
Comment by Orhan on 2016-04-27:
Thanks! I'm trying, Please write as answer to let me marking correct answer.
Alright, so the problem is most probably in this line of your code.
You use dynamic_reconfigure for your parameters, and you limit the increment param to the range [0.0, 500].
Thus, setting to positive should work, but not to negative. However, I'm not quite sure how dynamic_reconfigure reacts to parameters being not properly set from the outside...
Originally posted by mgruhler with karma: 12390 on 2016-04-27
This answer was ACCEPTED on the original site
Post score: 3 | {
"domain": "robotics.stackexchange",
"id": 24486,
"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": "roslaunch",
"url": null
} |
# Solve Sudoku Puzzles Via Integer Programming: Problem-Based
This example shows how to solve a Sudoku puzzle using binary integer programming. For the solver-based approach, see Solve Sudoku Puzzles Via Integer Programming: Solver-Based.
You probably have seen Sudoku puzzles. A puzzle is to fill a 9-by-9 grid with integers from 1 through 9 so that each integer appears only once in each row, column, and major 3-by-3 square. The grid is partially populated with clues, and your task is to fill in the rest of the grid.
### Initial Puzzle
Here is a data matrix B of clues. The first row, B(1,2,2), means row 1, column 2 has a clue 2. The second row, B(1,5,3), means row 1, column 5 has a clue 3. Here is the entire matrix B.
B = [1,2,2;
1,5,3;
1,8,4;
2,1,6;
2,9,3;
3,3,4;
3,7,5;
4,4,8;
4,6,6;
5,1,8;
5,5,1;
5,9,6;
6,4,7;
6,6,5;
7,3,7;
7,7,6;
8,1,4;
8,9,8;
9,2,3;
9,5,4;
9,8,2];
drawSudoku(B) % For the listing of this program, see the end of this example.
This puzzle, and an alternative MATLAB® solution technique, was featured in Cleve's Corner in 2009.
There are many approaches to solving Sudoku puzzles manually, as well as many programmatic approaches. This example shows a straightforward approach using binary integer programming.
This approach is particularly simple because you do not give a solution algorithm. Just express the rules of Sudoku, express the clues as constraints on the solution, and then MATLAB produces the solution.
### Binary Integer Programming Approach | {
"domain": "mathworks.com",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9865717484165853,
"lm_q1q2_score": 0.8424461958408871,
"lm_q2_score": 0.8539127510928476,
"openwebmath_perplexity": 1335.9852386783166,
"openwebmath_score": 0.8208943605422974,
"tags": null,
"url": "https://in.mathworks.com/help/optim/ug/sudoku-puzzles-problem-based.html"
} |
navigation, move-base
where ac is of type: actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>
The error I am getting is this:
In file included from
/usr/include/boost/bind.hpp:22:0,
from /opt/ros/hydro/include/ros/publisher.h:35,
from /opt/ros/hydro/include/ros/node_handle.h:32,
from /opt/ros/hydro/include/ros/ros.h:45,
from /home/nick/mqp_ws/src/mqp/hulk/include/hulk/Behavior.h:5,
from /home/nick/mqp_ws/src/mqp/hulk/include/hulk/GoToBehavior.h:5,
from /home/nick/mqp_ws/src/mqp/hulk/src/GoToBehavior.cpp:1:
/usr/include/boost/bind/bind.hpp: In
member function ‘void
boost::_bi::list3<A1, A2,
A3>::operator()(boost::_bi::type,
F&, A&, int) [with F =
boost::mfi::mf2<void, GoToBehavior,
const
actionlib::SimpleClientGoalState&,
const boost::shared_ptr<const
move_base_msgs::MoveBaseActionResultstd::allocator<void | {
"domain": "robotics.stackexchange",
"id": 20766,
"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": "navigation, move-base",
"url": null
} |
kalman-filter, gyroscope, accelerometer, noise
The rest of the values are zero. This is done under the assumption that there is no covariance between the different variables of the state. However, this is not always true and should be considered for accurate modeling.
2) The initial value for uncertainty was set based on information on the system and some trail and error.
3) The matrix $R$ was calculated in a method similar to that of $Q$. However, in this case, $noise\_ax, noise\_ay, noise\_az$ were calculated after converting sensor reading to angles (I don't quite remember how this value was obtained for yaw. Will update after checking notes). So, these values were squared and set as diagonal elements of $R$.
So, as a general approach:
1) Take sample data (in large quatity) from the sensor.
2) Calculate std. deviation before or after manipulating the data to bring it to the same space or physical dimensions of the state variables or observation variables, depending on convenience and the implementation.
3) Square the std. deviation values or multiply them to generate variance or covariance depending on assumptions regarding the independence of variables involved. | {
"domain": "robotics.stackexchange",
"id": 1898,
"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": "kalman-filter, gyroscope, accelerometer, noise",
"url": null
} |
c, random, generator
Title: Random password generator in C This is a simple password generator. What do you think about it? I am learning C for a while at school and at home. This just has a mix of symbols, lowercase, uppercase and numbers, with a configurable length.
#include <stdio.h>
#include <stdlib.h>
#include <time.h> | {
"domain": "codereview.stackexchange",
"id": 36779,
"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, random, generator",
"url": null
} |
sequence-alignment, minimap2
Title: Why are Minimap2 alignments different with CIGAR generation flag? I am using Minimap2 (v2.26-r1175) in Linux to generate a sequence alignment between the Streptomyces coelicolor A3(2) chromosome (ref.fa) and the Mycobacterium tuberculosis chromosome (query.fa). My desired output is a PAF (Pairwise mApping Format) file.
The general way to align reference and query sequences with Minimap2 is the following:
minimap2 ref.fa query.fa > approx_mapping.paf
# OR equivalently...
minimap2 -k15 -w10 ref.fa query.fa > approx_mapping.paf
You can get Minimap2 to generate custom CIGAR tags (cg:) in the PAF by adding the -c flag:
minimap2 -c ref.fa query.fa > approx_mapping_cigar.paf
# OR equivalently...
minimap2 -c -k15 -w10 ref.fa query.fa > approx_mapping_cigar.paf
Moving to an R environment [with the intention of downstream data visualization], you can quickly assess the number of observations in each object (a.k.a. rows in each dataframe) with dim():
file1 <- "approx_mapping.paf"
paf_basic <- read.table(file1, sep = "\t", fill = TRUE,
col.names = paste0("V",seq_len(max(count.fields(file1, sep = "\t")))))
dim(paf_basic)
[1] 205 18
file2 <- "approx_mapping_cigar.paf"
paf_cigar <- read.table(file2, sep = "\t", fill = TRUE,
col.names = paste0("V",seq_len(max(count.fields(file2, sep = "\t")))))
dim(paf_cigar)
[1] 200 24 | {
"domain": "bioinformatics.stackexchange",
"id": 2629,
"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": "sequence-alignment, minimap2",
"url": null
} |
geology, teaching
Title: Book recommendation for 7 year old By some poorly understood series of events, I have managed to convince my 7 year old daughter that she wants to be a geologist when she's older. Of course I'm aware that this likely won't be the case, but I thought I'd try to seize on the moment and get her a book on geology.
So I am looking for any recommendations for a children's book on geology, perhaps with facts/experiments about stuff that she can find in the garden/in her local area. We live in a reasonably urban part of the world (Surrey). There are at least 2 books that come to mind:
National Geographic Readers: Rocks and Minerals (2012), a richly illustrated guide for kids.
Ultimate Explorer Field Guide: Rocks and Minerals (2016) by Nancy Honovich, a guide focussed on getting kids outside, looking at rocks in their backyards and on the camping.
Considering you're in the UK, afterwards I'd start with some experiments about limestone. National Geographic used to have rock kits for kids, not sure who else sells them near you. With the keywords "rock kit kids uk" I get some results that may be worth a look at. | {
"domain": "earthscience.stackexchange",
"id": 2097,
"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": "geology, teaching",
"url": null
} |
python, performance, geospatial
I have included a screenshot of running the above code in the Python Console of QGIS. I believe the result is what I was wanting from the code as it matches the same sql expression I wrote manually which is stored in a text file (instead of hardcoding the names of layers and reading the textfile, I wanted a more dynamic approach). Here is the image: | {
"domain": "codereview.stackexchange",
"id": 19940,
"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, geospatial",
"url": null
} |
electric-fields, solid-state-physics, electronic-band-theory
In metals, the fermi level $(E_F)$ passes through the valence band. As $T$ becomes greater than $0$, the electrons just below $E_F$ surpass the level and shift to higher energy states within the band. As there are a lot of unoccupied eigenstates within the band allowing redistribution under an electric field, the valence band is the conduction band for metals.
In semi-metals, $E_F$ passes through the trough of the valence band which has bimodal density of states. So, they need to be at somewhat a higher temperature than metals to be conductive (so that the electrons under $E_F$ can shift to energy levels with greater density of states allowing them to be more conductive). Technically, this bimodal valence band is also the conduction band.
In semi-conductors, $E_F$ lies in the band gap. All states in the band below $E_F$ (the valence band) are filled at $0K$ and the band is not conductive. At higher temperatures, however, the electrons can have enough energy to surpass the band gap and shift to the immediately higher unoccupied band. The electrons in this higher band, now become conductive, and so the band is called the conduction band.
In insulators (e.g., diamond), the $E_F$ passes through a very large band gap. The valence band is filled and non-conductive, and the occupancy of electrons in the band immediately higher than $E_F$, even at higher temperature, is almost null because of the very large band gap that needs to be surpassed. This higher band is what we refer to as conduction band, although no appreciable conduction takes place here. This should be an example to the fact that just as extremely populated bands, extremely non-populated bands are non-conductive too. | {
"domain": "physics.stackexchange",
"id": 83119,
"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": "electric-fields, solid-state-physics, electronic-band-theory",
"url": null
} |
c++, programming-challenge, datetime, time-limit-exceeded, computational-geometry
Therefore,
\$ A(h,m,s) = A(0, m-5h \mod 60, s-5h \mod 60)\$
Thus we can make a neat little precomputed table area[minute][second], filled with 3600 values, and use that! Populating this takes negligible time relative to the programs' libc initialization time, so I did not bother to optimize it further. It is just a bunch of MACs which modern cpus crunch at insane speed anyway.
Additionally, a per-minute max area is computed and stored in array marea. This corresponds to the max over h=0, m, s=[0..59] and it can be extended to any h:m by rotating as explained above.
Counting
The rest is very simple, We start, say at 00:01:02 and end at 00:35:15.
First we increment the seconds from 02 to 59 until we get to 00:02:00
Then we increment the minutes, until we reach 00:35:00
Then we increment the seconds again until we reach the final time.
At each step we pick the area from the precomputed table (or the per-minute precomputed max) and compare it to our running maximum.
It's pretty fast since it does basically nothing except a few int ops, a float cmp, and there should be a few CMOVs if the compiler does its job. No trig at all...
This ugly piece of code should thus do the deed...
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <iomanip>
#define pi 3.14159265358979323846
using namespace std; | {
"domain": "codereview.stackexchange",
"id": 28514,
"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++, programming-challenge, datetime, time-limit-exceeded, computational-geometry",
"url": null
} |
Allahdadi. How to use for Loop and if statement to Learn more about loop, for loop. Use this formula to find a few Pythagorean triples that you have not yet seen in this investigation. Also assumethat gcd(a,b,c) = 1. Study Math Pythagorean Triples Flashcards at ProProfs - list of the pythagorean triples. The set of three integer values for the sides of a right triangle is called a Pythagorean Triple. It is very useful in times of examination. the nearest tenth of a centimeter on the triangle. You should explain what do you mean when you say that a Pythagorean triple (that is, some triple of real natural numbers a,b,c satisfying a^2+b^2=c^2) is less than a given (single) number? We know what is the meaning of some real number a is less. Triple Trouble. So here's a handy reference list for use in math class when creating problems for tests or classwork. D J de Solla Price, The Babylonian "Pythagorean triangle" tablet, Centaurus 10 (1964 / 1965), 1-13. The name is derived from the Pythagorean theorem, stating that every right triangle has side lengths satisfying the formula a 2 + b 2 = c 2; thus, Pythagorean triples describe the three integer side lengths of a right triangle. 2; Three Euclidean Metrics 69 2. A General Formula for Pythagorean Triples We will see how the following formula is derived in the Rational Points on the Unit Circle section, but for now we will work with this. All triples are a multiple of some primitive triple. Article Here is a more complete list up to 10,000 [with thanks to Tom Wallett] (2. Euclid developed a formula for generating Pythagorean triples given any integers m and n with m. )The Baudhayana Sulba Sutra, the dates of which are given variously as between the 8th century BC and the 2nd century BC, in India, contains a list of Pythagorean triples discovered algebraically, a statement of the Pythagorean theorem, and a geometrical proof of the Pythagorean theorem for an isosceles right triangle. | {
"domain": "cinziacioni.it",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9879462215484651,
"lm_q1q2_score": 0.8167467953706744,
"lm_q2_score": 0.8267117962054048,
"openwebmath_perplexity": 457.99876169456724,
"openwebmath_score": 0.49576327204704285,
"tags": null,
"url": "http://puvh.cinziacioni.it/pythagorean-triple-list.html"
} |
standard-model, group-theory, quantum-chromodynamics, isospin-symmetry
As $t^a$s are generators of transformations, trace and product are linear operations, therefore the quantity $\mathcal{A}$ is related to the linear combination of the basis of the representation in question.
Edit
However, I understand that the above rules for angular momentum are applied when direct-product of physical states is involved, namely, $3 \otimes 3= 1\oplus 3\oplus 5$ as discussed in Mike's answer. For the present case, if the same arguments are employed to derive the properties of the l.h.s. of (19.132), an invariant (relate to the base of a scalar representation), from the l.h.s. of the relation, why the latter only involves "normal" matrix product instead of direct product.
Also, as explained in Mike's answer, invariant tensors are simply Clebsh-Gordan coefficients. Therefore, (19.132) can be viewed as a relation between different C-G coefficients. So does that mean the r.h.s. of (19.132) is vanishing since the correponding C-G coefficient is vanishing, which does not involve what stays on the r.h.s. of (19.132)?
I probably have missed something very basic, thanks a lot for pointing out my misunderstanding. Invariant tensors are just a form of Clebsh-Gordan coefficients.
In partiular, if there was a symmetric invariant tensor ${\mathcal A}_{ijk}$ with indices in adjoint (the vector rep of ${\rm SO}(2)$ then for any two vectors $u_i$, $v_i$ the quantity $w_k={\mathcal A}_{ijk}u_iv_i$ would be a vector. We would therefore have found a new (symmetric) way to make a vector out of two vectors that differs from the usual
(antisymmetric) vector product. We know this is impossible because we know that the 3 (i.e the spin $j=1$) in $3 \otimes 3= 1\oplus 3\oplus 5$ is antisymmetric. | {
"domain": "physics.stackexchange",
"id": 58677,
"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": "standard-model, group-theory, quantum-chromodynamics, isospin-symmetry",
"url": null
} |
orbit, tidal-forces
However, this is a very large system in reality, and the Earth also has quite a strong gravitational force felt on the surface anyway. So when it comes to accurately measuring gravity or doing experiments that rely on gravity, how big of a factor is this centrifugal force? Does the apearant force of gravity fluctuate from 9.9 m/s^2 to 9.7 or is it more along the lines of 9.800001 to 9.799999 (assuming the average is exactly 9.8, which is a simplification). Or is there something I'm missing that means the force is non-existent? That the Earth and Moon orbit about their center of mass from the perspective of an inertial frame of reference is a bit irrelevant. One thing that is quite relevant is that gravitational force is undetectable by a local measuring device. For example, people standing still on the surface of the Earth do not feel gravity. They instead feel the normal force pushing them up, away from the center of the Earth. The gravitational force on astronauts in the International Space Station is about 90% of what they experience on the Earth's surface, but they feel none of that.
Another relevant factor is that the Earth as a whole, along with objects on the surface of the Earth, accelerate toward the Moon (and the Sun, and Jupiter, and Venus, and ...) gravitationally. The gravitational acceleration of those surface-bound objects toward those other bodies is not exactly the same as is that of the Earth as a whole.
The difference between these accelerations results in a force that can be measured. This is the tidal acceleration. An extremely sensitive scale will show that you weigh slightly more when the Moon is on the horizon than when it is directly overhead. For a 61 kg person, this difference in weight between the Moon being on the horizon vs directly overhead is about 10-4 newtons.
Compared to the ~600 newton weight of that 61 kg person, this is a very small effect. This very small effect, along with an even smaller effect from the Sun (roughly half), are however responsible for the tides in the oceans. | {
"domain": "astronomy.stackexchange",
"id": 5714,
"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": "orbit, tidal-forces",
"url": null
} |
ros-kinetic
Title: [solved]jsk_boundingBOXARRAY can't publish
my source code is this
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/PointStamped.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <jsk_recognition_msgs/BoundingBoxArray.h>
#include <pharos_msgs/object_custom_msg.h>
#include <pharos_msgs/object_custom_msgs.h>
///전역변수///
///------////
class velodyne_
{
public:
ros::NodeHandlePtr nh;
ros::NodeHandlePtr pnh;
velodyne_()
{
nh = ros::NodeHandlePtr(new ros::NodeHandle(""));
pnh = ros::NodeHandlePtr(new ros::NodeHandle("~"));
///서브스크라이브는 this 사용 publish는 메세지형식 이것만 잘 생각해놓기
sub_custom_msg = nh->subscribe("pharos_object_msg", 10 , &velodyne_::BOX_CB,this);
pub_box_msg = nh->advertise<jsk_recognition_msgs::BoundingBoxArray>("object_box",10);
} | {
"domain": "robotics.stackexchange",
"id": 31576,
"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-kinetic",
"url": null
} |
Using heap sort or merge sort, this can be done in Θ(mlgm) time. The pseudocode listed below is for the unbounded knapsack. 99), “Fast Food” ($2. Greedy Algorithm solves problems by making the best choice that seems best at the particular moment. Introduction to Greedy Algorithms (Section 13. It features improved treatment of dynamic programming and greedy algorithms and a new notion of edge-based flow in the material on flow networks. Greedy Algorithm and Dynamic Programming I am going to cover 2 fundamental algorithm design principles: greedy algorithms and Below is an O(n x W) dynamic programming pseudocode solution:. Greedy algorithms use problem solving methods based on actions to see if there’s a better long term strategy. A Pseudocode provides an intermediate step. It is used for the lossless compression of data. , its frequency) to build up an optimal way of representing each character as a binary string. STEPS IN PROBLEM SOLVING •First produce a general algorithm (one can use pseudocode) •Refine the algorithm successively to get step by step detailed algorithm that is very close to a computer language. Find the local optimal solution at each step, instead of considering the entire sequence of steps. When we evaluate the complexity of the binary search algorithm, 4:55. In fractional knapsack, you can cut a fraction of object and put in a bag but in 0-1 knapsack either you take it completely or you don't take it. com Free Programming Books Disclaimer This is an uno cial free book created for educational purposes and is not a liated with o cial Algorithms group(s) or company(s). To solve a problem based on the greedy approach, there are two stages. Algorithms are described in English and in a pseudocode designed to be readable by anyone who has done a little programming. • The first version of the Dijkstra's algorithm (traditionally given in textbooks) returns not the actual path, but a number - the shortest distance between u and v. It is a greedy algorithm in graph theory as it finds a minimum spanning tree for a connected weighted graph adding increasing cost arcs at each step. This branch is now useless. Implementation of these tree based algorithms in R and Python. Huffman code was proposed by David A. Implementing Huffman coding algorithm. 2) Developing a Greedy Algorithm (Section 13. Algorithm (below) provides the pseudocode the Greedy Randomized | {
"domain": "puntoopera.it",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9744347860767304,
"lm_q1q2_score": 0.8011696831464599,
"lm_q2_score": 0.822189123986562,
"openwebmath_perplexity": 806.7616996057025,
"openwebmath_score": 0.5701478719711304,
"tags": null,
"url": "http://puntoopera.it/rsls/greedy-algorithm-pseudocode.html"
} |
strings, swift, unicode
return output
}
Usage:
let input = "Is my résumé good enough?"
let expectedResult = "is-my-r-sum-good-enough-"
print(anchor(input)) //prints is-my-r-sum-good-enough-
print(anchor(input) == expectedResult ? "" : "") //prints We should always be thinking about how to write our code in a generic way. Otherwise, what happens if we want something very similar to what we've just written, but slightly different in some minor way? Well, it usually results in a lot of copy & pasting. Let's write some code that will allow us to apply the rules you want to apply, but in a more generic way.
I want to start with a skeleton that looks something like this:
struct StringFormatter {
enum CaseRule {
case None, UppercaseOnly, ConvertToUpper, LowercaseOnly, ConvertToLower
}
enum AsciiRule {
case None, AsciiOnly
}
var blacklistCharacters = Set<Character>()
var replacementCharacter = ""
var caseRule = CaseRule.None
var asciiRule = AsciiRule.None
func stringByApplyingFormatting(toString string: String) -> String {
// TODO: Implement actual formatting logic
return ""
}
}
Now we've got a reusable structure for applying this sort of formatting to our strings. Importantly, despite there being no logic in it yet, we have implemented the method we'd be calling to apply the formatting, so we can stick with test-driven development and go ahead and write our unit test.
class StringTestStuff: XCTestCase {
func testStringFormatting() {
let input = "Is my résumé good enough?"
let expectedResult = "is-my-r-sum-good-enough-" | {
"domain": "codereview.stackexchange",
"id": 18593,
"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": "strings, swift, unicode",
"url": null
} |
ros, rosjava-core
Title: simple installation problem in rosjava_core
Sorry I'm totally new to use ROS. I have had a java agent (program) which was used to control satellites and now I want to use it into ROS.
I have read some documents and think it should be okay for the running concept of the ROS. After that, I've passed all tutorials of ROS but when I try to install rosjava_core, I meet some problems. I don't know why I can't install it. When I follow the "rosws update", it just tell me:
[rosjava_core] Installing https://code.google.com/p/rosjava (default) to /home/wildfire/Robtic_java_workspace/rosjava_core
WARNING [vcstools] Command failed: 'hg --version'
errcode: 127:
/bin/sh: hg: not found
[/vcstools]
Exception caught during install: Error processing 'rosjava_core' : Unable to create vcs client of type hg for /home/wildfire/Robtic_java_workspace/rosjava_core: "Could not determine whether hg is installed 'hg --version returned 127, maybe hg is not installed'"
ERROR: Error processing 'rosjava_core' : Unable to create vcs client of type hg for /home/wildfire/Robtic_java_workspace/rosjava_core: "Could not determine whether hg is installed 'hg --version returned 127, maybe hg is not installed'"
Anyone can tell me what's this problem?
Originally posted by wildfire on ROS Answers with karma: 33 on 2012-06-20
Post score: 0
Same answer as here
Originally posted by phil0stine with karma: 682 on 2012-06-20
This answer was ACCEPTED on the original site
Post score: 1 | {
"domain": "robotics.stackexchange",
"id": 9873,
"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, rosjava-core",
"url": null
} |
the-moon
Title: Proportion of Lunar Fraction in a Year I grabbed a year of lunar fraction data from the USNO and binned the counts to find the shape of the curve as below
My understanding of lunar fraction was that 0.5 does not distinguish between the direction as it is a cycle from 0 (new moon) to 1 (full moon) then back to 0 (new moon). And therefore I assumed that 0.5 would have more counts than 0 or 1 like this
I trust the data and counts plot to be true but I cannot see what I am misunderstanding that would lead to this shape. Can anyone more knowledgeable than myself see my misunderstanding and/or explain the lunar fraction to me better? Think how the terminator (the line between the light and dark) moves on the moon.
Thinking of the moon as a 3d ball, you know that the terminator must move around the moon at a constant rate. But we see a projection of the moon; we see the moon as a disc. So the terminator doesn't seem to move constantly. It appears to move most quickly at half moon and slowest at new moon and at full moon.
At full moon, the terminator is right at the extreme edge of the lunar disc, so it seems to move very slowly. At half moon, it is in the middle of the disc, and so seems to move quickly.
See
how the meridians are closer together near the edge of the moon.
As the terminator seems to move quickly at half-moon, the lunar fraction is between 0.45 and 0.55 for less time than it is between 0.9 and 1 (for example)
In your diagram imagine tracing the curve, but moving most quickly through the middle, but slowly when turning the curve. You'll spend more time in the red, and least time in the green, resulting in the graph you get. | {
"domain": "astronomy.stackexchange",
"id": 7182,
"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",
"url": null
} |
qiskit, programming
Title: Qiskit histogram to Seaborn I am running certain circuits in the Aer simulators and I need to present them nicely. I prefer to use the options provided by Seaborn. How can I transfer my Aer data, e.g. histograms, to Seaborn?
For example, running the simple circuit:
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
meas.measure(range(3), range(3))
circ.add_register(meas.cregs[0])
qc = circ.compose(meas)
qc.draw()
and using Aer
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
yields:
However, I prefer to use the stylistic options of Seaborn instead in order to make nice plots. The counts variable in your code example is just a dictionary with bit strings for keys and the count of times that bit string was returned from the execution of the circuit. Something like: {"000": 513, "111": 467}. If you want to make your own plot with seaborn you can just access the data from the Counts object directly. For example, something like:
import matplotlib.pyplot as plt
import seaborn
counts = {"000": 513, "111": 467}
seaborn.barplot(list(counts.keys()), list(counts.values()))
yields:
That being said plot_histogram function does have some style arguments including for color: https://qiskit.org/documentation/stubs/qiskit.visualization.plot_histogram.html that may enable you to get the output visualization you want from the function. | {
"domain": "quantumcomputing.stackexchange",
"id": 3695,
"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",
"url": null
} |
programming, simulation, bloch-sphere
Title: Efficient Representation of Qubits on a Digital Simulator I was wondering about quantum simulators recently, and I was thinking about how a qubit could be represented on a digital machine. This Stack Overflow post seems to say that one will need at least $a2^n$ bits to represent a qubit (albeit partially), where $n$ is the number of qubits represented, and $a$ is the bit size of the complex number used. This has to do with the matrix representation of a qubit. However, I was thinking of a more efficient way of representing a qubit as a point on a Bloch Sphere. This way, a qubit object would only need to store two units of information. For example, in C, this would look like:
#include <stdlib.h>
#include <math.h>
#define QUBIT_PI (1 << sizeof(short) * 8 - 1)
typedef struct QUBIT_STRUCT
{
unsigned short theta;
unsigned short phi;
} qubit_t;
qubit_t *qubit_from_angles(double theta, double phi)
{
qubit_t *ret = malloc(sizeof(struct QUBIT_STRUCT));
qubit_t->theta = theta / M_PI * QUBIT_PI;
qubit_t->phi = phi / M_PI * QUBIT_PI;
return ret;
}
and a quantum gate would be like:
qubit_t *qubit_X(qubit_t *qubit)
{
qubit->theta = QUBIT_PI - qubit->theta;
qubit->phi = -qubit->phi;
return qubit;
} | {
"domain": "quantumcomputing.stackexchange",
"id": 3613,
"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": "programming, simulation, bloch-sphere",
"url": null
} |
quantum-operation, optimization
$$
\operatorname{Tr}_{Y}(J(N_{X\rightarrow Y})) = \mathbb{1}_X.
$$
For any real-valued linear function of $N_{X\rightarrow Y}$, there will always exist a Hermitian operator $H$ for which the value of this linear function is given by
$$
\operatorname{Tr}(H J(N_{X\rightarrow Y})).
$$
The resulting semidefinite program looks like this:
$$
\begin{align}
\text{maximize} \quad & \operatorname{Tr}(H P) \\[1mm]
\text{subject to} \quad & \operatorname{Tr}_{Y}(P) = \mathbb{1}_X\\[1mm]
& P \in \mathrm{Pos}(Y\otimes X),
\end{align}
$$
where $\mathrm{Pos}(Y\otimes X)$ refers to the set of all positive semidefinite operators acting on $X\otimes Y$.
Like all semidefinite programs, this one has a dual formulation, which is as follows:
$$
\begin{align}
\text{minimize} \quad & \operatorname{Tr}(Q)\\[1mm]
\text{subject to} \quad & \mathbb{1}_Y \otimes Q - H \in \mathrm{Pos}(Y\otimes X)\\[1mm]
& Q \in \mathrm{Herm}(X),
\end{align}
$$
where $\mathrm{Herm}(X)$ is the set of all Hermitian operators acting on $X$.
If you have a specific choice of $H$ in mind, you can solve this optimization problem numerically. I recommend CVX for MATLAB for this purpose. | {
"domain": "quantumcomputing.stackexchange",
"id": 1223,
"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-operation, optimization",
"url": null
} |
rust
Use Cow
This is a bit of an advanced optimization that you don't need to do—the Book doesn't even mention it once.
Currently, you allocate a new String even when the output is identical to the input. Instead, return Cow<str>: if the first character isn't a letter, you can return Cow::Borrowed(s), which points to the existing &str. If it does start with a letter, return Cow::Owned(format!(...)), which has the same overhead as it did before. Here, I'm using .into() instead of writing Cow::Owned and Cow::Borrowed explicitly. You can do either.
fn translate_word(s: &str) -> Cow<str> {
let mut it = s.chars();
let first = it.next().unwrap();
match first.to_ascii_lowercase() {
'a' | 'e' | 'i' | 'o' | 'u' => format!("{}-hay", s).into(),
'a'..='z' => format!("{}-{}ay", it.as_str(), first).into(),
_ => s.into(),
}
}
Final code
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=78daca7b7adab4587436cacf35bca90e | {
"domain": "codereview.stackexchange",
"id": 40274,
"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
} |
nuclear-physics
Title: What if electrons were used in gold foil experiment? I was studying Rutherford's gold foil experiment from my high school textbook. It states that ' by performing experiments in which fast electrons instead of alpha particles are projectiles that bombard target made up of various elements the sizes of nuclei of various elements have been accurately measured.' I am totally confused with this statement. I know that original experiment used the fact that distance of closest approach for the alpha particles was used to infer the size of nucleus. But how electrons can lead to more accurate results? What I would think and what I have found from other sources is something like this.... If electrons were used then they due to their size and charge they would have got easily affected by the electrons of the atom that come in their way. In fact due to the fact that alpha particles are positively charged and have significant mass they could overcome the interactions with the electrons.
Then what the author intends to say. Or what is wrong with my thought process? Someone please explain. This link and links therein should help:
The scattering of electrons from nuclei has given us the most precise information about nuclear size and charge distribution. The electron is a better nuclear probe than the alpha particles of Rutherford scattering because it is a point particle and can penetrate the nucleus.
.....
For low energies and under conditions where the electron does not penetrate the nucleus, the electron scattering can be described by the Rutherford formula.
...
As the energy of the electrons is raised enough to make them an effective nuclear probe, a number of other effects become significant, and the scattering behavior diverges from the Rutherford formula. The probing electrons are relativistic, they produce significant nuclear recoil, and they interact via their magnetic moment as well as by their charge. When the magnetic moment and recoil are taken into account, the expression is called the Mott cross section
It is that energetic electrons are used as the probe for the nucleus. The probability for the electron to scatter off the electrons of the atoms is small, and gets smaller as the energy gets higher. The orbitals are mostly empty space for a high energy electron. | {
"domain": "physics.stackexchange",
"id": 55410,
"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": "nuclear-physics",
"url": null
} |
ros, navigation, rviz, robot-model
Title: How to use navigation stack in simulation using .dae and rviz
To use and learn navigation stack,
I'd like to simulate 2D navigation
(path planning and collision avoidance)
using a robot model(e.g. PR2.dae) and rviz.
Are there any tutorials for that?
What are good practices for learning how to use navigation stack?
ros.org/wiki/pr2_simulator gave me some tutorials
but it uses Gazebo.
If possible, I'd like to use only rviz to make the simulation simple.
Thanks in advance.
Originally posted by moyashi on ROS Answers with karma: 721 on 2012-06-05
Post score: 0
RViz is not a simulator, but a visualization tool. That means whether you run in simulation or on the real robot, you can use RViz just the same. If you want to try 2D navigation, you either need a simulator or a real robot in addition to RViz.
If you want something simpler than Gazebo, you might want to use stage. There is a package that shows how to use the navigation stack in stage here.
Originally posted by Martin Günther with karma: 11816 on 2012-06-05
This answer was ACCEPTED on the original site
Post score: 3 | {
"domain": "robotics.stackexchange",
"id": 9686,
"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, navigation, rviz, robot-model",
"url": null
} |
acid-base, equilibrium, solubility, solutions
Above the figure it says: "distribution of the different species in a solution using $1800\,\mathrm{cc}$ of DI water, $100\,\mathrm{cc}$ of $49\%$ w/w HF and $0$ to $200\,\mathrm{cc}$ of $28\%$ w/w $\ce{NH4OH}$."
Here are the results I get for $10\,\mathrm{cc}$, $40\,\mathrm{cc}$ and $90\,\mathrm{cc}$:
$$
\begin{array}{c|cccc}
\hline
\text{Volume (cc)} & \ce{HF} & \ce{H2F2} & \ce{F-} & \ce{HF2-} \\
\hline
10 & 43\% & 48\% & 3\% & 6\% \\
40 & 35\% & 33\% & 14\% & 18\% \\
90 & 21\% & 12\% & 37\% & 30\% \\
\hline
\end{array}
$$
To calculate the fractions, I'm summing $\ce{HF}$, $\ce{H2F2}$, $\ce{F-}$ and $\ce{HF2-}$ to get the total and then I divide each of them by the total (both concentration and moles should both be valid).
I was wondering if anyone might have an idea of what I might be doing wrong. Or if the graph in the paper might possibly have an error or if there's some other numeric error in the paper.
Originally, I thought something was wrong with MATLAB's solution but I've checked that so many times by now, in more than just the two ways I show down below, that I really feel that that's not the issue. I've been at this problem for a month now, and about a week into it (3 weeks ago) I asked for help with the MATLAB side of things (see post on SO of original problem; I had some friends help out in the end). Honestly I just really want to know what the problem/mistake is.
The Equations | {
"domain": "chemistry.stackexchange",
"id": 10391,
"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": "acid-base, equilibrium, solubility, solutions",
"url": null
} |
$du/dx = 1/2x^{-1/2} = 1/2u^{-1}$, or equivalently $2u du = dx$, then you get $\int \frac{2+u}{u^2+1}2u du = \int \frac{4u+2u^2}{u^2+1} du$ and then split into two integrals (why are we allowed to do this?):
$$2\int \frac{u^2}{u^2+1}du + 2\int \frac{2u}{1+u^2}du$$
$$u=\sqrt{x}$$ $$x=u^2$$ $$dx=2udu$$ $$\int \frac{2+u}{1+u^2}2udu=\int \frac{4u+2u^2}{1+u^2}du$$ $$\int (\frac{4u}{1+u^2}+\frac{2u^2}{1+u^2})du$$ $$\int (\frac{4u}{1+u^2}+2-\frac{1}{1+u^2})du$$ $$\int (\frac{4u}{1+u^2}+2-\frac{1}{1+u^2})du=2\log(1+u^2)+2u-\tan^{-1}u+C$$ $$=2\log(1+x)+2\sqrt{x}-\tan^{-1}\sqrt{x}+C$$ | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.987758724167664,
"lm_q1q2_score": 0.8165917827484096,
"lm_q2_score": 0.8267117898012104,
"openwebmath_perplexity": 316.5266430394896,
"openwebmath_score": 0.9410854578018188,
"tags": null,
"url": "https://math.stackexchange.com/questions/1191365/how-to-solve-int-frac2-sqrtxx1dx-given-the-substitution-sqrtx"
} |
electricity, everyday-life
Title: Electric swatter working when it is off When I switch on a fly swatter for some time, then turn it off and touch it with a conductive material(such as a pencil), I get a momentary spark. The spark is not continuous that I get when the device is on.
Why is causing the spark? Is some charge getting stored in it? Yes. A fly swatter often charges a capacitor to store the charge for the spark; this capacitor might only leak off slowly when the fly swatter is off. You can still discharge this capacitor yourself by inducing the spark. Then, note the capacitor does not recharge because the fly swatter is off. | {
"domain": "physics.stackexchange",
"id": 75814,
"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": "electricity, everyday-life",
"url": null
} |
Author Message
TAGS:
### Hide Tags
Manager
Joined: 26 Apr 2010
Posts: 122
Concentration: Strategy, Entrepreneurship
Schools: Fuqua '14 (M)
Followers: 2
Kudos [?]: 129 [0], given: 54
$686,000 in bonus money is to be divided among 6 employees. No employe [#permalink] ### Show Tags 26 Nov 2010, 13:52 3 This post was BOOKMARKED 00:00 Difficulty: 55% (hard) Question Stats: 67% (02:54) correct 33% (02:25) wrong based on 199 sessions ### HideShow timer Statistics Source: Knewton$686,000 in bonus money is to be divided among 6 employees. No employee is to receive a bonus more than 20% greater than the bonus received by any other employee. What is the minimum possible bonus that an employee can receive?
(A) $96,000 (B)$97,000
(C) $98,000 (D)$99,000
(E) $100,000 [Reveal] Spoiler: OA _________________ I appreciate the kudos if you find this post helpful! +1 Manager Joined: 02 Apr 2010 Posts: 103 Followers: 5 Kudos [?]: 120 [0], given: 18 Re:$686,000 in bonus money is to be divided among 6 employees. No employe [#permalink]
### Show Tags
26 Nov 2010, 14:03
The question stem states that the difference between the minimum and maximum bonus may not exceed 20%. To determine the minimum possible bonus for an employee you have to assume that the other 5 employees obtain the maximum possible bonus.
If x denotes the minimum possible bonus and 1.2x denotes the maximum possible bonus you can set up the equation as follows: | {
"domain": "gmatclub.com",
"id": null,
"lm_label": "1. Yes\n2. Yes\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 1,
"lm_q1q2_score": 0.84997116805678,
"lm_q2_score": 0.84997116805678,
"openwebmath_perplexity": 2962.7877932937986,
"openwebmath_score": 0.5698367953300476,
"tags": null,
"url": "https://gmatclub.com/forum/686-000-in-bonus-money-is-to-be-divided-among-6-employees-127503.html"
} |
python, programming-challenge, python-3.x, unit-testing, caesar-cipher
EDGES = {pos: c for c, (pos, _) in LAUNCH.items()}
# REFLECT[barrier][incoming_direction] gives the outgoing direction
REFLECT = {
'/': {
DOWN: LEFT,
RIGHT: UP, LEFT: DOWN,
UP: RIGHT,
},
'\\': {
DOWN: RIGHT,
RIGHT: DOWN, LEFT: UP,
UP: LEFT,
},
' ': {
DOWN: DOWN,
RIGHT: RIGHT, LEFT: LEFT,
UP: UP,
},
}
def trace(pos, aim):
pos = (pos[0] + aim[0], pos[1] + aim[1])
while not pos in EDGES:
aim = REFLECT[grid[pos[0]][pos[1]]][aim]
pos = (pos[0] + aim[0], pos[1] + aim[1])
return EDGES[pos]
grid = iter(grid)
grid = [next(grid) for _ in range(13)]
mapping = {ord(c): trace(pos, aim) for c, (pos, aim) in LAUNCH.items()}
assert all(mapping[ord(d)] == chr(c) for c, d in mapping.items())
return str.maketrans(mapping)
if __name__ == '__main__':
# Make a translation table from the a file specified on the command line,
# or from the first 13 lines of stdin if no filename is given.
translation = grid_to_translation(fileinput() if len(argv) > 1 else stdin)
# Then use it to encrypt all subsequent input lines.
for text in stdin:
print(text.translate(translation), end='') The logic is neat and nicely done, there is not much to say. Just a few nitpicks: | {
"domain": "codereview.stackexchange",
"id": 20375,
"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, programming-challenge, python-3.x, unit-testing, caesar-cipher",
"url": null
} |
electromagnetism, electrostatics, electric-current, charge, potential
Title: How does current flow when two charged spheres are connected by a wire?
Here, the blue sphere (positively charged with +Q charge) is at a lower potential and the pink sphere (positively charged with +Q charge) is at a higher potential, even though they are equally positively charged, as the radius of the pink sphere is smaller.
TLDR: the blue sphere is at a lower potential and the pink sphere is at a higher potential
Scenario 1:
After we connect the two spheres by an uncharged conducting wire, current will flow from the pink sphere to the blue sphere until the electric potentials of the blue and pink spheres become equal. After equilibrium is reached, no charge will be found on the conducting wire; the uncharged conducting wire will remain uncharged after equilibrium. The uncharged conducting wire is then easily removed.
Scenario 2:
After we connect the two spheres by an uncharged conducting wire, current flows from higher potential to lower potential. The charges redistribute themselves to achieve an equipotential surface: after equilibrium is reached, the electric potentials of the pink ball, blue ball, and wire are equal. It's more appropriate to view the three objects, the blue ball, the pink ball, and the wire as a singular object after the balls have been connected by the wire. In this scenario, however, the conducting wire also becomes charged after equilibrium, even though it was uncharged initially.
My question:
Which scenario is correct? There will be charges on the wire, because if there were no charges on the wire and positive charges on the balls, then some charges would still want to go in the wire, so it wouldn't be an equilibrium.
But the idea behind this experiment is to consider a wire with infinitly small diameter, so the charge inside the wire can be neglected, because charges confined in a small volume would create a high electrical potential and we wouldn't be in equilibrium.
So it is a good approximation to say that the total charge on both spheres remains $2 \cdot Q$ and the charge on the wire is $0$. Scenario $1$ would hence be a good approximation of this system although it is never really possible to achieve it since wires have a finite diameter. | {
"domain": "physics.stackexchange",
"id": 87742,
"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": "electromagnetism, electrostatics, electric-current, charge, potential",
"url": null
} |
javascript, jquery
Title: Change functions based on jQuery plugin {options} I'm developing my first legitimate jQuery plugin, and I'm trying to keep it very modular. To do this, I'm writing many individual functions, which is fine, but I need a clean way to determine what functions to fire based on the plugin options provided by the user.
Right now, I'm using a .on('click',...) event with a switch statement. That method is ok and I just have a feeling that there is a better, time-tested method of changing what function is fired based on plugin {options}. A better method that is used by professional JavaScript developers and has been proven to work reliably.
Again, I'm trying to be as modular and professional as possible, but I'm self taught, so there's really no one to say if I'm doing it the "right" way, or the "best" way for future maintainability.
JSFiddle
(function($){
$.fn.showDateTime = function(options) {
// variables and settings
var d;
var $button = $(this);
var defaults = {
date: "all"
};
var settings = $.extend({}, defaults, options);
// event handlers
$button.on('click', function(){
d = new Date();
switch(settings.date){
case "all": showDate();
break;
case "date only": showDateOnly();
break;
case "time only": showTimeOnly();
break;
default: showDate();
}
});
// functions
function showDate(){
alert(d.toString());
}
function showDateOnly(){
alert(d.toDateString());
}
function showTimeOnly(){
alert(d.toLocaleTimeString());
}
};
})(jQuery); | {
"domain": "codereview.stackexchange",
"id": 23141,
"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, jquery",
"url": null
} |
demodulation
Title: 16-QAM demodulation I wonder how higher order QAM modulations (like 16-QAM) are demodulated in practice. Let us assume hard detection for simplicity.
For 4-QAM, checking sign of real and imaginary parts is enough, but in my opinion this approach does not scale and using it for higher order modulations would require checking against multiple different thresholds. This simply seems wasteful.
On the other hand, I could not come up with any alternatives except checking a distance between a received symbol and all possible symbols (essentially ML detector). This also does not seem like a good idea, especially in case of large constellations, like 1024-QAM.
Kind regards
For 4-QAM, checking sign of real and imaginary parts is enough, but in my opinion this approach does not scale and using it for higher order modulations would require checking against multiple different thresholds. This simply seems wasteful.
Well, there's hardly a different way to do it! You first decide the sign of the real and imaginary part (and that typically gives you the first two bits: Gray coding!).
Then, you know in which quadrant you are. You add / subtract a complex constant so that the quadrant lies centered.
Then you again decide the real and imaginary part.
Repeat.
Or, you just go through a series of if / else if / else statements.
In a software decider, the iterative approach is "natural", in a hardware decider (i.e. digital logic circuit), the second might be faster, because you can basically do as many comparisons as you want in parallel.
On the other hand, I could not come up with any alternatives except checking a distance between a received symbol and all possible symbols (essentially ML detector). This also does not seem like a good idea, especially in case of large constellations, like 1024-QAM.
Since the ML decision for a rectangular QAM is exactly what you get with threshold decisions, well, that wouldn't be any better.
Let me lose a few words on:
Let us assume hard detection for simplicity.
vs
how higher order QAM modulations are demodulated in practice | {
"domain": "dsp.stackexchange",
"id": 10952,
"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": "demodulation",
"url": null
} |
quantum-operation, kraus-representation
Title: Can any channel be written as $\Phi(X)=\operatorname{Tr}_{\mathcal Z}[U(X\otimes \sigma)U^\dagger]$ for any state $\sigma$? We know that every CPTP map $\Phi:\mathcal X\to\mathcal Y$ can be represented via an isometry $U:\mathcal X\otimes\mathcal Z\to\mathcal Y\otimes\mathcal Z$, as
$$\Phi(X) = \operatorname{Tr}_{\mathcal Z}[U(X\otimes E_{0,0})U^\dagger],\quad\text{where}\quad E_{a,b}\equiv \lvert a\rangle\!\langle b\rvert.\tag1$$
Showing this is quite easy e.g. from the Kraus representation.
If $A_a:\mathcal X\to\mathcal Y$ are Kraus operators for $\Phi$, then
$$U_{\alpha a,i0} \equiv \langle \alpha,a\rvert U\lvert i,0\rangle = \langle \alpha\rvert A_a\lvert i \rangle \equiv (A_a)_{\alpha,0}.\tag2$$
We can, of course, replace $E_{0,0}$ with any pure state in (1) without affecting the result.
This shows that, given any channel $\Phi$ and any pure state $\lvert\psi\rangle\in\mathcal Z$, we can represent $\Phi$ as in (1) (with $E_{0,0}\to\lvert\psi\rangle$).
However, what about the more general case of $E_{0,0}\to\sigma$ with $\sigma$ not pure?
To analyse this case, consider a channel written as
$$\Phi(X)=\operatorname{Tr}_{\mathcal Z}[U(X\otimes \sigma)U^\dagger]\tag3$$ | {
"domain": "quantumcomputing.stackexchange",
"id": 1760,
"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-operation, kraus-representation",
"url": null
} |
first, reaches a minimum, and many more problems in total, on principle. This method is done by starting with the whole array the source sis on fire this that! Nodes during a query is$ { 2n } / { 3 } of. \Log n ) points $m_1$ and $m_2$, i.e sort, it takes (... They maintain BST properties we split the work using the binary search is applied on the topic of binary:. A ]: binary search Tree in C, C++ practical for large a or n. ab+c=ab⋅ac and a2b=ab⋅ab= ab. Match, we get the desired key is compared to the keys in BST if. Should be in the sorted form is retrieved, Java, and website in interval! Helps to have a firm grasp of how that algorithm works on the topic of exponentiation. Is n't sorted, you must sort it using a sorting technique such as sort... Space into half till the match is found find the values of f. … BST is a searching algorithm for finding an element in a sorted list of large size $and m_2! ), and m2, i.e while searching, the algorithm can be stated as foll… binary search a! Search Tree in C, C++ the number of iterations as a fire spreading the... Searched in the worst case half till the match is found or the$... Repeatedly target the center of the original one ( log n ) applying the described procedure to the scenario. Xiaomi Service Centre, Ar Vs Vr Which Is Better, I'll Give You Everything Tik Tok Song, I'll Give You Everything Tik Tok Song, Plastic Bumper Filler Repair Kit, Foundation Armor Sx5000 Vs Sx5000wb, " /> | {
"domain": "crystalholidaystravel.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9643214511730025,
"lm_q1q2_score": 0.8097734841065384,
"lm_q2_score": 0.8397339736884711,
"openwebmath_perplexity": 548.7301588325508,
"openwebmath_score": 0.30998891592025757,
"tags": null,
"url": "https://crystalholidaystravel.com/1761ab/878868-cp-algorithms-binary-search"
} |
Since this is continuous in K, tends to -1 as K goes to infinity, and equals 1 at ${K=0}$, the intermediate value theorem says that there exists some positive real K making the covariance zero.
Rather than arbitrary collections of real-valued variables, we can also consider random variables taking values in ${{\mathbb R}^d}$ for some integer ${d\ge0}$, in which case they are said to be multivariate normal if and only if their components are. For a random variable ${X=(X_1,\ldots,X_d)}$, then linear combinations of its components ${X_k}$ can be expressed in the form ${a\cdot X}$ for ${a\in{\mathbb R}^d}$, giving the following definition.
Definition 5 An ${{\mathbb R}^d}$-valued random variable ${X=(X_1,X_2,\ldots,X_d)}$ is multivariate normal (or, joint normal) if its components ${X_k}$ are joint normal or, equivalently, if ${a\cdot X}$ is normal for all ${a\in{\mathbb R}^d}$.
Multivariate normal distributions can be conveniently characterized by their mean ${\mu={\mathbb E}[X]}$ and covariance matrix ${C={\rm Cov}(X,X)}$. If X is an ${{\mathbb R}^d}$-valued random variable with integrable components, then the mean is a vector in ${{\mathbb R}^d}$ and can be written component-wise as ${\mu_k={\mathbb E}[X_k]}$. If the components are square-integrable, then the covariance matrix can also be defined as a ${d\times d}$ matrix with components given by, | {
"domain": "almostsuremath.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9937100978631075,
"lm_q1q2_score": 0.8192761394010701,
"lm_q2_score": 0.8244619242200081,
"openwebmath_perplexity": 176.82963870131064,
"openwebmath_score": 0.9435343742370605,
"tags": null,
"url": "https://almostsuremath.com/2021/02/24/multivariate-normal-distributions/"
} |
quantum-mechanics, homework-and-exercises, operators, hamiltonian, time-evolution
$$
whose solution is
$$
c(t)= c(0)e^{-i e^{t/w_0}E_0 w_0/\hbar},
$$
so you can ride on that and define $a(t) = \alpha(t) e^{-i e^{t/w_0}E_0 w_0/\hbar}$ and $b(t) = \beta(t) e^{-i e^{t/w_0}E_0 w_0/\hbar}$, for which the Schrödinger equation simplifies to
\begin{align}
i\hbar \dot \alpha(t) & =E_1 \beta(t) , \\
i\hbar \dot \beta(t) & = E_1 \alpha(t) ,
\end{align}
whose solutions are
\begin{align}
\alpha(t) & = \alpha(0) \cos(E_1t/\hbar) -i \beta(0) \sin(E_1t/\hbar)\\
\beta(t) & = -i\alpha(0) \sin(E_1t/\hbar) + \beta(0) \cos(E_1t/\hbar).
\end{align}
Anything beyond that will depend on exactly what you want to do with those solutions. | {
"domain": "physics.stackexchange",
"id": 42888,
"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, operators, hamiltonian, time-evolution",
"url": null
} |
c#, beginner, console
static void Main(string[] args)
{
var stopwatch = new Stopwatch();
int input1;
DateTime starTime;
DateTime endTime;
double duration;
int counter = 0;
while (true)
{
Console.Write("1-Start Timer\n2-Stop Timer\n");
input1 = Convert.ToInt32(Console.ReadLine());
if (input1 == 1)
{
starTime = stopwatch.StartTime();
counter = 1;
}
else
{
throw (new InvalidOperationException("Please Start the timer with 1"));
}
Console.WriteLine("Please enter '2' to stop the timer whenever you want");
input1 = Convert.ToInt32(Console.ReadLine());
if (input1 == 2)
{
endTime = stopwatch.Stoptime();
counter = 0;
}
else
{
throw (new InvalidOperationException("Please end the timer with 2"));
}
if (counter == 1)
{
throw (new InvalidOperationException("stuff"));
}
duration = (endTime - starTime).TotalSeconds;
if (duration > 60.0)
{
duration = (endTime - starTime).TotalMinutes;
Console.WriteLine(duration + "m");
}
else
{
Console.WriteLine(duration + "s");
}
}
}
}
} You have the beginning of a stopwatch representation—you have its data. You still need to add its behavior.
Approach your design of the class as if the class should stand on its own. Input/output will be handled by something else, like the console, but the stopwatch should be the authority on its internal state.
The simplest stopwatch has a start/stop button and a display. We'll interpret "having a display" to mean "a way to get the stored elapsed time".
This means we'll need to provide three methods:
Start: Sets the stopwatch in a running state.
Stop: Sets the stopwatch in an idle state.
TimeElapsed: Reads out the currently elapsed time. | {
"domain": "codereview.stackexchange",
"id": 44805,
"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, console",
"url": null
} |
quantum-field-theory, operators, momentum, hilbert-space
Consider a scalar quantum field theory with underlying spacetime symmetry group being the orthochronous restricted Poincare transformations. A scalar field operator $\phi (x)$ can be generated by the (unitary) translation operator $T(x)= \exp (iP^{\mu}x_{\mu})$ and the operator at some other point (say, the origin):
$$\phi(x)=\exp(iP^{\mu}x_{\mu})\phi(0)\exp (-iP^{\mu}x_{\mu})$$
The generator(s) of space-transformations, $P^{\mu}$, act on single-particle states $|p\rangle$ as follows:
$$P^{\mu}|p\rangle=p^{\mu}|p\rangle$$
My question is, how does the operator $P^{\mu}$ act on multi-particle states? For example, how does the 4-momentum operator act on a two-particle state:
$$P^{\mu}|k_1,k_2\rangle = ?$$
Is a two-particle state simply not an eigenstate of the 4-momentum operator? Or maybe it's an eigenstate when the two are equal? Or maybe we need to define 4-momentum operators that act on different $n$-particle Hilbert spaces ((anti-)symmetrized appropriately)? I think you're overthinking. The total momentum of a state with particles of momentum $k_1$ and $k_2$ is just $k_1 + k_2$, so
$$P^\mu |k_1, k_2 \rangle = (k_1 + k_2)^\mu |k_1, k_2 \rangle.$$
If you wish, you can show this more explicitly by thinking of momentum as the generator of translations; both particles are translated, so you pick up phase factors from both, so the momenta of the two just sum. | {
"domain": "physics.stackexchange",
"id": 86008,
"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, operators, momentum, hilbert-space",
"url": null
} |
hilbert-space, quantum-spin, fermions, second-quantization
instead of in continuous space,
we can define the smeared field operators
\begin{equation}
a_n(f)\equiv \int d^Dx\ f(x)a_n(x)
\hskip2cm
a_n^*(f)\equiv (a_n(f))^*.
\tag{5}
\end{equation}
(Recall the definition (1) of the "integral.") These satisfy
\begin{align*}
a_n(f) a_k^*(g)+a_k^*(g)a_n(f) &= \delta_{nk}\int d^Dx\ g^*(x)f(x)
\tag{6}
\\
a_n(f) a_k(g)+a_k(g)a_n(f) &= 0.
\tag{7}
\end{align*}
If we take the smearing functions $f,g$ to be "smooth" enough
(slowly-varying compared to the lattice spacing $\epsilon$),
then we might as well be working in continuous space.
So far, we have a *-algebra of operators represented on an inner product space,
but nothing has been said about the physical significance of these
operators. In particular, nothing has been said about spin, which is what the question is all about.
Also, nothing has been said yet about time. Let's fix this first.
An example of a Hamiltonian operator $H$ will be given below.
Given such an operator,
we can construct a one-parameter family of
unitary operators $U(t)=\exp(-iHt)$,
and we can define time-dependent versions of the field operators like this:
\begin{equation}
a_n(f,t)\equiv U(-t)a_n(f)U(t).
\tag{8}
\end{equation}
Since this is a unitary transformation, equation (6) implies
\begin{align*} | {
"domain": "physics.stackexchange",
"id": 53439,
"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": "hilbert-space, quantum-spin, fermions, second-quantization",
"url": null
} |
on effect of size. Use our free online app Moment of Inertia of a Disk Calculator to determine all important calculations with parameters and constants. The object in the diagram below consists of five thin cylinders arranged in a circle. Moment of inertia of the system If two identical bodies of known mass are placed symmetrically on the supporting disk at a distance x from the axis of rotation, then the total moment of inertia of the system will be: I I D 2 I E [7] where I D is the moment of inertia of the supporting disk (including the shaft and tightening bolt) and I E. PART 2: Moment of Inertia of apparatus with additional masses. Polar Area Moment of Inertia and Section Modulus. Another thing to note is that moment of inertia is intrinsic to the. Using the Vernier caliper measure the diameter of the second smallest axle and the bow caliper to measure the diameter of the biggest axel precisely. Rotational inertia of the Frisbee A 108 g Frisbee is 28 cm in diameter and has about half its mass spread uniformly in a disk, and the other half concentrated in the rim. Integrating to find the moment of inertia of a two-dimensional object is a little bit trickier, but one shape is commonly done at this level of study—a uniform thin disk about an axis through its center (Figure $$\PageIndex{5}$$). Moment of Inertia - Rotational inertia for uniform objects with various geometrical shapes. The moment of inertia of a hollow circular section of outer diameter D and inner diameter d, as shown in Fig. (9), the final angular. 0625 kgm 2 Example – 6: Calculate the M. Moment of Inertia " Area Moment of Inertia " is a property of shape that is used to predict deflection, bending and stress in beams " Polar Moment of Inertia " as a measure of a beam's ability to resist torsion - which is required to calculate the twist of a beam subjected to torque. Moment of inertia of a disc about an axis which is tangent and parallel to its plane is I. Scaling of Moments of Inertia Learning Goal: To understand the concept of moment of inertia and how it depends on mass, radius, and mass distribution. Experimental Moments 1. 2 words related to moment | {
"domain": "michaelis-bestattungen-muenster.de",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9838471680195556,
"lm_q1q2_score": 0.8111445292838085,
"lm_q2_score": 0.8244619242200082,
"openwebmath_perplexity": 319.556178889402,
"openwebmath_score": 0.637360692024231,
"tags": null,
"url": "http://rbor.michaelis-bestattungen-muenster.de/moment-of-inertia-of-disc-about-diameter.html"
} |
quantum-field-theory, energy-conservation, virtual-particles
Title: Where do "virtual" particles come from? Quantum physics tells us that even a perfect vacuum be populated by "virtual" pairs of subatomic particles. I have read that these particles are allowed to violate the Conservation of Matter and Energy because they do so for such a short amount of time before annihilation that they don't count. I don't buy it.
As we.have established that "Virtual Particles" are "real" (by virtue of the fact that well known processes don't occur with out them) . The question still begs. As no conversion is 100 percent efficient ( a photon is still left in our reality even after annihilation) To preserve the laws of physics, the energy to create them must come from somewhere. *
.Given this, I have two questions:
Have " virtual" pairs ever been observed and/or isolated?
Where do "virtual" particles come from? (As they would have to come from somewhere to satisfy conservation; regardless of how short a time they spend in our universe.)
post is edited and reflects (to clarify what I am asking) information discussed below where Question 1 is answered. Question 2 remains. Virtual particle pairs pop spontaneously out of the vacuum and then recombine and disappear; they exist for too short a time for us to isolate the pair, separate them, and then study them. This means there is no way to "see" them directly.
Despite this, their (indirect) influence on experiments is real. There are well-understood problems in QM which, when solved without taking virtual particle effects into account, yield the wrong answer (i.e., the computed prediction does not match experimental data). Take their effects (called "quantum corrections") into account, and you get the right answer.
How good is the match between theory and experiment when quantum corrections are included? Richard Feynman described the match as like predicting the distance between Los Angeles and New York theoretically and having it match the measured answer to within the thickness of a single sheet of paper.
These things furnish physics guys with a high level of confidence that virtual particles are not just theoretical constructs without physical reality, but things that are part of the real world- specifically, what's called the quantum vacuum.
I invite the experts here to weigh in on this with specific examples of the sort I mentioned above. | {
"domain": "physics.stackexchange",
"id": 51483,
"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, energy-conservation, virtual-particles",
"url": null
} |
php, laravel, laravel-blade
Questions
What would be an optimal way to reduce code repetition in the two controllers?
Are there any code optimisation opportunities?
What would be an optimal way to reduce code repetition in the two controllers?
If those four values from the first settings record and $article_categories are applicable to all views then they could be shared with all views using the View facade's share() method in the boot() method of the App\Providers\AppServiceProvider. Then there may not be a need to have those lines in the constructor of the FrontEndController, and the member variables can be eliminated also.
Otherwise if those values from the settings record only apply to certain views, one could define a helper method(s) to obtain the data to be sent to the view. In the two methods index() and show() the first four entries are repeated so those could be returned by a new helper method, and the other data entry - e.g. articles or article can be added via array_merge() or the array union operator - i.e. +.
In the FrontEndController constructor a loop could be used to iterate over the properties that need to be set from the settings record.
In the ArticlesController::show() method these three lines could be pulled out:
Article::where('title', 'like', '%' . $qry . '%')
->orWhere('short_description', 'like', '%' . $qry . '%')
->orWhere('content', 'like', '%' . $qry . '%')
and assigned to a local variable like $articlesQuery, which could be then used to generate $articles and $article_count.
Are there any code optimisation opportunities?
If site_settings is only used inside the constructor then perhaps it does not need to be a member variable - it could simply be a local variable.
In the ArticlesController::category() method the line with the query to get the category:
$category = ArticleCategory::where('id', $category_id)->first(); | {
"domain": "codereview.stackexchange",
"id": 43636,
"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, laravel, laravel-blade",
"url": null
} |
Question
# Consider the following in respect of the function $$f(x) = \left\{\begin{matrix}2+ x, & x \geq 0\\ 2 - x, & x < 0\end{matrix}\right.$$1. $$\displaystyle \lim_{x \rightarrow 1} f(x)$$ does not exist.2. f(x) is differentiable at x = 0.3. f(x) is continuous at x = 0.Which of the above statements is/are correct?
A
1 only
B
3 only
C
2 and 3 only
D
1 and 3 only
Solution | {
"domain": "byjus.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9825575137315161,
"lm_q1q2_score": 0.8033139424354829,
"lm_q2_score": 0.8175744739711883,
"openwebmath_perplexity": 6857.01895374182,
"openwebmath_score": 0.8908342719078064,
"tags": null,
"url": "https://byjus.com/question-answer/consider-the-following-in-respect-of-the-function-f-x-left-begin-matrix-2-x/"
} |
state-space, bilinear-transform
$$ \mathbf{A_d} = \left(\alpha\mathbf{I}-A\right)^{-1}\left(\alpha\mathbf{I}+A\right) $$
We know that the linear $(z+1)$ term of $\mathbf{X}(z)$ can be applied wherever $\mathbf{Q}(z)$ is used. We apply this in the output expression to give the new output discrete equation as:
$$ z\mathbf{Q}(z) = \left(\alpha\mathbf{I}-A\right)^{-1}\left(\alpha\mathbf{I}+A\right)\mathbf{Q}(z) + \left(\alpha\mathbf{I}-A\right)^{-1}\mathbf{B}\mathbf{X}(z) $$
$$ \mathbf{Y}(z) = \mathbf{C}\left(z+1\right)\mathbf{Q}(z) + \mathbf{D}\mathbf{X}(z)$$
$$ \mathbf{Y}(z) = \mathbf{C}z\mathbf{Q}(z) + \mathbf{C}\mathbf{Q}(z) + \mathbf{D}\mathbf{X}(z)$$
We can now pull out $\mathbf{B_d}$ as:
$$ \mathbf{B_d} = \left(\alpha\mathbf{I}-A\right)^{-1}\mathbf{B} $$
Because we know an expression for $z\mathbf{Q}(z)$, we can formulate $\mathbf{Y}(z)$ as: | {
"domain": "dsp.stackexchange",
"id": 11957,
"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": "state-space, bilinear-transform",
"url": null
} |
gravity
Title: Gravity is inversely proportional to the distance squared, and tidal forces to the distance cubed. Is there any phenomenon inv/prop to the distance^4? Kinda ran out of characters for the title so had to improvise. Gravity decreases with the square of the distance due to the inverse-square law, and tides are inversely proportional to the cube of the distance since they're the difference between gravity.
So one would assume that if a gravitational phenomenon exists that's inversely proportional to the fourth power of the distance, it would be the difference between tides. If so, does it have a name? And if not, does any similar phenomenon that scales to 1/d^4 exist? Yes, a very important one!
I'm pretty sure the force field due to a rotating body's $J_2$ force field due to it's equatorial oblateness varies as $r^{-4}$. See Wikipedial's Geopotential model; Largest terms
The potential field will be
$$u = J_2 \frac{1}{r^3}(3 \sin^2\theta-1)/2$$
and when moving away in a given direction, the magnitude of the force will then vary as $r^{-4}$.
Earth's $J_2$ term is pretty big. In low Earth orbit it's about a 1 part per thousand variation in Earth's gravitational field. It precesses the orbits of inclined satellites, so for example the plane of ISS' orbit precesses around the Earth (relative to the starts) about every two months, so that it alternates between constant daylight for several weeks then alternating day/night every 90 minutes for several weeks.
It has a small effect on the Moon as well.
This force also explains why Jupiter's and Saturn's moons (and Saturn's rings) are all so tightly constrained to the equatorial planes of those planets. | {
"domain": "astronomy.stackexchange",
"id": 7208,
"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": "gravity",
"url": null
} |
The final step is taking the limit of better and better approximations over finer and finer subdivisions of $[0,1]$.
The points $C_i$ were found by dividing the interval $[0,1]$ into $n$ equal pieces and finding the right endpoints of those pieces. Since the length of $[0,1]$ is $1$, each piece must have length $\frac1n$. The first begins at $x=0$, so its right endpoint must be at $\frac1n$. The next begins at $\frac1n$, so its right endpoint must be at $\frac1n+\frac1n=\frac2n$. The third begins at $\frac2n$, so its right endpoint must be at $\frac2n+\frac1n=\frac3n$. Continuing in this fashion, you can see that the right endpoint of the $i$-th subinterval must be at $\frac{i}n$.
-
OK. So just out of curiosity, does this method return a approximation of area, or an exact value? – OneChillDude Dec 4 '12 at 4:25
@bwheeler96: The individual summations are approximations; their limit is the exact value. In fact, the area of regions that cannot be chopped up and rearranged into rectangles can be defined as that limit. – Brian M. Scott Dec 4 '12 at 4:31
So, $f(C_i)$ is the value of $f$ at $C_i$, but more importantly it is the height of the specific rectangle being used in the approximation. Then $i$ is just the interval which is the base of the rectangle. As $|C_{i+1}-C_i|\rightarrow 0$, this sum becomes the area under the curve.
-
OK. What I meant to say was how do I find $(C_i)$ ? Is it a constant? – OneChillDude Dec 4 '12 at 4:20 | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9715639686018702,
"lm_q1q2_score": 0.8053670783408596,
"lm_q2_score": 0.8289388083214156,
"openwebmath_perplexity": 164.50885095719082,
"openwebmath_score": 0.8719300031661987,
"tags": null,
"url": "http://math.stackexchange.com/questions/250455/integral-and-area-of-a-section-bounded-by-a-function"
} |
then be easily found by translating! Containing ones down the main difference between this calculator finds the modular of... Multiply a matrix following nxn matrix step-by-step this website uses cookies to you! Number 2, it is multiplied with the original matrix modular multiplicative inverse of following! By translating back to equation form Gauss-Jordan elimination to transform [ a | I into... Determinante eine inverse wenn und nur wenn ihr Determinante eine inverse im Koeffizienten aufweist Ring 2 units glass. Using elementary row operations for the multiplicative inverse of matrix C. Step 3: of glass lesson a... ( 5 ) = 11 - 10 = 1 a Course lets you earn progress by quizzes. In arithmetic, there is one number which does not have a * a = I identity matrices by when... Numbers each time page to learn more, visit our Earning Credit page what is inverse! Are done in modular multiplicative inverse of matrix regular numbers, our answer matrix, I is known as the identity matrix a... Get the identity matrix of a matrix to Another lesson skew symmetric matrix expression and then invert matrix! Is the matrix that is similar to a scalar matrix is a square matrix ones!, b, multiplied by the same number of rows and … what is the number b is. Expression and then invert the matrix that gives you the identity matrix is the number b is., our answer matrix, we multiply both sides by the multiplicative inverse: Another name for.! And has taught math at a public charter high school person while spinning than not spinning original the... Refreshing the page, or contact customer support dimension to it improve our educational.... With a superscript of -1 matrix Step 1: be a Study.com Member answer by translating back to equation.. Inverse '' of 7 , which is 1/7 is written a^ ( -1 ) solve! Coefficient matrix A^-1 = A^-1 * a sup -1 = I if we a! Guided Practice Practice Read and study the lesson to answer each question mostly as... inverse '' of 7 , which is you 're with... Person while spinning than not spinning the discussion on how to find the inverse of a matrix a written... The vector equation into a 3x3 skew symmetric | {
"domain": "gridserver.com",
"id": null,
"lm_label": "1. Yes\n2. Yes\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9814534344029238,
"lm_q1q2_score": 0.8544506708232129,
"lm_q2_score": 0.8705972600147106,
"openwebmath_perplexity": 696.4878762898684,
"openwebmath_score": 0.757369875907898,
"tags": null,
"url": "https://s12762.gridserver.com/1gb40i0t/43d397-master-electrician-test"
} |
photons, photoelectric-effect, metals
Title: Does the Photoelectric Effect cause any kind of decay? From my understanding, the Photoelectric Effect knocks electrons off of some metal using photons. Since electrons are being thrown out of the metal, does this cause some kind of decay? (I am guessing that you by "decay" mean, "is the material loosing mass slowly". As the other answer suggests, decay is a word reserved for something else in physics.)
"Knocs electrons off" is in this sense quite a simplistic way to describe it. Rather see it like this:
The photoelectric effect is when a photon (light) excites an electron. "Excites" means that it has more energy (a higher energy state), and in this case enough energy to move now (enough energy to reach the socalled conduction band). Moving electrons is current.
Just remember that this material from which the electrons are "ripped off" from - or rather excited in - is a part of a circuit. In an electric circuit the electrons moving away are as part of the current replaced by new electrons right away from further down the circuit.
Electrons are moving around the circuit at all points at all times if you have a steady current. | {
"domain": "physics.stackexchange",
"id": 22293,
"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": "photons, photoelectric-effect, metals",
"url": null
} |
c++, beginner, object-oriented, design-patterns
private:
/* data-member */
std::string libraryNumber;
Date dateRegisted;
std::vector<BookItem> checkedOutBooks;
public:
/* data-member */
std::string name;
char sex;
/* ctors */
Member() = default;
Member( const std::string &n, const char s, Date d ) : dateRegisted( d ), name( n ), sex( s ) {}
/* method-functions */
std::string getLibraryNumber() const { return libraryNumber; }
void setLibraryNumber( const std::string &lNum ) { libraryNumber = lNum; };
void checkOut( System &sys, const std::string &isbn );
void returnBook( System &sys, const std::string &isbn );
bool operator==( const Member &m );
bool operator!=( const Member &m ) { return !( *this == m ); }
// dtor
~Member() = default;
};
#endif
System.cc
#ifndef SYSTEM_HH
#define SYSTEM_HH
#include <string>
#include <list>
#include <vector>
#include "Date.hh"
#include "BookItem.hh"
#include "Librarian.hh"
#include "Member.hh"
class System {
friend class Librarian;
friend class Member;
private:
/* data-members */
std::list<BookItem> books{};
std::vector<Member> members{};
Librarian librarian;
Member member;
public:
/* ctors */
System() = default;
System( const std::string &name, Date &date ) : libraryName( name ), dateCreated( date ) {}; | {
"domain": "codereview.stackexchange",
"id": 39645,
"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, design-patterns",
"url": null
} |
quantum-field-theory
In order to find the probability density for $x$, you have to expand your state in $|x\rangle$'s and procced analogous to the momentum. Write $|\psi\rangle=a^\dagger|0\rangle=\sum_x|x\rangle\langle x|\psi\rangle$. I write it like sum to hide the normalisation. $\langle x|\psi\rangle$ is easy to obtain if you substitute the definitions. As with $k$, $|\langle x|\psi\rangle|^2$ is pretty much the answer, up to some normalisation. | {
"domain": "physics.stackexchange",
"id": 7489,
"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",
"url": null
} |
newtonian-mechanics, momentum, conservation-laws
Title: Understanding Momentum I'm trying to learn more about momentum and I'm a little confused. Based on my understanding, in an isolated system, total momentum is conserved in a collision. Today in class the professor went over an example of a car on a ferry driving from one end to the other, in the opposite direction of the ferry. According to him, the total momentum for the system was zero in this case. I understand why total momentum is zero in a collision: because the objects come at rest. But in the example both the car and the ferry are moving (the goal is to find the ferry's new velocity as the car takes off).
So my question is: Is total momentum always zero if two objects are in touch with each other and are applying the same amount of force (but in the opposite direction) to each other? Also, the water applies the same amount of force to the ferry (again in the opposite direction) but how come it's not considered in our "system"? The rule is that the total momentum of an isolated system is constant. In the example with the car and the ferry, the isolated system is the system consisting of the car and the ferry. The system is isolated because it is assumed that there is no interaction (such as drag) between the ferry and the water.
Then you could imagine that the car and ferry are stationary with respect to each other. Then as the car begins to move and gains momentum in one direction, the ferry gains momentum in the other direction. Conservation of momentum guarantees that the car and ferry momenta add to zero so that the total momentum is zero.
It is important to notice that the rule is not that total momentum is zero, but that total momentum is conserved. So if the car and ferry were initially drifting with some speed, then when the car starts moving across the ferry, the car will gain momentum and the ferry will lose momentum but the total momentum will remain at its initial non-zero value.
Also notice that in a more realistic model, you would include the drag force from the water. Then the momentum of the car/ferry system would not be conserved (which is allowed because it is no longer an isolated system). But if you add in the momentum of the water, you will find that still the total momentum is conserved. | {
"domain": "physics.stackexchange",
"id": 14030,
"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, momentum, conservation-laws",
"url": null
} |
directly, since they have dimension greater than three. The concept of the graph of a function is generalized to the graph of a relation. Thread: chart function of two variables. Furthermore, sums, dif-. For example, if you are studying the effects of a new educational program on student achievement, the program is the independent variable and your measures of achievement are the dependent ones. You can choose any other combination of numbers as well. f(x,y) is inputed as "expression". Fortunately for us, we have technology which facilitates this task. Use Wolfram|Alpha to generate plots of functions, equations and inequalities in one, two and three dimensions. But polynomials, trig functions, power and root functions, logarithms, and exponential func-tions are all continuous. Suppose that X and Y are two random variables having moment generating functions MX(t) and MY (t) that exist for all t in some interval 3. In the present case, we see that the critical point at the origin is a local maximum of f2 , and the second critical point is a saddle point. Integrals of a function of two variables over a region in R 2 are called double integrals, and integrals of a function of three variables over a region of R 3 are called triple integrals. The standard deviation of an observation variable is the square root of its variance. It is good programming practice to avoid defining global variables and instead to put your variables inside functions and explicitly pass them as parameters where needed. I'm having a bit of trouble grasping the domain and range of functions of 2 variables. 3-Dimensional graphs of functions are shown to confirm the existence of these points. Boolean Functions (Expressions) It is useful to know how many different Boolean functions can be constructed on a set of Boolean variables. To input the variable x as a Wildcard, first type Shift + ?, then type x; similarly, for y. Importantly,. peaks is a function of two variables, obtained by translating and scaling Gaussian distributions, which is useful for demonstrating mesh, surf, pcolor, contour, and so on. Local extreme values of a function of two variables. Dependent has two categories, there is only one discriminant function. When variables change together, their interaction is called a relation. In general, I can't create new functions in a poisoned session. That is, a function | {
"domain": "firstbostonsoftware.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9871787864878117,
"lm_q1q2_score": 0.8504922476085536,
"lm_q2_score": 0.8615382129861583,
"openwebmath_perplexity": 349.66721326333993,
"openwebmath_score": 0.6182748079299927,
"tags": null,
"url": "http://firstbostonsoftware.com/kt1a/exu.php?flz=function-of-two-variables"
} |
ros, moveit, ros-kinetic, moveit-commander
Title: MoveItCommanderException: Error setting joint target. Is the target within bounds?
Hey guys,
I have a 5 DOF arm. I am controlling it with an XBOX 360 controller.
Now, the maximum limits my arm can reach is +/-3.1 radians. As soon as it reaches either of the limitations, it throws the following error:
[ERROR] [1526221188.380066]: bad callback: <function callback at 0x7f48e9de4e60>
Traceback (most recent call last):
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 750, in _invoke_callback
cb(msg)
File "/home/kashyap/catkin_ws/src/igus_trajectory_planning/scripts/set_joy.py", line 123, in callback
group1.set_joint_value_target(group1_variable_values)
File "/home/kashyap/catkin_ws/src/moveit/moveit_commander/src/moveit_commander/move_group.py", line 227, in set_joint_value_target
raise MoveItCommanderException("Error setting joint target. Is the target within bounds?")
MoveItCommanderException: Error setting joint target. Is the target within bounds?
In my code, i am trying to print 'position not reachable' when it reaches either of the 2 extremes. Any suggestions as to how can I avoid the long error message from above in favour of 'position not reachable' ?
Originally posted by Kashyap.m94 on ROS Answers with karma: 46 on 2018-05-13
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 30812,
"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, moveit, ros-kinetic, moveit-commander",
"url": null
} |
go, lexical-analysis
Title: Simplest lexer for c in go I started learning compilers development and as pet project decided to implement c compiler.
The first step is implementing simplest lexer.
Also, I decided to try new programming language and chose go. This is my first go program and I will be grateful for any advice. Thanks.
package lexer
import (
"errors"
"fmt"
"unicode"
)
type tokenType int
const (
EOF tokenType = iota
Identifier
NumericConstant
IntType
ReturnKeyword
OpenRoundBracket
CloseRoundBracket
OpenCurlyBracket
CloseCurlyBracket
Semicolon
)
type token struct {
tokenType tokenType
value string
}
type parser struct {
code []rune
currentIndex int
}
func (p *parser) nextToken() token {
p.skipSpaces()
if p.isEOF() {
return token{tokenType: EOF}
}
var newToken token
r := p.currentRune()
if unicode.IsLetter(r) {
newToken = p.parseLetterStartToken()
} else if unicode.IsNumber(r) {
newToken = p.parseNumberStartToken()
} else if r == '(' {
newToken = token{tokenType: OpenRoundBracket, value:string(r)}
} else if r == ')' {
newToken = token{tokenType: CloseRoundBracket, value:string(r)}
} else if r == '{' {
newToken = token{tokenType: OpenCurlyBracket, value:string(r)}
} else if r == '}' {
newToken = token{tokenType: CloseCurlyBracket, value:string(r)}
} else if r == ';' {
newToken = token{tokenType: Semicolon, value:string(r)}
} else {
errorText := fmt.Sprintf("Unexpected character: %c", r)
panic(errors.New(errorText))
}
p.currentIndex += 1
return newToken
} | {
"domain": "codereview.stackexchange",
"id": 36330,
"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": "go, lexical-analysis",
"url": null
} |
quantum-mechanics, quantum-entanglement
Take for instance $[\hat{\sigma}_{y1} \hat{\sigma}_{x2} \hat{\sigma}_{x3}, \hat{\sigma}_{x1} \hat{\sigma}_{y2} \hat{\sigma}_{x3}]$; I think that I must not understand the implementation of the tensor products as my guess would be that $\hat{\sigma}_{y1} \hat{\sigma}_{x2} \hat{\sigma}_{x3} \hat{\sigma}_{x1} \hat{\sigma}_{y2} \hat{\sigma}_{x3} - \hat{\sigma}_{x1} \hat{\sigma}_{y2} \hat{\sigma}_{x3} \hat{\sigma}_{y1} \hat{\sigma}_{x2} \hat{\sigma}_{x3} = [\hat{\sigma}_{y1}, \hat{\sigma}_{x1}][\hat{\sigma}_{x2}, \hat{\sigma}_{y2}] \hat{\sigma}_{x3} \neq 0$. Any help would be much appreciated. Thank you! $$(_^1 _^2_x^3)( _^1\sigma_^2_^3)\\=-\sigma_x^1_^1 _^2_x^3 \sigma_^2_^3\quad (x1,y1\, {\rm anticommute})\\
=+ \sigma_x^1\sigma_y^2_^1 _^2_x^3 _^3\quad (x2,y2 \,{\rm anticommute})\\
=+(_^1\sigma_^2_^3)(_^1 _^2_x^3)\quad (x3,x3 \,{\rm commute})
$$
Everything else commutes. | {
"domain": "physics.stackexchange",
"id": 71280,
"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, quantum-entanglement",
"url": null
} |
php
Title: Building functions.php Lets say I build functions.php and I have 3 functions inside of it that I use. Lets say that I build a 4th function, but what I really want to do is simply put the instructions of function 4 into function 1 for example. Is there anything wrong with this?
Consider my example here, where I have included a function inside of a function. I am aware that the variables inside of a function are local, and that you cannot call a variable inside a function outside of it, however I have tested this with a simple echo test and it seems to work. Is there anything wrong with doing this? If so, can you explain how you might go about doing this generally? You do not have to be specific.
functions.php
function validate_registration($password, $confirmpassword, $email) {
if ((empty($email)) || (empty($password)) || (empty($confirmpassword))) {
registration_form();
echo "Please enter the required information:";
}
elseif ((filter_var($email, FILTER_VALIDATE_EMAIL)) && ($password == $confirmpassword)) {
input_registration($email, $password);
}
elseif ((filter_var($email, FILTER_VALIDATE_EMAIL)) && ($password !== $confirmpassword)) {
registration_form();
echo "Your password does not match!";
}
else {
registration_form();
echo "You have not entered a valid email address!";
}
}
the input_registration function:
function input_registration ($email, $password) {
$email_clean = htmlspecialchars($email);
$password_clean = htmlspecialchars($password);
$hash = md5($password_clean);
$db = new PDO("mysql:host=localhost;dbname=users", "root", "")
$statement = $db->prepare("INSERT into userinfo(email, hash) VALUES (:email, :hash)") | {
"domain": "codereview.stackexchange",
"id": 3961,
"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",
"url": null
} |
python, algorithm, python-3.x
# Distance to each vertex along augmenting paths.
dist = {}
inf = float('inf')
def bfs():
# Breadth-first search of the graph starting with unmatched
# vertices in U and following "augmenting paths" alternating
# between edges from U->V not in the matching and edges from
# V->U in the matching. This partitions the vertexes into
# layers according to their distance along augmenting paths.
queue = deque()
for u in U:
if pair_u[u] is nil:
dist[u] = 0
queue.append(u)
else:
dist[u] = inf
dist[nil] = inf
while queue:
u = queue.pop()
if dist[u] < dist[nil]:
# Follow edges from U->V not in the matching.
for v in graph[u]:
# Follow edge from V->U in the matching, if any.
uu = pair_v[v]
if dist[uu] == inf:
dist[uu] = dist[u] + 1
queue.append(uu)
return dist[nil] is not inf
def dfs(u):
# Depth-first search along "augmenting paths" starting at
# u. If we can find such a path that goes all the way from
# u to nil, then we can swap matched/unmatched edges all
# along the path, getting one additional matched edge
# (since the path must have an odd number of edges).
if u is not nil:
for v in graph[u]:
uu = pair_v[v]
if dist[uu] == dist[u] + 1: # uu in next layer
if dfs(uu):
# Found augmenting path all the way to nil. In
# this path v was matched with uu, so after
# swapping v must now be matched with u.
pair_v[v] = u
pair_u[u] = v
return True
dist[u] = inf
return False
return True | {
"domain": "codereview.stackexchange",
"id": 29191,
"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, algorithm, python-3.x",
"url": null
} |
proof-techniques, greedy-algorithms
Title: Proof of a greedy algorithm used for a variation of bin-packing problem We are given an array of weights $W$ (all weights are positive integers), and we need to put the
weights inside bins. Each bin can hold a maximum of Max_val, and each weight is at most Max_val. The variation is that the ordering of weights should not be changed, that is, $W_i$ should be inside a bin before $W_j$ is inserted, for all $i < j$.
For this problem statement, intuitively we can see that a greedy approach of filling a bin till its maximum value is reached and creating a new bin for further weights will produce the minimum number of bins. I am unable to come up with a formal proof that the greedy solution is optimal. Any hints or guidelines would be great! Let $G$ be the solution produced by the greedy algorithm. For each other solution $S$, let $i(S)$ be the index of the first weight at which $S$ diverges from $G$. Let $O$ be an optimal solution maximizing $i(O)$. Thus $G$ places $i(O)$ in bin $j$ (for some $j$), and $O$ places $i(O)$ in bin $j+1$. If we move $i(O)$ to bin $j$ (which is possible since $O$ is ordered), we obtain a solution $O'$ using at most as many bins as $O$, and satisfying $i(O') > i(O)$. This contradicts the choice of $O$.
If we try to run this argument on the unrestricted bin packing algorithm, we will have trouble when moving $i(O)$ to bin $j$, since that bin might be occupied with other elements, not leaving enough room for $i(O)$. In the variant you consider, this cannot happen. | {
"domain": "cs.stackexchange",
"id": 16005,
"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": "proof-techniques, greedy-algorithms",
"url": null
} |
symmetry, conservation-laws, gauss-law, vector-fields, noethers-theorem
Title: Does the divergence theorem imply an underlying symmetry? The divergence theorem connects the flux (through surface) and divergence (in a volume) for any vector field.
This theorem expresses continuity. It isn't clear (to me) whether there is a conserved quantity associated with the continuity equation. It appears that this theorem would be equivalent to mass conservation, if the flux represented (say) fluid flow. In the general case of a vector field, I'm not sure what (if anything) is conserved.
I would like to know if this continuity implies a conserved quantity and an underlying symmetry, by the converse of Noether's theorem. If this (existence of symmetry/conserved quantity) is true for some vector fields but not all, what causes the distinction? Examples would be greatly appreciated.
While I don't have a strong background on Lagrangian mechanics, I'm happy to be directed to background reading that would help. The integral theorem of Gauss, $$\int\limits_V \! d^3x \; \vec{\nabla} \cdot \vec{A}(\vec{x}) =\int\limits_{\partial V}\! d \vec{\sigma} \cdot \vec{A}(\vec{x}), \tag{1} \label{1}$$ is a purely mathematical statement. Taken by itself, it does not express "continuity" in any sense. | {
"domain": "physics.stackexchange",
"id": 99479,
"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": "symmetry, conservation-laws, gauss-law, vector-fields, noethers-theorem",
"url": null
} |
Likewise, the graph of $y=cos(x)+0.5x$ is a standard cosine graph oscillating around $y=0.5x$.
We teach polar graphing the same way. To graph $r=3+cos(2\theta )$, we encourage our students to “read” the function as a cosine curve of period $\pi$ oscillating around the polar function $r=3$. Because of its period, this curve will complete a cycle in $0\le\theta\le\pi$. The graph begins this interval at $\theta =0$ (the positive x-axis) with a cosine graph 1 unit “above” $r=3$, moving to 1 unit “below” the “center line” at $\theta =\frac{\pi}{2}$, and returning to 1 unit above the center line at $\theta =\pi$. This process repeats for $\pi\le\theta\le 2\pi$.
Our students graph polar curves far more confidently since we began using this approach (and a couple extensions on it) than those we taught earlier in our careers. It has become a matter of understanding what functions do and how they interact with each other and almost nothing to do with memorizing particular curve types.
So, now that our students are confidently able to graph polar curves like $r=3+cos(2\theta )$, we wondered how we could challenge them a bit more. Remembering variable center lines like the Cartesian $y=cos(x)+0.5x$, we wondered what a polar curve with a variable center line would look like. Not knowing where to start, I proposed $r=2+cos(\theta )+sin(\theta)$, thinking I could graph a period $2\pi$ sine curve around the limacon $r=2+cos(\theta )$. | {
"domain": "wordpress.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9859363762626284,
"lm_q1q2_score": 0.817280920653363,
"lm_q2_score": 0.8289388040954684,
"openwebmath_perplexity": 597.7391518388741,
"openwebmath_score": 0.8109343647956848,
"tags": null,
"url": "https://casmusings.wordpress.com/tag/limacon/"
} |
ruby, programming-challenge
so that this code needn't be changed if you rename the class. (Note that new str.split... is the same as self.new str.split....)
However, you don't need a class method to create the instance. Instead, just write:
arr = str.split("\n").map { |row| row.split(" ").map { |val| val.to_i } }
grid = Grid.new(arr)
Consolidate all calculations in the class
You want to move:
def max_product lines
lines.flat_map { |line| line.each_cons(4).to_a }.map { |cons| cons.inject {
|prd, x| prd * x} }.max
end
and
[:horizontals, :verticals, :diagonals, :inv_diagonals].map { |method|
max_product(grid.send(method)) }.max
into the class definition and make the latter a method:
def max_product_all_ways
[:horizontals, :verticals, :diagonals, :inv_diagonals].map { |method|
max_product(grid.send(method)) }.max
end
but I think it would be clearer to write:
def max_product_all_ways
[max_product(horizontals),
max_product(verticals),
max_product(diagonals),
max_product(inv_diagonals)].max
end
You would then invoke max_product_all_ways as follows:
arr = str.split("\n").map { |row| row.split(" ").map { |val| val.to_i } }
grid = Grid.new(arr)
grid.max_product_wall_ways
Diagonal detail
It's a small thing, but in diagonals you don't need to compute the diagonals of length less than four if only arrays of size four are to be considered. In fact, you should not, as it is conceivable that a diagonal of length less than four could have the greatest product!
Revised class definition
So this is what we now have (more or less):
class Grid | {
"domain": "codereview.stackexchange",
"id": 11031,
"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, programming-challenge",
"url": null
} |
python, programming-challenge, hash-map, lambda
Turning book into a set of letters is an \$O(m)\$ operation. With that, c not in book_letters becomes an \$O(1)\$ operation. Repeated in the loop n times makes it \$O(n)\$, so the entire function becomes \$O(m + n)\$ … considerably faster.
But wait! While we’re at it, what is with the temporary list of characters [c …]? It is created just to be iterated over in the join(…). Why not just iterate without the temporary list creation?
def new_book(book, plain_text):
book_letters = set(book)
return book + "".join(c for c in plain_text if c not in book_letters)
Better solutions
Why add plain_text to the book? If you and you friend (or spy) have exchanged a book, and then you need to send a message with letters which were not in the book, you have to send a complete new_book to your friend (spy) … which could be intercepted making the encryption useless.
Plus, if a second message is sent with still different letters, yet another book would be necessary. A third message would require a third book, and so on! Decoding the cipher would require knowing which book was used to encode it (book1, book2, book3, …) — information which is not given.
It is a simple matter to expand the book without relying on plain_text. Just unconditionally add string.printable to the original book. This easily takes care of your missing !ABENQjx characters.
Except, it is still not a complete solution. Résumé would still result in -1 encodings. Adding the entire Unicode character set to book would be required, if you stayed with this approach. Instead, why not record the maximum value your book encoder returns, and return that value plus ord(c) for characters not in the book? When an encoded value exceeds the maximum value the book can decode, subtract that maximum, and use chr(#) to convert it back to the required character. | {
"domain": "codereview.stackexchange",
"id": 44023,
"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, programming-challenge, hash-map, lambda",
"url": null
} |
gazebo
<body2>${name}_link</body2>
<anchor>${name}_motor_screw_link</anchor>
<anchorOffset>0 0 0</anchorOffset>
<axis>0 0 1</axis>
<threadPitch>3141.6</threadPitch>
</joint:screw> | {
"domain": "robotics.stackexchange",
"id": 9637,
"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": "gazebo",
"url": null
} |
c++, tic-tac-toe, ai
Separate responsibilities
The Model-View-Controller design pattern is often useful for programs like this. Because the view in this case is essentially just printing the board to std::cout, we can simplify a bit and just have a model, the TicTacToe class, and a controller, the Game class. Doing so would make it much easier to make changes to the code such as porting it to use a GUI or adapting it to be playable remotely via a socket. | {
"domain": "codereview.stackexchange",
"id": 28752,
"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++, tic-tac-toe, ai",
"url": null
} |
c, performance
int byte_type[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, | {
"domain": "codereview.stackexchange",
"id": 1235,
"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",
"url": null
} |
algorithms, asymptotics, runtime-analysis, big-o-notation
If $c< +\infty$ then $f(n) = O(g(n))$ (and $g(n) = \Omega(f(n))$). In particular:
If $0 < c < +\infty$ then $f(n) = \Theta(g(n))$ (and $g(n) = \Theta(f(n))$).
If $c=0$ then $f(n) = o(g(n))$ (and $g(n) = \omega(f(n))$).
If $c > 0$ then $f(n) = \Omega(n))$ (and $g(n) = O(f(n))$). In particular:
If $0 < c < +\infty$ then $f(n) = \Theta(g(n))$ (and $g(n) = \Theta(f(n))$).
If $c = +\infty$ then $f(n) = \omega(g(n))$ (and $g(n) = o(f(n))$). | {
"domain": "cs.stackexchange",
"id": 15819,
"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, asymptotics, runtime-analysis, big-o-notation",
"url": null
} |
rotational-dynamics, angular-momentum, reference-frames
So you can't compute $\vec{L}'$ in a frame where all points of the system are at rest, unless of course the system isn't rotating at all in the inertial frame.
Edit: that last paragraph is true for a rigid body. For a generic system of moving points, $\vec{L}'$ could be zero without every point being at rest, but it doesn't change the fact that $\vec{L}'$ is defined in the center-of-mass frame defined above. | {
"domain": "physics.stackexchange",
"id": 88363,
"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": "rotational-dynamics, angular-momentum, reference-frames",
"url": null
} |
That is, we always take the area of quadrilateral as positive. The area of a quadrilateral is the number of unit squares that can be fit into it. The diagonal divides the quadrilateral in to two triangles. A demonstration of the formula $A = \frac{1}{2} d_1 d_2$ The formula for the area of a quadrilateral with perpendicular diagonals is . 4. Area of General Quadrilateral You are here. Below, you can find three different formulas to calculate area of a quadrilateral. There are many types of quadrilaterals, each having its own properties and formula of area. If ABCD is a quadrilateral, then considering the diagonal AC, we can split the quadrilateral ABCD into two triangles ABC and ACD. Applied Math Area of Quadrilateral . We will study the Area of a Quadrilateral formula in detail. Kite is a special quadrilateral in which each pair of the consecutive sides is congruent, but the opposite sides are not congruent. Area of a Quadrilateral. How to find the area of a trapezoid - How to Find - Know the formula A quadrilateral is a plane figure which is bounded by four sides. Quadrilateral Area, Formula, Types, & Examples. 5.2 Quadrilaterals. Definition of quadrilateral : The word quadrilateral can be separated as Quad + lateral. The interior angles of a simple (and planar) quadrilateral add up to 360 degrees of arc. The area of any irregular quadrilateral can be calculated by dividing it into triangles. Let us now discuss the quadrilateral formula in detail. Area of kite =1/2 x Diagonal 1 x Diagonal 2. where diagonal 1 = long diagonal of kite(KM) Area of General Quadrilateral. Quadrilateral. If I have some cells containing the side lengths of a quadrilateral box. cm . Here quad means four and lateral means sides. Jump to navigation Jump to search {{#invoke:Hatnote|hatnote}} Template:Infobox Polygon In Euclidean plane geometry, a quadrilateral is a polygon with four sides (or edges) and four vertices or corners. I got stuck with too many variables. A1= 1 A2 | {
"domain": "cykelfabriken.se",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9621075755433747,
"lm_q1q2_score": 0.8017479100188483,
"lm_q2_score": 0.8333245994514084,
"openwebmath_perplexity": 895.497638350082,
"openwebmath_score": 0.6410919427871704,
"tags": null,
"url": "https://cykelfabriken.se/x50qr/f781ae-quadrilateral-area-formula"
} |
astrophysics, orbital-motion, planets, solar-system, moon
Now on to astrophysics.
While there are still details to be hammered out, we have a reasonably good understanding for how the Solar System formed. A cloud of material began to collapse under its own gravity. Because the gas and dust particles in this cloud could bump into one another, they could exchange energy and angular momentum (important fact #1). Also, the cloud, even though it may have been close to spherical, likely contained some net angular momentum on the whole (important fact #2) - it is just unlikely that all the particles' motions would exactly cancel.
These two important facts, when taken together, mean the material is likely to settle into a disk. Particles whose angular momentum deviates from the average (by going in the wrong direction, by moving out of the preferred plane, by moving too fast in the right direction, etc.) will tend to be brought in line with everything else by these collisions. Gravity alone could accomplish this via dynamical friction, but collisions speed up the process so it occurs in reasonable time. Because important facts #1 and #2 are ubiquitous in so many astrophysical settings, many systems naturally form disks, for example galaxies.
The Sun, planets, moons, asteroids, and everything else then all formed from this disk, where everything was rotating with the same sense. As a result, most objects in the Solar System move in a plane, in the same direction. Furthermore, their spins are aligned the same way.
There are exceptions to this rule, but they are not common. They are interesting because they show the object in question does not have quite the same history as typical objects in the Solar System. Notable examples include: | {
"domain": "physics.stackexchange",
"id": 8825,
"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, orbital-motion, planets, solar-system, moon",
"url": null
} |
slam, navigation, octomap, octomap-server
Originally posted by jwrobbo with karma: 258 on 2012-02-04
This answer was ACCEPTED on the original site
Post score: 3
Original comments
Comment by Felix Endres on 2012-02-07:
Have a look at the file "/opt/ros/electric/stacks/octomap_visualization/rosdep.yaml" and install the mentioned packages manually using "apt-get install "
Comment by Mike Moore on 2012-02-04:
Thanks jwroobo, experimental for color OCTOMAPS. Definitely isnt building properly as I still get these missing dep. errors: "Failed to find rosdep qglviewer-qt4 for package octovis on OS:ubuntu version:oneiric" and "Failed to find rosdep qt4-opengl for package octovis on OS:ubuntu version:oneiric"? | {
"domain": "robotics.stackexchange",
"id": 8106,
"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, octomap, octomap-server",
"url": null
} |
c++, simulation, pthreads
if(pthread_mutex_lock(&Bridge))
cerr << "failed to lock bridge" << endl;
if(pthread_mutex_lock(&okToOutput))
cerr << "failed to lock output" << endl;
cout << "Vehichle " << inData->licencePlate << " is ON the main bridge going " << dirToStr(inData->direction) << endl;
if(pthread_mutex_unlock(&okToOutput))
cerr << "failed to unlock output" << endl;
if(usleep(inData->sleepT2))
cerr << "Vehichle " << inData->licencePlate << " failed to sleep" << endl;
if(pthread_mutex_lock(&okToOutput))
cerr << "failed to lock output" << endl;
cout << "Vehichle " << inData->licencePlate << " is OFF the main bridge after going " << dirToStr(inData->direction) << endl;
if(pthread_mutex_unlock(&okToOutput))
cerr << "failed to unlock output" << endl;
if(pthread_mutex_unlock(&Bridge))
cerr << "failed to lock bridge" << endl;
return NULL;
}
My compiler doesn't properly support C++11 so no smart pointers etc. As mentioned in the comments, there's not much to review.
Don't abuse using namespace std
Putting using namespace std within your program is generally a bad habit that you'd do well to avoid.
Factor out common code
In this case, the code gets a lock, does something, and releases the lock. That could easily be isolated to a common function:
class Locker
{
pthread_mutex_t& mutex;
bool ok;
public:
operator bool() const {return ok;} | {
"domain": "codereview.stackexchange",
"id": 10286,
"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++, simulation, pthreads",
"url": null
} |
c, strings, pattern-matching
for (int j = 0; j < *ret; j++)
;
There's no return statement if the loop completes.
getr_seq()
Why are we working through this character by character, when we have a perfectly good string library provided in C? We can use strcmp() or memcmp() to compare the substrings, and strcpy()/memcpy() to copy characters (though I don't see any need to do so, meaning we can eliminate the array parameter).
This function is also missing a return statement in at least one path.
Modified code
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
static bool is_repeating(const char *arr, size_t chunk_size)
{
/* are all substrings of length i equal? */
for (const char *chunk = arr + chunk_size; *chunk; chunk += chunk_size) {
if (memcmp(arr, chunk, chunk_size)) {
/* no, unequal */
return false;
}
}
/* all length-i substrings identical */
return true;
}
size_t minimal_repeating_length(const char *arr)
{
const size_t n = strlen(arr);
for (size_t i = 1; i < n; ++i) {
if (n % i == 0 && is_repeating(arr, i)) {
return i;
}
}
return n; /* no repetitions, so it's the whole string */
}
int main(void)
{
const char *arr = "abcdeabcde";
size_t repeat_len = minimal_repeating_length(arr);
printf("(%.*s)\n", (int)repeat_len, arr);
} | {
"domain": "codereview.stackexchange",
"id": 41663,
"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, strings, pattern-matching",
"url": null
} |
aqueous-solution, liquids
Title: Liquid Versus Aqueous States? I am studying ionic equations and have encountered the statement of the phase of matter in the equation since ionic substances tend to react differently based on their phase.
I know that
(l) state is when the substance itself is a liquid
(aq) state is when we put the substance in an aqueous solutions, most commonly water.
But I don't know
1) Why and when would you use one state over the other. (Answered)
2) How do you define the concentration when you say (aq) state? Is it predefined/can be computed based on the substance or reaction or is it irrelevant?
2) How do you define the concentration when you say (aq) state? Is it predefined/can be computed based on the substance or reaction or is it irrelevant? | {
"domain": "chemistry.stackexchange",
"id": 11763,
"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": "aqueous-solution, liquids",
"url": null
} |
electromagnetism, tensor-calculus, integration, vector-fields
However, does this solution mean that a person that has never learned tensor analysis can never solve the problem? I wonder whether there are any other solutions without using tensors.
Thank you for your reading the question. Waiting for your excellent answers. "Tensor" analysis is just fancy language, and you can do this just fine without it. The essence of tensor analysis (or at least one way of looking at said essence; see this answer for more on that) is to do things component by component. Since
$$
\int_V\text{d}V\ \mathbf A=\sum_j \hat{\mathbf e}_j\int_V\text{d}V\ (\hat{\mathbf e}_j\cdot\mathbf A),
$$
it is sufficient to just consider the integral of the scalar quantity $A_j=\hat{\mathbf e}_j\cdot\mathbf A$. In this language, the proof is a reformulation of what you've given: because
$$
\nabla \cdot(x_j\mathbf A) = (\nabla x_j)\cdot\mathbf A + x_j \nabla\cdot\mathbf A = \hat{\mathbf e}_j\cdot\mathbf A,
$$
we can write
\begin{align}
\int_V\text{d}V\ (\hat{\mathbf e}_j\cdot\mathbf A)
& =
\int_V\text{d}V\ \nabla \cdot(x_j\mathbf A)
\\ & =
\oint_S\text{d}\mathbf S\cdot(x_j\mathbf A),
\end{align}
which vanishes because $\mathbf A$ and $\mathrm d\mathbf S$ are orthogonal, and you're done. See? Easy! The tensor-analysis layer is just some fancy language on top to make everything come together slightly more coherently, but it is fundamentally the same proof. | {
"domain": "physics.stackexchange",
"id": 38522,
"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": "electromagnetism, tensor-calculus, integration, vector-fields",
"url": null
} |
• what you gona do if the equation has 4th power? – Salihcyilmaz Sep 3 '15 at 15:55
• @Salihcyilmaz Well, if you are trying to factor a 4th degree polynomial it gets much more difficult. There is actually a closed form formula, but it is quite hairy. There is no general easy way for higher order polynomials. However, whenever one can find one root, the problem can be reduced by polynomial division. – Eff Sep 3 '15 at 16:06
• Well, i didn't now that there was a closed form for 4th degree polynomial, nice to know :) What i simply referred was higher order polynomials as you stated. Then we can use some numeric methods, maybe newtons method. – Salihcyilmaz Sep 3 '15 at 16:10 | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9848109543125689,
"lm_q1q2_score": 0.8227933435214094,
"lm_q2_score": 0.8354835411997897,
"openwebmath_perplexity": 264.45204670060247,
"openwebmath_score": 0.9208398461341858,
"tags": null,
"url": "https://math.stackexchange.com/questions/1419460/a-more-scientific-way-to-factor"
} |
javascript, jquery, sqlite, cordova
Title: Nested SQLite transactions in jQuery I'm using Cordova with jQuery and jQuery Mobile to develop a hybrid app. In this app I need to save data that I get from a server.
The data is a JSON. I chose this SQLite plugin for Cordova to save the content in tables for easy access.
I make an AJAX-GET call to get the data I need and call the function below with the parameters: content is the JSON; myAction is a string(sync or update); upt is an integer(unix timestamp).
function syncQueries(content, myAction, upt){
//JSON
var uid = content.content[0].uid;
var name = content.content[0].name;
var now = Math.round(Date.now()/1000);
if (typeof content.content[0].kurzbeschreibung != 'undefined'){
var kurzbeschreibung = content.content[0].kurzbeschreibung;
}
if (typeof content.content[0].hauptkategorie != 'undefined'){
var parentID = content.content[0].hauptkategorie;
}
if (typeof content.content[0].unterkategorie != 'undefined'){
var parentID = content.content[0].unterkategorie;
}
if(content.content[0].beschreibung.match(/<img/)){
var beschreibung = findImgTag(content.content[0].beschreibung);
} else {
var beschreibung = content.content[0].beschreibung;
}
//sync data
if(myAction == 'update'){
db.transaction(function(tx){
if(content.content[0].tabelle == 'hauptkategorie'){ | {
"domain": "codereview.stackexchange",
"id": 14864,
"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, jquery, sqlite, cordova",
"url": null
} |
polymers, plastics
Title: Can Polyethylene Dissolve on 50-60 °C I know that polyethylene's melting point is between 115–135 °C, however I would like to know if can it start dissolving between 50-60 °C?
In a real example, if I put warm food (straight from the oven, I think it can be max. 50-60 °C) into a re-closable polyethylene plastic bag and close it, will any chemical reaction affect the food (from the polyethylene's side)? Or is polyethylene safe at that temperature, and if the bag is warm it doesn't mean that any chemical reaction is started? I didn't experienced any alteration, but I'm not an expert and don't know much about chemistry yet, so I would appreciate some guidance. There may be better answers forthcoming, but a chemical does not need to melt (i.e. be in the liquid phase) to be reactive. For example, your food very likely has some liquid component, and that could be enough to react with some solid. Now polyethylene is used all over the place and is very nonreactive in many non-rigorous situations (like food service), so you are probably just fine. But I wanted to make the more general point that you don't have to be a liquid or gas to be reactive. | {
"domain": "chemistry.stackexchange",
"id": 3659,
"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": "polymers, plastics",
"url": null
} |
particle-physics, astrophysics, resource-recommendations, cosmic-rays
Title: A good reference on cosmic ray? I am looking for a good reference on cosmic ray, both galactic and solar. Does anyone have any suggestion?
I'm looking for a reference that covers the production and propagation of cosmic rays in a rigorous way. It should target people that know about particle physics, but are ignorant about cosmic rays. Reinhard Schlickeiser's Cosmic Ray Astrophysics (Springer publisher link) is probably a good starting point for you. From the "about this textbook" in the link:
This book provides an exhaustive account of the origin and dynamics of cosmic rays.
It may be a little dated, having been printed in 2002 (pre-Fermi LAT), but it covers exactly what you want: the production & propagation of cosmic rays--it's been a while since I read it (having moved away from academia a few years ago), but I believe it covers galactic CRs (which ought to cover solar as well) and I think it does touch upon extra-galactic CRs.
I don't really recall it being particularly difficult with the maths beyond e.g. vector calculus. A background in astrophysics is probably useful, especially with radiative processes (i.e., having read/worked through Rybicki & Lightman). I don't think particle physics knowledge is needed in the book, but, again, it's been a while since I've needed to look at it. | {
"domain": "physics.stackexchange",
"id": 52947,
"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, astrophysics, resource-recommendations, cosmic-rays",
"url": null
} |
java
Solution to [(not x_0 or x_1) and not (x_1 or not x_2)] is:
{x_0=false, x_1=false, x_2=true}
As always, any critique is much appreciated. First note that in a CNF a clause cannot be negated. This is because a Clause ¬ (A ∨ B) is equal to ¬A ∧ ¬B. But let's ignore this and assume we're talking about a more lenient Formula instead.
Next your BinaryVariable could just as well be a normal String.
Replace all BinaryVariable with String and assign the variables as String var1 = "X_1" and it should still work.
Instead of doing that I suggest to actually put the assignment of the BinaryVariable inside the class. So add a boolean field and some methods and the class looks like this:
public final class BinaryVariable {
//note: removed redundant comment
private final int id;
//not static since the solver will change this assignment
private boolean assignment = false;
public BinaryVariable(int id) {
this.id = id;
}
public void setFalse(){
assignment = false;
}
public void setTrue(){
assignment = true;
}
public boolean isTrue(){
return assignment;
}
@Override
public int hashCode() {...}
@Override
public boolean equals(Object o) {...}
@Override
public String toString() {
return "x_" + id;
}
}
Instead of the methods setTrue() and setFalse() you can also use the method assign(boolean value). This works just as well.
Now your isSatisfied method in the Clause class can be changed to this:
public boolean isSatisfied() {
for (BinaryVariable binaryVariable : binaryVariableList) {
if (negatedBinaryVariableSet.contains(binaryVariable)) {
if (!binaryVariable.isTrue()) {
return !negated;
}
} else {
if (binaryVariable.isTrue()) {
return !negated;
}
}
}
return negated;
} | {
"domain": "codereview.stackexchange",
"id": 25008,
"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",
"url": null
} |
basic sine curve has a midline at the x-axis (y = 0). In order to sketch the curve of a function, you need to:. Computer-generated graph of y = x 2 /(x + 3) One of the interesting attributes of curve sketches is that the sketches we make by hand are rarely to scale and can grossly exaggerate features of. DUE TUESDAY FEBRUARY 16 AT THE BEGINNING OF CLASS. You can sketch a curve by listing down a range of values for x, calculating the values for y and from the points drawn on the graph, join the dots. Let’s put it all together; here are some general curve sketching rules: Find critical numbers (numbers that make the first derivative 0 or undefined). CURVE SKETCHING Curve Sketching Steps: for sketching the graph of f(x). Created by T. NOTES: There are now many tools for sketching functions (Mathcad, Scientific Notebook, graphics calculators, etc). 7 Curve Sketching. A full lesson on sketching cubics, quartics and reciprocal functions. And the goal here--STUDENT: [INAUDIBLE. Applet: Curve Sketching: Increasing/Decreasing Try it! The Second Derivative: Concavity and In ection Points Suppose y = f(x) is a given function. 6 # 1-3 SPICY 5. Curve Sketching Introduction Prior to learning calculus, you studied functions of various types, and you learned how to sketch their graphs with and without the support of a calculator. In my opinion, one of the more difficult topics in Extension 1 and 2 has got to be curve sketching. From the derivative's graph, identify the interval graph where f (the original function) is concave up. Polar curves: wrapping a function around the pole. Likes scottdave. Graphs reveal the behaviour of functions and are used for many purposes in mathematics, science and engineering. To zoom, use the zoom slider. This is a graph of the derivative of function h(x). Similarly, we set x = 0 to find the y- intercept. But some of the steps are closely related. (If f ˜˜x˚ ˚ f ˜x˚, the graph is symmetric with respect to the y-axis; if f ˜˜x˚ ˚˜f ˜x˚, the graph is symmetric with respect to the origin). C2 Sketching Trigonometric graphs (trigonometric graph shapes) Sketching graphs: | {
"domain": "curaben.it",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9910145712474399,
"lm_q1q2_score": 0.8500606980030403,
"lm_q2_score": 0.8577681122619883,
"openwebmath_perplexity": 1251.2958620737718,
"openwebmath_score": 0.5482892990112305,
"tags": null,
"url": "http://vurg.curaben.it/curve-sketching.html"
} |
javascript, object-oriented
App.animate = App.animate || {};
App.animate.init = function(){
setTimeout(function(){
App._elements.container._element.animate( { 'bottom' : '-265px' }, 200, function(){
App._elements.container._element.animate( { 'bottom' : '-270px' }, 50, function(){
App._elements.container._element.animate( { 'bottom' : '-265px' }, 50, function(){
App._elements.container._element.animate( { 'bottom' : '-270px' }, 50, function(){
App._elements.container._element.animate( { 'bottom' : '-265px' }, 50 );
});
});
});
});
}, 1500);
};
App.animate.show = function(){
App._elements.container._element.animate( { 'bottom' : '0' }, 50, function(){
App._elements.container._element.animate( { 'bottom' : '-50px' }, 50, function(){
App._elements.container._element.animate( { 'bottom' : '0' }, 50, function(){
App._elements.container._element.animate( { 'bottom' : '-20px' }, 50, function(){
App._elements.container._element.animate( { 'bottom' : '0' }, 50 );
});
});
});
}).addClass( 'active' );
}; | {
"domain": "codereview.stackexchange",
"id": 18707,
"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",
"url": null
} |
php, beginner, http
sprintf(
'Request to %s failed',
$url
)
);
$response = json_decode($answer);
$err = json_last_error();
if ($err !== \JSON_ERROR_NONE || !property_exists($response, 'documents'))
{
if ($err === \JSON_ERROR_NONE)
$msg = sprintf('%d - %s', $err, json_last_error_msg());
else
$msg = sprintf('documents not found in %s', json_encode($response));
throw new \RuntimeException($msg);
}
if (empty($response->documents))
return null;//return null if we reached the end
return $response->documents;
} | {
"domain": "codereview.stackexchange",
"id": 8510,
"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, beginner, http",
"url": null
} |
complexity-classes, randomized-algorithms
Proof: assume $\mathsf{RNC}\subseteq \mathsf{NTIME(2^{polylog})}$. If Permanent has a quasipolynomial size formula, then we can guess and verify such a formula for Permanent using a quasipolynomial time polynomial identity tester by assumption. This places Permanent in $\mathsf{NTIME(2^{polylog})}$.
By Toda's theorem, $\Sigma_2$ is then also in $\mathsf{NTIME(2^{polylog})}$. By padding, the linear-exponential time version of $\Sigma_5$ is also in $\mathsf{NEXP}$. Hence the linear-exponential version of $\Sigma_5$ has a circuit of size $o(2^n/n)$ (i.e. submax). But, by a simple diagonalization argument, one can show that the linear-exponential version of $\Sigma_5$ requires max circuit size, which is a contradiction (by the way, this is a variant of a mid-level question for a graduate-level complexity course; okay, maybe proving that $\mathsf{EXPSPACE}$ requires max-size circuits is a simpler one). QED.
Now the unpopular direction.
We already know that randomness read many times can do something non-obvious. An interesting example can be found in "Making Nondeterminism Unambiguous" by Reinhardt and Allender (they state it in terms of non-uniformity but in principle it is about using read-many-times randomness). Another interesting example (less directly related) is "Randomness Buys Depth for Approximate Counting" by Emanuele Viola. I guess all I'm saying is that I wouldn't be surprised if the derandomization of $\mathsf{RNC}$ is not what most people would expect it to be.
(There are also a couple of other papers, like Noam Nisan's wonderful paper on read-once vs. read-many randomness, that show how to buy two-sided error with one-sided error.) | {
"domain": "cstheory.stackexchange",
"id": 2173,
"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-classes, randomized-algorithms",
"url": null
} |
terminology, reductions
Title: Why "reduce to", not the other way around? This action confuses me for a while. As you know, once we come up with a problem and we want to know how hard it is, we will do the "reduction". Intuitively, if we prove problem B is as hard as problem A, we can know the complexity boundary of B. But if problem B is harder than A, why we call the reduction process -- reduce problem A to problem B, not reduce problem B to A? There are several different types of reduction, but generally, if we say we reduce problem A to problem B, it means something like: if we had a way to solve B, we could use that to solve A. Some reductions may allow to use B as a black box. Others might require that "yes" instances of A map to "yes" instances of B, and that "no" instances map as well. Or, it may be something simpler, like "hey, I already have a great solution to problem B, and now with just a simple transform, I can use it to solve problem A."
In all forms, it implies something related to "we could solve A if we had solutions to B".
What that means has something to do with what is known. If B is an easy problem to solve, then A reducing to B tells us that solving A is no harder than solving B, plus doing the reduction from A to B. In that case, an easy reduction, to an easy problem, proves that A is easy.
On the other hand, especially in the context of hardness results, we would usually reduce a known difficult problem (A here) to B, and that would show that, because A is hard, but transforming an instance of A into B is easy, B must also be hard, because if B were easy, it would give a solution to the known A problem.
So basically, for an easy reduction from A to B, it proves 2 things: A is not harder than B, and B is not easier than A. Yes, those are the same thing, but usually, you only care about one of them, depending on whether you know A to be difficult, or B to be easy. | {
"domain": "cs.stackexchange",
"id": 6958,
"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": "terminology, reductions",
"url": null
} |
ros, win-ros
Originally posted by Atlancer on ROS Answers with karma: 46 on 2016-03-23
Post score: 1
I was able to narrow down the problem: it appears that I was using the wrong headers (the ones for Boost 1.47 instead of Boost 1.56). More info (for anyone interested) can be found in my post on Stackoverflow here: http://stackoverflow.com/questions/36211108/how-to-read-demangled-symbols. To fix the problem I just copied all the headers from boost_1_56_0 folder to C:\opt\rosdeps\hydro\x64\include.
Update 1: Also, during the compilation I encountered the error in timer.cpp and wall_timer.cpp which indicated that conversion from ros::VoidConstPtr to bool was not possible. To fix the error I manually added an explicit cast to bool:
impl_->has_tracked_object_ = (bool) ops.tracked_object;
Then, I was finally able to compile everything.
Update 2: You also need to include boost_chrono-mt.dll into rosdeps/libs folder (just copy it there, no need to add it to any of the .CMake files). It turns out that boost_date_time-mt.dll depends on it at runtime. It will save you 10+ hours of debugging with Dependency Walker.
Originally posted by Atlancer with karma: 46 on 2016-03-24
This answer was ACCEPTED on the original site
Post score: 2 | {
"domain": "robotics.stackexchange",
"id": 24220,
"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, win-ros",
"url": null
} |
fluid-dynamics, pressure, bernoulli-equation
But the secondary effects are more interesting. In conductors, charge tends to pile up on the edge of the box: so the center of the box now has a much lower density, the outside has a much higher density, and so we roughly would expect that the added "push" of the system outwards manifests as a higher total pressure. Repulsive particle interactions increase pressure, attractive particle interactions reduce it. You can similarly imagine that the attractive interaction means that when you increase volume, you get a "bump" from kinetic energy but you have to "tear apart" the potential energy holding these guys together, if that helps you visualize why the force on the external world is weaker.
Finally, it's worth considering diatomic compounds like $O_2$. These things can be treated a lot like ideal gases, but they have an internal energy (rotational kinetic energy) which doesn't tend to contribute to the pressure. This is to encourage you to forget the fallacy "average internal energy per unit volume" or some such; it's a rate-of-change, not an average.
Example: van der Waals equation of state
Probably the most famous example of the effects of particle-interactions on pressure is the so-called van der Waals equation. This is a simple, early heuristic to capture the non-ideal effects of a changing volume and pressure on a real fluid. It turns out that it contains a liquid-gas phase transition at a certain temperature, so it is our first stop also when we want to introduce phase transitions to our students. Actual fluids have been fitted to the following equation for parameters $(a, b)$:$$
\left( p + a~\left(\frac {n}{V}\right)^2\right)~\big(V - b~n\big) = n~R~T. | {
"domain": "physics.stackexchange",
"id": 40016,
"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": "fluid-dynamics, pressure, bernoulli-equation",
"url": null
} |
c#, sql, sql-server, ado.net
sqlConnection.Open();
SqlTransaction sqlTrans = sqlConnection.BeginTransaction("Insert");
sqlCommand.Transaction = sqlTrans;
try
{
foreach (Earning earning in earningsList)
{
paramEmployeeID.Value = earning.EmployeeID;
paramWorDays.Value = earning.WorkDays;
paramDayOffs.Value = earning.DayOffs;
paramLeaveDays.Value = earning.LeaveDays;
paramAbsentDays.Value = earning.AbsentDays;
paramExtraShifts.Value = earning.ExtraShifts;
paramBasicSalary.Value = earning.BasicSalaryAmount;
paramBudjAllowance.Value = earning.BudjetoryAllowance;
paramNoPayDays.Value = earning.NoPayDays;
paramLessNoPay.Value = earning.LessNoPayAmount;
paramAmountForEPF.Value = earning.AmountForEPF;
paramOverTime.Value = earning.OverTimeAmount;
paramExtraShiftsAmount.Value = earning.ExtraShiftAmount;
paramIncentiveAllowance.Value = earning.IncentiveAllowance;
paramSpecialAllowance.Value = earning.SpecialAllowance;
paramOtherAllowance.Value = earning.OtherAllowance;
paramBFAmount.Value = earning.BroughtForwardAmount;
paramEpf.Value = earning.AmountForEPF / 100 * 8;
paramReference.Value = reference;
paramToDate.Value = toDate;
paramFromDate.Value = fromDate;
sqlCommand.ExecuteNonQuery();
}
sqlTrans.Commit();
return true;
}
catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }
sqlTrans.Rollback();
if (sqlConnection.State == System.Data.ConnectionState.Open) sqlConnection.Close();
return false;
}
}
} As this method is quite large, let's start digging through the code. | {
"domain": "codereview.stackexchange",
"id": 8810,
"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#, sql, sql-server, ado.net",
"url": null
} |
ros, ros2, colcon
dependencies are added using tags in package.xml. But for building the code, cmake's find_package() is used?
In order to be able to automate packaging as well as determine inter-package dependencies those need to be declared in a machine readable format. That is why they are present in the manifest files package.xml.
In CMake you need to find other packages. If the names of your build dependency names align perfectly with the names of the CMake config files you might be able to use convenience functions like ament_auto_find_build_dependencies. But in reality there are often mismatches between rosdep key names (the ones in the package.xml file) and the CMake config name. Therefore it is very common for them to be reiterated in CMake.
And what benefit is colcon build adding here, can't I just build the package using make?
Any ROS package (which in ROS 2 could any build system like CMake, Python setuptools, etc.) can be build using its native build tool. So yes, you can invoke just cmake && make && make install on a ROS package using CMake (even if it uses ament_cmake or in ROS 1 catkin).
The "problem" with this approach is scalability. First, if you want to build multiple packages you need to manually determine in which order you need to build them. Second, if you want to build more than one package it will require a lot of manual labor. Pretty much all colcon is doing for you is figuring out the dependency graph and invoke the necessary commands to build each package based on the build system it uses (while also leveraging parallelism where possible to speed up the process).
According to its package.xml file it requires - among others - the package camera_info_manager. How do I install it? Does ROS2 ship with a package manager that allows installation of package from remote source? | {
"domain": "robotics.stackexchange",
"id": 35464,
"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, colcon",
"url": null
} |
ros-kinetic, rosbridge
Title: How rosbridge finds custom messages?
I want to subscribe a custom message from a rosbridge server.
First I create a custom package and message by following the ROS official tutorial. Then build with catkin tool with catkin_make install. After source the .bash file I could successfully see my .msg through rosmsg show, or find my package though rospack find. However, when I use my client to request my custom message, it shows:
subscribe: Unable to import my_pack.msg from package my_pack. Caused by: No module named my_pack.msg
Note: I am using roslibpy as client side to connect to rosbridge server. Also Ubuntu 16.04 and ROS kinetic
I think my question would be: how rosbridge locates ROS packages? Should I add additional env var such that ROS bridge could find my package?
Originally posted by wthwlh on ROS Answers with karma: 26 on 2019-03-05
Post score: 0
Original comments
Comment by gvdhoorn on 2019-03-06:\
Should I add additional env var such that ROS bridge could find my package?
No, that should not be necessary.
Are you starting the rosapi_node? That is required for rosbridge to understand what msgs/srvs/actions exist.
Which launch file do you use to start rosbridge?
@gvdhoom Thanks for the reply, I have figured that out, it turns out I didn't source my setup.bash in that rosbridge server window...That is stupid...
Originally posted by wthwlh with karma: 26 on 2019-03-06
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by gvdhoorn on 2019-03-06:
Well .. that would certainly be required, yes. | {
"domain": "robotics.stackexchange",
"id": 32592,
"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-kinetic, rosbridge",
"url": null
} |
• This uses a rule I'd never heard of! rapidtables.com/math/algebra/Logarithm.htm#base switch – Dancrumb Oct 28 '15 at 16:25
• @Dancrumb Which rule are you talking of? – SchrodingersCat Oct 28 '15 at 16:32
• The one I linked to – Dancrumb Oct 28 '15 at 17:16
• In case the link doesn't work: The logarithm base switch rule. – Dancrumb Oct 28 '15 at 17:17
• Presumably $\log_a( b) = 1/ \log_b( a)$ which can be shown from $b^{\log_b(a) \log_a(b)} = \left(b^{\log_b(a)}\right)^{\log_a(b)} = a^{log_a(b)} = b$ so $\log_b(a) \log_a(b) = 1$ – Henry Oct 28 '15 at 21:01
HINT: use that $\log_2 50!=\frac{\ln(50!)}{\ln(2)}$ thus we get $$\frac{\ln(2)+\ln(3)+...+\ln(49)+\ln(50)}{\ln(50!)}=\frac{\ln(50!)}{\ln(50!)}=1$$
• Not complaining, but why did you call it a hint, when you gave the entire solution? – Paul Sinclair Oct 29 '15 at 0:49 | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9759464492044004,
"lm_q1q2_score": 0.8295263508090999,
"lm_q2_score": 0.8499711756575749,
"openwebmath_perplexity": 682.7309340284363,
"openwebmath_score": 0.7982543706893921,
"tags": null,
"url": "https://math.stackexchange.com/questions/1501800/summing-reciprocal-logs-of-different-bases"
} |
java, linked-list
Title: Optimizing twin() method Part III of this question says:
Fill in the twin() method in the SList class so that it performs as indicated
in the comment. Your solution should not use arrays.
Below is the solution written for the twin() method in 8 lines of code. Modular testing is done for the twin() method.
public class SList {
private SListNode head;
private int size;
/**
* SList() constructs an empty list.
**/
public SList() {
size = 0;
head = null;
}
/**
* isEmpty() indicates whether the list is empty.
* @return true if the list is empty, false otherwise.
**/
public boolean isEmpty() {
return size == 0;
}
/**
* length() returns the length of this list.
* @return the length of this list.
**/
public int length() {
return size;
}
/**
* insertFront() inserts item "obj" at the beginning of this list.
* @param obj the item to be inserted.
**/
public void insertFront(Object obj) {
head = new SListNode(obj, head);
size++;
}
/**
* insertEnd() inserts item "obj" at the end of this list.
* @param obj the item to be inserted.
**/
public void insertEnd(Object obj) {
if (head == null) {
head = new SListNode(obj);
} else {
SListNode node = head;
while (node.next != null) {
node = node.next;
}
node.next = new SListNode(obj);
}
size++;
}
/**
* nth() returns the item at the specified position. If position < 1 or
* position > this.length(), null is returned. Otherwise, the item at
* position "position" is returned. The list does not change.
* @param position the desired position, from 1 to length(), in the list.
* @return the item at the given position in the list.
**/
public Object nth(int position) {
SListNode currentNode; | {
"domain": "codereview.stackexchange",
"id": 10288,
"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, linked-list",
"url": null
} |
automata-theory, context-free
$\langle q_i, * \rangle, a, \langle A,= \rangle \to \langle q_j, * \rangle, \epsilon$
$\langle q_i, * \rangle, a, \langle A,B \rangle \to \langle q_j, B \rangle, \epsilon$
$\langle q_i, A \rangle, a, \langle \cdot,= \rangle \to \langle q_j, * \rangle, \epsilon$
$\langle q_i, A \rangle, a, \langle \cdot,B \rangle \to \langle q_j, B \rangle, \epsilon$
***ADDENDUM 2
The above proof could be highly simplified, because:
the PDA derived from the quadratic Greibach Normal form needs only one state (provided that the acceptance condition is the empty stack at the end of the input);
$P'$ could simply store the TOP of the stack in its internal state (there is no need to use $\Gamma' = \Gamma \times Gamma$
as soon as I have some free time I'll update the answer. | {
"domain": "cstheory.stackexchange",
"id": 4755,
"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": "automata-theory, context-free",
"url": null
} |
python, database, sqlite
if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
if os.path.isfile(backup_file):
That is:
if os.path.isfile(backup_file):
if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
You seem to be following PEP8 for the most part,
with few exceptions:
Don't put a space before parentheses, as in print (something)
Put two empty lines in front of function definitions | {
"domain": "codereview.stackexchange",
"id": 23480,
"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, database, sqlite",
"url": null
} |
lagrangian-formalism, momentum, hamiltonian-formalism, supersymmetry, sigma-models
Inflicting the partial derivatives I get the following result:$$\pi_{\psi^m}=\frac{\partial L}{\partial \dot{\psi}^m}=ig_{mj}\bar{\psi}^j\tag{6}$$$$\pi_{\bar{\psi}^m}=\frac{\partial L}{\partial \dot{\bar{\psi}}^m}=0\tag{7}$$So far I have the fermionic momenta correct. The issue arises when I try to compute the bosonic momentum:$$p_m=\frac{\partial L}{\partial \dot{\phi}^m}=g_{mj}\dot{\phi}^j+i\Gamma_{jkm}\bar{\psi}^j\psi^k\tag{8}$$Clearly there is an additional non vanishing term which makes $(8)$ differ from $(3)$. Alternatively, should we (leaving aside the fermionic momenta for a while) work with $(1)$ thinking that two such terms may cancel, we get:$$p_m=\frac{\partial L}{\partial \dot{\phi}^m}=g_{mj}\dot{\phi}^j+\frac{i}{2}\bigl(\partial_jg_{km}-\partial_kg_{jm}\bigr)\bar{\psi}^k\psi^j\tag{9}$$Again this is non vanishing term. Is the fermionic covariant derivative to be treated independent of $\dot{\phi}^m$ so that it is killed by the derivative operator $\frac{\partial}{\partial \dot{\phi}^m}$? Or is $(3)$ a typing error? Or is it something else? Kindly help out. | {
"domain": "physics.stackexchange",
"id": 46648,
"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": "lagrangian-formalism, momentum, hamiltonian-formalism, supersymmetry, sigma-models",
"url": null
} |
c++, performance, event-handling, windows, graphics
The Main Event: Optimizing GetPixel
At the core of your code's logic is a call to GetPixel to retrieve the current color value of a particular pixel on the screen. That is unfortunate if you're concerned about speed, because GetPixel is a very slow function, indeed. Why is it so slow? The above-linked documentation doesn't give much of a hint. In fact, this API has a dirty little secret: individual pixels cannot be directly manipulated by the graphics subsystem, so GetPixel (and its brother, SetPixel) have to simulate it, which makes an ostensibly simple, straightforward function call into an extremely slow operation. In addition to the usual overhead of a function call, parameter validation, and switching to and from kernel mode, the GetPixel function also has to create a temporary bitmap, copy the contents of the DC into that temporary bitmap, perform all necessary color-mapping, map the coordinates and locate the pixel, retrieve its color value, and then destroy the temporary bitmap. A lot of work for a single pixel!
The throughput of GetPixel is on the order of 100,000 pixels per second, which is usually fast enough. If you want to speed up drawing operations that involve the manipulation of multiple pixels, the general strategy is to minimize overhead by copying the DC's contents into a temporary device-independent bitmap (DIB) and then using pointer arithmetic on this DIB to access individual pixels. This gives you direct access to each pixel, and allows a throughput of millions or more pixels per second. The problem for you is that you cannot simply use a cached snapshot of the screen—you really do need to update it each time through the loop, which means that this strategy doesn't save you a whole lot in terms of overhead. But it'll still be slightly faster.
Here's an approximation of the code that would be required:
COLORREF FastGetPixel(DWORD x, DWORD y)
{
// Retrieve a device context for the screen.
const HDC hdcScreen = GetDC(NULL); | {
"domain": "codereview.stackexchange",
"id": 23717,
"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, event-handling, windows, graphics",
"url": null
} |
• Great - thanks for clearing that up! – Sjoseph May 30 '18 at 14:38
• Is it still classed as a conditional probability, if Baye's is not needed? – Sjoseph May 30 '18 at 14:50
• @Sjoseph Yes, it's a conditional probability, as is any probability of the form $P(\cdot |\cdot )$. – The Phenotype May 30 '18 at 14:57
• If the question was the same except we instead wanted to know was the probability of it being die 1, would it then be a baye's problem? – Sjoseph May 30 '18 at 15:08
• @Sjoseph Bayes theorem is used whenever you want to calculate $P(A|B)$, where $P(A|B)$ and $P(A\cap B)$ are "too difficult" to calculate directly and $P(B|A)$ is "easy", so you use the equation $P(A|B) = \frac{P(B|A)P(A)}{P(B)}$. This is exactly what happens in the scenario you are proposing. – The Phenotype May 30 '18 at 15:14
I would not use Bayes rule here.
To be found is $$P(A\mid B)=\frac{P(A\cap B)}{P(B)}$$
Now find $P(A\cap B)$ on base of $$P(A\cap B)=P(A\cap B\mid H)P(H)+P(A\cap B\mid T)P(T)$$
and also find $P(B)$ on base of $$P(B)=P(B\mid H)P(H)+P(B\mid T)P(T)$$ | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9728307668889048,
"lm_q1q2_score": 0.8042506727753405,
"lm_q2_score": 0.8267117983401363,
"openwebmath_perplexity": 381.89492401393494,
"openwebmath_score": 0.7663354873657227,
"tags": null,
"url": "https://math.stackexchange.com/questions/2801924/bayes-rule-conditional-probability-coin-toss-and-dice-roll"
} |
mercury
As for a YouTube video saying the highest point is "Mt. Hermes," that sounds dubious to me with respect to anything official (for one, mountains on other bodies are "montes" after the Latin, if they have a formal name). A search shows no one else is using this name.
Regarding "sea level," it's what Wikipedia said: You use a reference ellipsoid, usually. The reference ellipsoid is made usually by fitting many different limb profiles to an ellipsoid, and/or via a laser altimeter. The best fit is the ellipsoid. Any deviations from that would be topography. Mercury has plenty-enough data to make a reference ellipsoid, indeed you linked to one in the comments above. Once these are published in the scientific literature, assuming they are generally accepted, the International Astronomical Union makes that a standard and publishes it in various reports. They don't often update their standards, though I think the last one was in 2015. So, it would not reflect the latest you found.
Practically all resolved solar system bodies have a reference ellipsoid that's used and published. How good it is, though, is another question. Asteroids, given their highly irregular shapes, for example, that were imaged by flyby missions would generally have a much more poorly constrained ellipsoid than, say, Earth's moon that has been observed through telescopes for over 400 years, orbited by numerous spacecraft, has retroreflectors on it, and has >8 billion laser altimeter points from the Lunar Reconnaissance Orbiter Laser Altimeter. | {
"domain": "astronomy.stackexchange",
"id": 4979,
"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": "mercury",
"url": null
} |
gazebo-7, ros-indigo
So now it compiles (both gazebo and the sdformat). After that I download gazebo_ros_pkgs and compile it. I tried with both indigo-devel and kinetic-devel, since I am not sure which one to use for my setup, but in both cases I get the following errors when launching a launch file which worked on both Indigo+Gazebo2.2 and Indigo+Gazebo7 (from deb):
Error [Element.hh:336] Unable to find value for key[gravity]
[INFO] [WallTime: 1495147521.301791] [0.000000] Calling service /gazebo/spawn_urdf_model
Error [Element.cc:684] Missing element description for [gravity]
Service call failed: transport error completing service call: unable to receive data from sender, check sender's logs for details
Segmentation fault
Warning [parser.cc:438] Converting a deprecated SDF source[data-string].
Error [Converter.cc:127] Unable to convert from SDF version 1.6 to 1.5
Warning [parser.cc:438] Converting a deprecated SDF source[data-string].
Error [Converter.cc:127] Unable to convert from SDF version 1.6 to 1.5
Warning [parser.cc:438] Converting a deprecated SDF source[data-string].
Error [Converter.cc:127] Unable to convert from SDF version 1.6 to 1.5
Any pointers would be much appreciated, thanks! | {
"domain": "robotics.stackexchange",
"id": 4103,
"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": "gazebo-7, ros-indigo",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.