text stringlengths 49 10.4k | source dict |
|---|---|
homework-and-exercises, special-relativity, kinematics, inertial-frames, lorentz-symmetry
\tag{09}\label{eq09}
\end{equation}
equation proved by dividing equations \eqref{eq05a}, \eqref{eq05b} side by side and setting $\:\mathbf{u}\equiv \mathrm d\mathbf{x}/\mathrm d t\:$, $\:\mathbf{u'}\equiv \mathrm d\mathbf{x'}/\mathrm d t'$. | {
"domain": "physics.stackexchange",
"id": 51909,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework-and-exercises, special-relativity, kinematics, inertial-frames, lorentz-symmetry",
"url": null
} |
ros-kinetic
‘ 788935 -2362 -82’ is the first GPS coordinate in my rosbag file when I ran ‘ndt mapping’. I think I had followed all I need to do, but ‘ndt matching’ is not working. The ‘base_link’ is just following the ‘gps’ frame, and ‘gps’ frame is very far from pointcloud map. So it does not perform matching properly.
I had checked the ‘frame’ coordinates of moriyama quick start demo, and my custom environment. Every coordinates are same. The only difference is, the pointcloud map is just beyond the ‘map’ frame. Moriyama demo’s pointcloud map is displayed far from ‘map’ frame, actually on the GPS coordinates.
So I had tried to shift the pointcloud map to the GPS coordinates, just as moriyama demo does. Firstly, I had tried using ‘TF’ to shift it, but pointcloud map in pcd file seems to be registered on ‘map’ frame directly. So I couldn’t modify its position using ‘TF’. Second, I had checked source code and launch file of ‘points_map_loader’ and ‘ndt_mapping’. But I failed to find out how to do.
Is there any way to solve this problem??
Originally posted by ktk1501 on ROS Answers with karma: 11 on 2019-07-15
Post score: 1
Original comments
Comment by miku54 on 2022-12-13:
@gvdhoorn Hi, I have the same problem as you, can you please share the solution?
Comment by gvdhoorn on 2022-12-13:
I only edited the question, I did not post it.
Comment by miku54 on 2022-12-13:
Oh my God! Do you know the reason for this problem?
Comment by gvdhoorn on 2022-12-14:
No, I don't.
I'd recommend checking the answer below.
There are two things I recommend: | {
"domain": "robotics.stackexchange",
"id": 33422,
"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
} |
$\Phi$ is an injection of $\mathbb{Q}$ into $\mathbb{Z}$.
By the Cantor Schroder Theorem, there is a bijection between $\mathbb{Z}$ and $\mathbb{Q}$.
As bof mentioned, a nicer injection would be
$\Phi(q) = \begin{cases} 0 & \quad q = 0 \\ 1 & \quad q = 1 \\ -1 & \quad q = -1 \\ 2^m (2n + 1) & \quad q = \frac{m}{n} \text{ simplest form } \\ - 2^m(2n + 1) & \quad q = - \frac{m}{n} \text{ simplest form} \end{cases}$
• this is one of the most impressive and elegant answers i've seen on here, well done! – furashu Feb 1 '14 at 9:18
• Instead of using prime factorizations, you could just map the reduced fraction $\frac mn$ to the integer $2^m(2n+1)$ – bof Feb 1 '14 at 9:23
• @bof True. This would have saved me like ten minutes of typing. – William Feb 1 '14 at 9:27
• @William can you explain what bof said? what's the significance of that integer? – furashu Feb 1 '14 at 9:39
• @William oh i am checking it now, I just like to know where things coem from, to get a glimpse on peoples intuition and knowledge. – furashu Feb 1 '14 at 9:46
If you know that $\mathbb{Z}$ is countable, you know there is a bijection $\chi:\mathbb{N} \rightarrow \mathbb{Z}$. Hence, it is sufficient to find a bijection $\nu:\mathbb{Z} \rightarrow \mathbb{Q}$ since then $\chi \circ \nu$ is a bijection between $\mathbb{N}$ and $\mathbb{Q}$. | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9869795095031688,
"lm_q1q2_score": 0.8592616765465871,
"lm_q2_score": 0.8705972801594706,
"openwebmath_perplexity": 422.84460954533535,
"openwebmath_score": 0.844674825668335,
"tags": null,
"url": "https://math.stackexchange.com/questions/659302/how-to-prove-that-mathbbq-the-rationals-is-a-countable-set"
} |
performance, vba, excel
dTime = Timer
Call TurnOffCalc
Set StartCell = shFullYearData.Range("A1")
'Find Last Row and Column
LastRow = shFullYearData.Cells(shFullYearData.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = shFullYearData.Cells(StartCell.Row, shFullYearData.Columns.Count).End(xlToLeft).Column
shFullYearData.Activate
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).Select
PWSelection = shStartForm.Cells(1, 1).Value
shFullYearData.Range(shFullYearData.Cells(1, 1), shFullYearData.Cells(1, LastColumn)).AutoFilter
If PWSelection <> "All" Then
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).AutoFilter Field:=12, Criteria1:=PWSelection
End If
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).AutoFilter Field:=26, Criteria1:=">=1"
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).AutoFilter Field:=3, Operator:= _
xlFilterValues, Criteria2:=Array(0, "12/31/2019")
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).Sort Key1:=Range("G1"), Order1:=xlAscending, Header:=xlYes, Key2:=Range("B1"), Header:=xlYes | {
"domain": "codereview.stackexchange",
"id": 38990,
"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": "performance, vba, excel",
"url": null
} |
# Need Help With Simple Mathematical Sets Difference (Intersection) Problem
I'm having trouble with a seemingly simple problem in Math and I need some help with it. The problem states:
A hospital is doing a treatment research on 50 volunteers. Of those, some have had a few reactions: 12 have had headaches, 8 felt nausea and 4 had headaches and nausea. How many volunteers had headaches and not nausea? How many volunteers didn't feel neither (headache and nausea simultaneously)?
It's not a homework as I'm not in school anymore but studying by myself to try my country's equivalent of the SAT to get into college.
So, I know that my Universe (U) in this case is 50. I know the sets (let's say A and B) are A={12}, B={8} and A∩B={4}, so the number of volunteers that had only headaches exclusively is 8 (12 - 4 people that also had nausea) but i can't figure out the number of volunteers that haven't had neither.
I've tried putting together a simple equation to find the number: 12 volunteers that felt headache + 8 that felt nausea + x people that felt neither = 50 that will amount to x=30 volunteers but the book (without explaining why) says the correct answer is 34.
I've tried breaking the problem down by its inquiries, writing them one by one (which I won't do here to not extend the question) and it seems to be a simple thing, really, and that what I've done is correct.
Is the book wrong (unlikely)? Is my solution correct? How should I go about when solving this problem? | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9766692257588073,
"lm_q1q2_score": 0.8377557092057274,
"lm_q2_score": 0.8577681031721325,
"openwebmath_perplexity": 1113.4042548556235,
"openwebmath_score": 0.4290485382080078,
"tags": null,
"url": "https://math.stackexchange.com/questions/2709325/need-help-with-simple-mathematical-sets-difference-intersection-problem"
} |
c++, library, gui
gtk_widget_destroy(GTK_WIDGET(dialog));
while (g_main_context_iteration(NULL, false));
return selection;
}
} // namespace boxer
boxer_osx.mm
#include <boxer/boxer.h>
#import <Cocoa/Cocoa.h>
namespace boxer {
namespace {
NSString* const OK_STR = @"OK";
NSString* const CANCEL_STR = @"Cancel";
NSString* const YES_STR = @"Yes";
NSString* const NO_STR = @"No";
NSAlertStyle getAlertStyle(Style style) {
switch (style) {
case Style::Info:
return NSInformationalAlertStyle;
case Style::Warning:
return NSWarningAlertStyle;
case Style::Error:
return NSCriticalAlertStyle;
case Style::Question:
return NSWarningAlertStyle;
default:
return NSInformationalAlertStyle;
}
}
void setButtons(NSAlert *alert, Buttons buttons) {
switch (buttons) {
case Buttons::OK:
[alert addButtonWithTitle:OK_STR];
break;
case Buttons::OKCancel:
[alert addButtonWithTitle:OK_STR];
[alert addButtonWithTitle:CANCEL_STR];
break;
case Buttons::YesNo:
[alert addButtonWithTitle:YES_STR];
[alert addButtonWithTitle:NO_STR];
break;
default:
[alert addButtonWithTitle:OK_STR];
}
} | {
"domain": "codereview.stackexchange",
"id": 14493,
"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++, library, gui",
"url": null
} |
filters, transfer-function
Title: Recursive filter with repeated poles This post follows this previous resolved post where I was trying to find the inverse Z-transform of a more simple filter output (that I used as an example to get the methodology). The present filter implements an additional integrator and I tried to use the same method. The problem is, I am not sure about how to deal with repeated poles. | {
"domain": "dsp.stackexchange",
"id": 6973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "filters, transfer-function",
"url": null
} |
classical-mechanics, rotational-dynamics, rigid-body-dynamics, angular-velocity, constrained-dynamics
$$
$$
\left( \vec{x}_{i}-\vec{x}_{j}\right)\cdot\left(\dot{\vec{x}_{i}}-\dot{\vec{x}_{j}}\right) + \left( \vec{x}_{i}-\vec{x}_{j}\right)\cdot\left(\dot{\vec{x}_{j}}-\dot{\vec{x}_{k}}\right) + \left( \vec{x}_{j}-\vec{x}_{k}\right)\cdot\left(\dot{\vec{x}_{i}}-\dot{\vec{x}_{j}}\right) + \left( \vec{x}_{j}-\vec{x}_{k}\right)\cdot\left(\dot{\vec{x}_{j}}-\dot{\vec{x}_{k}}\right) = 0
$$
$$
0 + \left( \vec{x}_{i}-\vec{x}_{j}\right)\cdot\left(\dot{\vec{x}_{j}}-\dot{\vec{x}_{k}}\right) + \left( \vec{x}_{j}-\vec{x}_{k}\right)\cdot\left(\dot{\vec{x}_{i}}-\dot{\vec{x}_{j}}\right) + 0 = 0
$$
$$ | {
"domain": "physics.stackexchange",
"id": 99067,
"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": "classical-mechanics, rotational-dynamics, rigid-body-dynamics, angular-velocity, constrained-dynamics",
"url": null
} |
ros, moveit, kuka, ros-industrial
<!-- If database loading was enabled, start mongodb as well -->
<include file="$(find kuka_moveit_roof)/launch/default_warehouse_db.launch" if="$(arg db)">
<arg name="moveit_warehouse_database_path" value="$(arg db_path)"/>
</include>
</launch> | {
"domain": "robotics.stackexchange",
"id": 36238,
"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, kuka, ros-industrial",
"url": null
} |
cc.complexity-theory, np-hardness
Title: How hard is deciding the existence of Red-Blue perfect matching? Two-colorable perfect matching problem is to decide whether a graph has coloring with two colors such that each node has exactly one neighbor the same color as itself. The problem was proven to be NP-complete by Schaefer. It remains NP-complete even for planar cubic graphs.
I am interested in a variant where we want to decide whether input graph has coloring with two colors such each node has exactly one neighbor colored differently from itself. I call this Red-Blue perfect matching problem. I don't know whether this is a known problem.
How hard is deciding the existence of Red-Blue perfect matching? As Mikhail noted, the problem was called Perfect Matching Cut in literatures. It was proved to be NP-complete in the following paper (see Theorem 1 on page 5), with a reduction from monotone 1-in-3-SAT:
Pinar Heggernes, Jan Arne Telle. Partitioning Graphs Into Generalized Dominating Sets. | {
"domain": "cstheory.stackexchange",
"id": 4653,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "cc.complexity-theory, np-hardness",
"url": null
} |
ubuntu-trusty, ubuntu, ros-indigo
Title: How to install Indiago ROS in Ubuntu14.04.4 (trusty LTS)?
Hi All:
I am new about ROS but middle in linux.
Here is one problem that encountered during the installation of Indiago ROS.
The main steps of installation are following the offical site as shown below:
http://wiki.ros.org/indigo/Installation/Ubuntu
First , I tried to install Indiago-desktop-full by typing the following commands below:
sudo apt-get install ros-indigo-desktop-full
which shows the following messages:
paultsai@paultsai-VirtualBox:~$ sudo apt-get install ros-indigo-desktop-full
[sudo] password for paultsai:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
ros-indigo-desktop-full : Depends: ros-indigo-desktop but it is not going to be installed
Depends: ros-indigo-perception but it is not going to be installed
Depends: ros-indigo-simulators but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
In order to fix the dependency issues, I tries to first install ros-indigo-desktop by typing the following commands
paultsai@paultsai-VirtualBox:~$ sudo apt-get install ros-indigo-desktop
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
ros-indigo-desktop : Depends: ros-indigo-common-tutorials but it is not going to be installed
Depends: ros-indigo-geometry-tutorials but it is not going to be installed | {
"domain": "robotics.stackexchange",
"id": 26051,
"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": "ubuntu-trusty, ubuntu, ros-indigo",
"url": null
} |
# Exponential Distribution and Expected Times
Suppose two people A,B are assigned to do an individual task and then a group task.
Person A completes his individual task on average around 30 minutes. Person B completes his individual task on average around 40 minutes. After a person completes his individual task, he will move on to the group task. The group task can be completed alone by either A or B on average around 1 hour. The group task can be completed together on average around 30 minutes.
What is the expected time to finish all tasks?
My attempt: I know that it should be a max time it takes for the individual tasks to be done + additional time to finish group task.
I would have
E(max(A,B)) + E(T) where A is time it takes A for his own task and B is time it takes for his own task. The trouble I am having is conditioning on T, which is additional time to do the group task after all individual tasks have been finished.
I know that if can be broken up into two cases and further into two mini-cases:
Case 1: A>B Our time will be A if A > B + T. Our time will be A + T if A < B + T.
Case 2: B>A Our time will be B if A > B + T. Our time will be B + T if A < B + T.
I am not sure how to represent E(T) from here. Intuitively, seems like E(T) could be (0 + Average Time it Takes to Complete Group Task Together) divided by 2, so E(T) = 15 minutes.
Hence my answer would be E(max(A,B)) + E(T) = E(A+B-min(A,B)) + E(T) = 30 + 40 - 120/7 + 15 = 475/7 minutes.
Is my reasoning correct?
It depends on the distribution of times. You have used the words "Exponential distribution" in the title, so let's suppose that the times are distributed that way and use the memoryless property.
Person A works at a rate of $2$ per hour and person B at a rate of $1.5$ per hour on their individual tasks. Individually they work on the group task at a rate of $1$ per hour and together at a rate of $2$ per hour. | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9865717460476701,
"lm_q1q2_score": 0.8133908379999517,
"lm_q2_score": 0.8244619220634457,
"openwebmath_perplexity": 341.23228260546483,
"openwebmath_score": 0.7568016052246094,
"tags": null,
"url": "https://math.stackexchange.com/questions/1187929/exponential-distribution-and-expected-times"
} |
gazebo, urdf, ros-kinetic
</link>
<joint name="panda_joint6" type="revolute">
<safety_controller k_position="100.0" k_velocity="40.0" soft_lower_limit="-0.0175" soft_upper_limit="3.7525" />
<origin rpy="1.57079632679 0 0" xyz="0 0 0" />
<parent link="panda_link5" />
<child link="panda_link6" />
<axis xyz="0 0 1" />
<dynamics damping="0"/>
<dynamics friction="0"/>
<limit effort="12" lower="-0.0175" upper="3.7525" velocity="2.6100" />
</joint>
<link name="panda_link7">
<visual>
<geometry>
<mesh filename="package://franka_description/meshes/visual/link7.dae" />
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="package://franka_description/meshes/collision/link7.stl" />
</geometry>
</collision>
<inertial>
<mass value="0.1" />
<inertia ixx="0.03" iyy="0.03" izz="0.03" ixy="0.0" ixz="0.0" iyz="0.0" />
</inertial> | {
"domain": "robotics.stackexchange",
"id": 32092,
"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, urdf, ros-kinetic",
"url": null
} |
python, python-3.x, interview-questions, pandas, natural-language-processing
def main():
# Amount of max words in key-word
number_grams = 3
number_top_keywords = 20
save_file = open(sys.argv[1], 'a')
# Reading in the minimum data
script = open(sys.argv[2], "r").read()
total_trans = open(sys.argv[3], "r").read()
names_trans = [str(sys.argv[3]) + "\n"]
# Reading in optional extra transcripts
for tran in sys.argv[4:]:
total_trans += open(tran, "r").read()
names_trans.append(str(tran) + "\n")
# Processing text from the script and group key-words in script dataframe
script_data = ngrams_to_strings(get_n_grams(text_process(script), number_grams))
script_df = group_in_dataframe(script_data, "Main script")
# Taking the top n words from the script dataframe
script_df_top = script_df.head(number_top_keywords)
# Processing text from all the transcripts and group key-words in a dataframe
total_trans_data = ngrams_to_strings(get_n_grams(text_process(total_trans), number_grams))
total_trans_df = group_in_dataframe(total_trans_data, "Transcripts")
# Merge script dataframe and transcripts dataframe into one
script_trans_df = pd.concat([script_df_top, total_trans_df], axis=1, join="inner")
# Sort merged dataframe to appearance in transcipts
script_trans_df = script_trans_df.sort_values("Transcripts", ascending=False) | {
"domain": "codereview.stackexchange",
"id": 25974,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, interview-questions, pandas, natural-language-processing",
"url": null
} |
quantum-mechanics, wavefunction, schroedinger-equation, linear-algebra, quantum-states
Title: Why is the Schrödinger Equation valid for the component functions (wave function) of state vectors? I'm new to quantum mechanics and confused about the way the Schrödinger equation is used (more general eigenvalue equations of observables).
Let's take the time-independent Schrödinger equation (eigenvalue equation).
Suppose our system is n+1 dimensional and the eigenvectors of our hamiltonian (or any other observable) are $|x_i\rangle $ with eigenvalue $x_i$. A state vector takes the form: $|\psi\rangle = \sum_{i=0}^n \phi(x_i)|x_i\rangle$ with component/(wave) functionf $\phi(x_i) = \langle x_i | \psi \rangle$. The time-independent Schrödinger equation (or eigenvalue equation for any observable) reads:
$$ \hat{H} |x_i \rangle = x_i |x_i \rangle $$
This is an eigenvalue equation for a $\mathbf{\text{state vector}}$.
My confusion is why that equation should also hold for the component (wave) function. Ie why is:
$$ \hat{H} \phi(x_i) = x_i \phi(x_i) $$ true?
Thanks in advance!
Cheers,
Thomas
EDIT:
I think it is only valid, if the Hamilton operator (or the observable) is itself expressed in the $|x_i\rangle$ basis (it then becomes a matrix (at least in the finite dimensional case). Even though I never saw that spelled out... So one should better write:
$$ \hat{H}_{|x_i\rangle} \phi(x_i) = x_i \phi(x_i) $$ In standard bra-ket notation, one could write | {
"domain": "physics.stackexchange",
"id": 88472,
"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, wavefunction, schroedinger-equation, linear-algebra, quantum-states",
"url": null
} |
reinforcement-learning
is selecting neurons even a thing for RL, can we just give it a max possible number of neurons and layers, letting it learn correct movement of creature's limbs?
Generalization is an issue, large number of neurons can overfit (not generalize well) DQN involves neural network in order to allow generalization. The ability of the neural network to generalize to new cases (and new experiments/environments) depends on the approximation that the neural network provides which depends on the neural networks parameters and hyper-parameters.
For building a huge neural network : as a concept you can increase the depth of the neural network to get better results. However, the question is do you have enough data? in RL language, you need more different examples for the larger network to train. Theoretically, having infinite neural networks with infinite number of different experiments/environments will lead to the best results. however, we are not patient enough to wait for very long training time and most probably you don't have large number of different environments/experiments to teach the neural network. hence the standard way to do this is by starting with a small network (few neurons and 1 or 2 layers) and train it then expand it gradually step by step and stop when the network can't generalize well.
you can think of the size of the neural network as a water tank as long you have large amounts of water(experiments) you need larger tank to occupy it. A large network without sufficient number of learning experiments leads to worse results specially when the the agent face new unseen experiments.
:[1] https://web.stanford.edu/class/psych209/Readings/MnihEtAlHassibis15NatureControlDeepRL.pdf
:[2] https://www.semanticscholar.org/paper/Virtual-to-real-deep-reinforcement-learning%3A-of-for-Tai-Paolo/494af0cedf1abb2454d457d0a89e21b983233276
:[3] https://arxiv.org/pdf/1612.05533.pdf | {
"domain": "datascience.stackexchange",
"id": 3250,
"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": "reinforcement-learning",
"url": null
} |
c++, beginner, algorithm, recursion, combinatorics
That avoids the need to check the length and allows you to take non-null-terminated strings. It make the function faster and more flexible to use.
if(pos==length) f_out << word << std::endl;
Never use std::endl. It is basically always wrong. In this case, it should be:
if(pos==length) f_out << word << '\n';
But if you've refactored the function to take a pointer and a size (and thus, non-null-terminated strings), you would have to use:
if(pos==length) f_out.write(word, length) << '\n';
or:
if(pos==length) f_out.write(word, length).put('\n');
Down to main().
You never confirm that the file actually opened. You can either test is_open(), the fail bit, or you can set stream exceptions before trying to open it.
char* word;
int min=2, max=4;
Don't declare variables until they're needed. word is not needed until 5 lines later... and technically not even then.
Don't declare multiple variables on a single line. That causes all kinds of headaches with syntactic quirks, and makes it harder to see where variables come from.
I would also recommend that min and max be constexpr. You should also assert that max >= min, for safety.
If we remove word (because it's unnecessary), your main loop looks like this:
for(int i=min; i<=max; i++) {
char* buffor = new char[i+1];
for(int x=0; x<i; buffor[x]='a', x++);
buffor[i]='\0';
gen(f_out, buffor);
delete [] buffor;
} | {
"domain": "codereview.stackexchange",
"id": 30954,
"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, algorithm, recursion, combinatorics",
"url": null
} |
mobile-robot, navigation
When using this algorithm, records are kept of the explored coordinates and uploaded to a shared database. However, there are some cases, that I did not consider:
- When should it move down?
- What if the goal is not reachable from a coordinate directly above it?
- If no horizontal move in any direction is possible, how long should it backtrack?
- How to detect unreachable goals (obstacles can then be removed if requested)
Maybe if enough exploration data of the area is available, a Jump Point Search is performed to calculate an optimal path. However this assumes a 2D map. How can I take the 3rd dimension into account?
Also, what would be a good data structure to store the exploration data? What comes to my mind first is some sort of bug algorithm. That is a path finding algorithm that has only small constant amount of memory and only sees (small) local parts of the world.
You can imagine this as
Go directly to the goal
If there is an obstacle in a way, pick a direction and start going around it
Once there is a free path again, goto 1
Of cause there are some problems with this, I'm not entirely sure that this will work in 3D. Selecting a way around an obstacle will be a little trickier than just saying "always go right".
Other than that, this algorithm can select a wrong direction and spend a long time going around the obstacle which it could avoid easily by going other way around it.
These slides might help you with some of the details. | {
"domain": "robotics.stackexchange",
"id": 286,
"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": "mobile-robot, navigation",
"url": null
} |
neural-networks, deep-learning, convolutional-neural-networks, long-short-term-memory, gpu
Title: How do GPUs faciliate the training of a Deep Learning Architecture? I would love to know in detail, how exactly GPUs help, in technical terms, in training the deep learning models.
To my understanding, GPUs help in performing independent tasks simultaneously to improve the speed. For example, in calculation of the output through CNN, all the additions are done simultaneously, and hence improves the speed.
But, what exactly happens in a basic neural network or in a LSTM type complex models in regard with GPU. GPUs are able to execute a huge amount of similar and simple instructions (floating point operations like addition and multiplication) in parallel. In contrast to a CPU which is able to execute a few complex tasks sequentially very quick. Therefore GPUs are very good at doing vector & matrix operations.
If you look at the operations performed inside a single basic NN layer you will see that most of the operations are matrix-vector multiplications:
$$x_{i+1} = \sigma(W_ix_i + b_i)$$
where $x_i$ is the input vector, $W_i$ the matrix of weights, $b_i$ the bias vector in the $i^{th}$ layer, $x_{i+1}$ the output vector and $\sigma(\cdot)$ the elemtwise non-linear activation. The computational complexity here is governed by the matrix-vector multiplication. If you look at the architecture of a LSTM cell you will notice that inside of it are multiple such operations.
Being able to execute the matrix-vector operations quickly and efficiently in parallel will reduce execution time, this is where GPUs excel CPUs. | {
"domain": "ai.stackexchange",
"id": 2078,
"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": "neural-networks, deep-learning, convolutional-neural-networks, long-short-term-memory, gpu",
"url": null
} |
quantum-mechanics, homework-and-exercises, angular-momentum, quantum-spin, hydrogen
In the following, I will assume that $L$ and $S$ are fixed and I will not write $L$ and $S$ explicitly. The value of $J$ will depend on the relative orientation of $\vec L$ and $\vec S$. There are two possibilities: $J = L+1/2$ and $J = L - 1/2$.
There are two ways to label the states of the system. We can use the labels of total angular momentum $J, m_j$ or we can use the labels of the z angular momentum for $L$ and $S$, $m_\ell, m_s$. Since $J$ is the sum of $L$ and $S$, $m_j = m_\ell + m_s$. Since $S = 1/2$, $m_s = \pm 1/2$.
The total Hilbert space has dimension $2 (2 L + 1)$. But this is divided into 2-dimensional subspaces that do not mix with one another. A typical subspace contains the states
$$ | J = L+{1\over 2}, m_j\rangle \qquad | J = L - {1\over 2}, m_j\rangle $$
or, in the $m_\ell, m_s$ basis,
$$ | m_j-{1\over 2}, +{1\over 2}\rangle \qquad | m_j + {1\over 2}, -{1\over 2}\rangle \ . $$
These pairs of states give two different orthogonal bases for the same Hilbert space. They are related by a unitary transformation. The Clebsch-Gordan coefficients are defined to be the elements of this $2\times 2$ unitary matrix. Clebsch-Gordan coefficients can be written $c_{m_j,+}$, etc., as in the question, but it is much more transparent to write them as explicitly indicating this change of basis, | {
"domain": "physics.stackexchange",
"id": 80832,
"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, angular-momentum, quantum-spin, hydrogen",
"url": null
} |
moveit
</launch>
ur_common.launch:
<launch>
<!-- robot_ip: IP-address of the robot's socket-messaging server -->
<arg name="robot_ip" />
<arg name="port" />
<arg name="min_payload" />
<arg name="max_payload" />
<arg name="prefix" default="" />
<arg name="servoj_time" default="0.008" />
<arg name="base_frame" default="$(arg prefix)base" />
<arg name="tool_frame" default="$(arg prefix)tool0_controller" />
<!-- The max_velocity parameter is only used for debugging in the ur_driver. It's not related to actual velocity limits -->
<arg name="max_velocity" default="10.0"/> <!-- [rad/s] -->
<node name="$(arg prefix)robot_state_publisher" pkg="robot_state_publisher" type="robot_state_publisher" >
<remap from="joint_states" to="$(arg prefix)joint_states"/>
</node> | {
"domain": "robotics.stackexchange",
"id": 29125,
"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": "moveit",
"url": null
} |
java, game, swing
/** Draw the game's graphics.
*
* @param g
*/
private void render(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
if (gameState == INTRO) {
//Background
g2.setPaint(new GradientPaint(0, 0, new Color(213, 213, 255), 0, 600, Color.WHITE));
g2.fillRect(0, 0, 800, 600);
g2.setFont(new Font("Tahoma", Font.BOLD, 50));
g2.setColor(new Color(0, 0, 0, introTextOpacity));
drawCenteredString("Made by Dan95363", 400, 250, g2);
} else if (gameState == MAIN_MENU) {
if (showIntro) {
//Instructions
g2.setFont(new Font("Tahoma", Font.BOLD, 20));
g2.setColor(Color.BLACK);
drawString("You are the red square. Avoid the blue circles and collect the\n" +
"yellow circles. Once you have collected all of the yellow\n" +
"circles, move to the green beacon to complete the level.\n" +
"Some levels consist of more than one beacon; the\n" +
"intermediary beacons act as checkpoints. You must complete\n" +
"all 30 levels in order to submit your score. Your score is a\n" +
"reflection of how many times you have died; the less, the better.", 30, 40, g2);
g2.setColor(Color.BLUE);
drawCenteredString("Press enter to continue", 400, 350, g2);
} else {
//Background
g2.setPaint(new GradientPaint(0, 0, new Color(213, 213, 255), 0, 600, Color.WHITE));
g2.fillRect(0, 0, 800, 600); | {
"domain": "codereview.stackexchange",
"id": 21888,
"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, game, swing",
"url": null
} |
discrete-signals, fourier-transform, continuous-signals, dsp-core, self-study
Title: Mathematically Inclined Signal and Systems / Signal Processing Book Recommendations I'm an electronics engineering student with high inclination to analysis and pure mathematics. I was just wondering if there was any book ( or any resource ) that treats signal and systems and signal processing with a lot of mathematics rigour ( actually doing proper complex analysis, using functional analysis and linear algebra rigorously to explain convolution, fourier, laplace and z transforms for example ).
I'm very disapointed with the books i've read ( Oppenhein, Lathi and related ) because it actually throws a lot of the beauty of analysis and algebra away, focusing on the computational side.
Thanks a lot Oppenheim and Willsky's Signals and Systems or Lathi's Linear Systems and Signals are intended for Sophomores who have only a single semester of differential equations under their belts, so it is a bit unfair to criticize them for leaving out the functional analysis and the conformal mapping. At the sophomore level my favorite book is Siebert's Circuits, Signals, and Systems. It won't give you the mathematical rigor you desire either, but you can see his great love for the mathematics and he has these wonderful, witty, footnotes that provide a great historical perspective.
There is a great book (which I love, but do not recommend to you) by the (applied) mathematician Richard Hamming (of the "Hamming window", "Hamming code", "Hamming distance", "Hamming bound" and "Hamming problem") called Digital Filters. In it he makes a number of snarky comments like:
Since we are interested mainly in using mathematics, we are obliged in our turn to be ambiguous with respect to mathematical rigor. Those who believe that mathematical rigor justifies the use of mathematics in applications are referred to Lighthill and Papoulis for rigor; those who believe that it is the usefulness in practice that justifies the mathematics are referred to the rest of this book. (1998 Dover edition, page 72.)
So in addition to the book by Papoulis that @Matt_L recommended I will add Hamming's (and Siebert's!) recommendation of M.J. Lighthill, Fourier Analysis and Generalized Functions, Cambridge University Press, 1958. | {
"domain": "dsp.stackexchange",
"id": 935,
"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": "discrete-signals, fourier-transform, continuous-signals, dsp-core, self-study",
"url": null
} |
electromagnetism, electricity
Title: Why electric generators in turbojet engine always need reduction gearing? The rotor of the turbojet engine is rotating with average speeds from 15 000 to 150 000 rpms, depending on size.
Why reduction gearing is used to drive the generator? Why it is not common, or probably inpractical, to use permament magnets mounted on the shaft and rotating with such speed, and stationary coils? This would probably save some lossed in reduction gears?
I think there is some fundamental obstacle to gearless solution, e.g. back-EMF rising sharply at higher RPMs. Correct me if I'm wrong.
Thank you! A generator's AC output frequency is a small-integer multiple of the
rotation rate. High rotation rates for generators are avoided because efficient magnetic materials (iron, basically) have AC
losses related to electrical conductivity (eddy currents). At frequencies of
50 Hz-1 kHz they are efficient and make lightweight high-power-output
generators and motors. From 1 kHz up to 20 kHz they are usable if
some care is taken in construction (iron in thin laminations
with insulation between sheets).
At frequencies below 50 Hz, the usual issue is the effectiveness of the
copper wiring, which has to be made thin (but with insulation around it).
Thin wires are prone to breakage, and the insulation thickness starts
to crowd out the copper, which means the electrical resistance of the
copper (in a given winding throat) becomes too high for efficiency.
Traditionally, 400 Hz was deemed
the 'sweet spot' for aircraft transformers, motors, generators.
Permanent magnet rotors can be OK at higher frequency, but only in
conjunction with a soft magnetic material for the stator; the magnetic
field in the output coils MUST change, or no generation of current takes
place. Iron-based magnetic materials are still the limiting factor.
Ferrite (magnetic oxides) can go to higher frequency without losses
due to electrical conduction, being nonconductive. The magnetization
of ferrites is, however, inferior to that of iron. Generators are also possible without soft magnetic materials, and with superconducting coils are efficient
and lightweight, but there are reliability issues with cooling. | {
"domain": "physics.stackexchange",
"id": 35880,
"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, electricity",
"url": null
} |
I recommend using a binary search in range $$0 \le \theta_r \le \frac{2 \pi}{n}$$as there is only one zero for $$f(\theta_r) = \cos\left((n-1)\frac{\theta_r}{2}\right) - \frac{2 R_b}{R_g - R_b}\sin\left(\frac{\theta_r}{2}\right) + 1$$ If $$f(\theta_r) \lt 0$$, $$\theta_r$$ is too large; if $$f(\theta_r) \gt 0$$, $$\theta_r$$ is too small.
(The upper limit applies if $$R_b = 0$$, as then the red circles form a closed ring of circles.)
For neighboring red circles to touch, $$R_r = (R_g - R_r) \sin\left(\frac{\theta_r}{2}\right) \quad \iff \quad R_r = R_g \frac{\sin(\theta_r/2)}{1 + \sin(\theta_r/2)}$$
Here is a verified Python implementation, that returns $$R_r$$ and $$\theta_r$$ as a tuple:
from math import pi, atan2, sin, cos
def find_r_theta(rG, rB, n):
n = round(n)
if n < 1:
raise ValueError("N must be at least 1, %s given" % n)
if n == 1:
return (rG - rB, 0)
if n == 2:
rR = 4*rG*rB*(rG-rB)/(rG+rB)**2
return (rR, 2*atan2(rR, rG*(3*rB-rG)/(rG+rB))) | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9908743618023695,
"lm_q1q2_score": 0.8235583329686691,
"lm_q2_score": 0.8311430436757312,
"openwebmath_perplexity": 2756.0255479970806,
"openwebmath_score": 0.9937154650688171,
"tags": null,
"url": "https://math.stackexchange.com/questions/4022525/placing-n-equally-sized-circles-and-one-larger-circle-inside-the-circumference-o"
} |
c#, regex
var again = RegexHelpers.StripHtmlAttributes(remove);
var tt = again;
public static string StripHtmlAttributes(string s)
{
const string pattern = @"\s.+?=[""'].+?[""']";
var result = Regex.Replace(s, pattern, string.Empty);
return result;
} You could simplify the declaration of the tags you want to keep, as it is very structured:
var whitelist = new List<string>(new string[] { "p", "h1", "br" });
foreach (var w in whitelist) {
txt = txt.Replace("<" + w + ">", "<" + w + ">")
.Replace("<" + w + "/>", "<" + w + "/>"));
}
var remove = Sanitizer.GetSafeHtmlFragment(txt);
foreach (var w in whitelist) {
remove = remove.Replace("<" + w + ">", "<" + w + ">")
.Replace("<" + w + "/>", "<" + w + "/>"));
}
var again = RegexHelpers.StripHtmlAttributes(remove);
var tt = again; | {
"domain": "codereview.stackexchange",
"id": 6008,
"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#, regex",
"url": null
} |
string-theory, renormalization
Now, if I apply the Bianchi identities to the first two terms of $\nabla^\mu\beta^G_{\mu\nu}$, apparently the last equality holds if $R_{\mu\nu}\nabla^\mu \phi = 0$, which does not seem to me to hold in general. What am I missing? The terms in $\nabla^\mu \beta^G_{\mu\nu} $ which are not related to the Bianchi identities you discussed are
$$- \frac{1}{4} \nabla^\mu\left(H_{\mu\rho\lambda}\right)H_{\nu}^{\ \rho\lambda} + 2\nabla^2 \nabla_\nu \phi = -2\nabla^\mu \phi\left(R_{\mu\nu}+2\nabla_\mu\nabla_\nu \phi \right)+2\nabla^2 \nabla_\nu \phi $$
where the second equality follows from using both $\beta^B=\beta^G=0$.
As long as there is no torsion $\nabla_\mu\nabla_\nu\phi=\nabla_\nu\nabla_\mu\phi$, so the second term above can be written as $-2\nabla_\nu \left(\nabla\phi\right)^2$ which is one of the terms you are looking for. Although you didn't show it explicitly, it sounds like you did all this already and the remaining problematic terms are
$$-2R_{\mu\nu}\nabla^\mu \phi+2\nabla^2 \nabla_\nu \phi$$
The second term looks like one of the terms you need but covariant derivatives acting on vectors don't commute, and they are related to the curvature tensor (in fact this is often how the curvature tensor is introduced).
$$[\nabla_\mu,\nabla_\nu]\nabla^\mu \phi = R_{\mu\nu}\nabla^\mu\phi.$$ | {
"domain": "physics.stackexchange",
"id": 84568,
"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": "string-theory, renormalization",
"url": null
} |
c++, interview-questions, mathematics, graph
Title: Print pair representing objects from sequence of nonnegative integer pairs There are some things I am not sure of from a professional standpoint about the "correct" way to write C++ code. I have been looking through source code produced by various opensource projects, as well as other code posted here and on Stack Overflow.
So let's just leave it at this. Let's say I am interviewing for company A over the phone. Not white board yet. They ask me to write the code below and turn it in a hour. This is a hypothetical situation, however it parallels how most "big" companies are interviewing nowadays. Would this code "get me the job"? If not, what would you change, or what can you coach me with so I can get a job programming?
#include <iostream>
#include <queue>
#include <algorithm>
#include <iterator>
/*
* This program reads a sequence of pairs of nonnegative integers
* less than N from standard input (interpreting the pair p q to
* mean "connect object p to object q") and prints out pair
* representing objects that are not yet connected. It maintains an
* array id that has an entry for each object, with the property
* that id[p] and id[q] are equal if and only if p and q are
* connected.
*/
static const int N = 10;
int main( int argc, char *argv[ ] )
{
/*
* Ease the type of long types
*/
typedef std::ostream_iterator<int> output_data;
typedef typename std::vector<int>::iterator v_it; | {
"domain": "codereview.stackexchange",
"id": 598,
"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++, interview-questions, mathematics, graph",
"url": null
} |
c#
Title: Managing contacts I'm trying to tidy the following fragment of code:
if (this.Details.Recipients.Count > 0)
this.Recipient = this.Details.Recipients[0];
else
{
this.Recipient = new Contact();
this.Details.Recipients.Add(this.Recipient);
}
if (this.Details.CCs.Count > 0)
this.CC = this.Details.CCs[0];
else
{
this.CC = new Contact();
this.Details.CCs.Add(this.CC);
}
if (this.Details.BCCs.Count > 0)
this.BCC = this.Details.BCCs[0];
else
{
this.BCC = new Contact();
this.Details.BCCs.Add(this.BCC);
}
But when I simplify it in the following way, I run into problems because I have to pass the objects by ref. And if I do that, then I get an error (A property, indexer or dynamic member access may not be passed as an out or ref):
InitialiseContacts(this.Details.Recipients, this.Recipient);
InitialiseContacts(this.Details.CCs, this.CC);
InitialiseContacts(this.Details.BCCs, this.BCC);
}
static void InitialiseContacts(ObservableCollection<Contact> contacts, Contact contact)
{
if (contacts.Count > 0)
contact = contacts[0];
else
{
contact = new Contact();
contacts.Add(contact);
}
}
Any ideas? So I think the error you is getting is hopefully obvious. You can't pass a property by ref. There is quite a few answers if you google this. Here's a quick one I found on stack overflow
So instead don't pass in the object, but rather have a new instance returned from the method. Something along the lines of
this.BCC = FirstOrCreateIfEmpty(this.Details.BCCs);
this.CC = FirstOrCreateIfEmpty(this.Details.CCs);
public Contact FirstOrCreateIfEmpty(List<Contact> contacts)
{
if(contacts.Any())
{
return contacts.First();
} | {
"domain": "codereview.stackexchange",
"id": 6424,
"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#",
"url": null
} |
organic-chemistry, reaction-mechanism, stereochemistry
The question is to predict the nature of the product(s) of the above reaction, that is if the product(s) form a racemic mixture, meso, diasteromers, or are structural isomers.
I am aware of the fact that addition of $\ce{H2}$ is a syn addition. So it should form a meso compound. However the answer key gives it as a mixture of diastereomers. I am not quite sure if the reaction is strictly selective and some anti products are also formed. To answer and understand this, let’s first consider the products of the hydrogenation ($\ce{H2; Pd/C}$) of 1-methylidene-4-methylcyclohexane (the same reactant except the methyl group is in para-position). This compound is symmetric and therefore achiral. We can draw the methyl group pointing upwards iwthout loss of generalisation. The hydrogenation is syn-selective and it can occur from the top or the bottom. We expect a $1:1$ mixture of the former methylidene group pointing upwards (the syn-isomer) and pointing downwards (the anti-isomer). Both are achiral (the plane of symmetry is retained in the reaction) but not identical; therefore, they must be diastereomers.
Now let’s move the methyl group back into the 2-position. By moving the methyl group, the plane of symmetry is lost; it suddenly makes a difference whether the methyl group points upwards (S) or downwards (R). For each of the two isomers, we can again hydrogenate from both above and below; we can expect two anti and two syn isomers at first approximation: we enter one stereocentre into the reaction and we form an additional one making two stereocentres in total and thus 4 theoretically possible isomers. | {
"domain": "chemistry.stackexchange",
"id": 7135,
"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": "organic-chemistry, reaction-mechanism, stereochemistry",
"url": null
} |
https://en.m.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic
• "Overkill?" Perhaps. T. Bongers answer is probably a lot easier, but your answer does capture the thought process that the OP was considering. (i.e. that the results have an "even part" and an "odd part" and ... so on.) – fleablood Oct 19 '18 at 18:27
• fleablood.Thanks for your comment. – Peter Szilas Oct 19 '18 at 19:24
To expand my comment, you need to make the reasoning a lot more precise. Start with an assumption that there are natural numbers $$m_1, m_2, n_1, n_2$$ for which
$$f(m_1, n_1) = f(m_2, n_2).$$
Then you have
$$(2m_1 - 1)2^{n_1} = (2m_2 - 1) 2^{n_2}.$$
Now we can assume without loss of generality that $$n_1 \le n_2$$, so that
$$2m_1 - 1 = (2m_2 - 1)2^{n_2 - n_1}.$$
Now the left side is odd, so the right side is odd too; thus, $$n_2 - n_1 = 0$$ (why?). But then we get $$2m_1 - 1 = 2m_2 - 1$$, hence $$m_1 = m_2$$. This completes the proof.
I can see that F can never be surjective because 1 does not have a pre-image.
Let's prove that.
If $$f(m,n) = (2m -1)*2^n = 1$$ then as $$2m-1$$ and $$2^n$$ are integer factors of $$1$$ and the only integer factors of $$1$$ are $$\pm 1$$ so $$2^n = \pm 1$$ and that is only possible if $$n = 0$$ which is not possible as $$0 \not \in \mathbb N$$. | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9896718473283829,
"lm_q1q2_score": 0.8939648436531956,
"lm_q2_score": 0.9032942041005328,
"openwebmath_perplexity": 133.04482498097448,
"openwebmath_score": 0.8663015961647034,
"tags": null,
"url": "https://math.stackexchange.com/questions/2962351/surjective-and-injective-function"
} |
php, game, image
// save in apc
Cache::set($cacheKey, serialize($imageContent));
}
// show file contents
echo $imageContent;
return;
}
// or create an image
else {
// create image object
$this->image = ImageCreateTrueColor(self::CELL_SIZE, self::CELL_SIZE);
if ($this->exists($id))
{
switch ($this->mapGroundType)
{
default:
case 'sea':
$backgroundColor = array_map('hexdec', str_split('0099FF', 2));
$noizeColor = array_map('hexdec', str_split('004C80', 2));
break;
case 'stone':
case 'mountain':
$backgroundColor = array_map('hexdec', str_split('969BA0', 2));
$noizeColor = array_map('hexdec', str_split('5A5D60', 2));
break;
case 'sand':
$backgroundColor = array_map('hexdec', str_split('CC9900', 2));
$noizeColor = array_map('hexdec', str_split('996600', 2));
break;
case 'forest':
$backgroundColor = array_map('hexdec', str_split('336600', 2));
$noizeColor = array_map('hexdec', str_split('003300', 2));
break;
case 'grass':
$backgroundColor = array_map('hexdec', str_split('339933', 2));
$noizeColor = array_map('hexdec', str_split('006600', 2));
break;
} | {
"domain": "codereview.stackexchange",
"id": 5769,
"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, game, image",
"url": null
} |
c#, javascript, jquery, asp.net
function getDriving() {
var url = $('#map').data('heatmap-driving');
getHeatmapData(url, "Speed");
}
Just plain getting crazy
You could utilize a function closure and import only the symbols you need, throw in a 'use strict'; directive.
This will:
Give you bragging rights because you used 'use strict';. There are other benefits, but from the standpoint of your script it basically does nothing. Bragging right. That's it.
Remove the need for fully qualified class names like google.map.x.Foo.
Allow your code to function even if some other JavaScript library defines a $ function
(function ($, MVCArray, HeatmapLayer, LatLng) {
'use strict';
function getHeatmapData(url, propertyName) {
$.getJSON(url,
function (data) {
var marker = [];
$.each(data,
function (i, item) {
marker.push({
'location': new LatLng(item.Latitude2, item.Longitude2),
'map': map,
'weight': item[propertyName],
'radius': 10
});
});
var pointArray = new MVCArray(marker);
heatmap = new HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
});
}
this.getStops = function () {
var url = $('#map').data('heatmap-stops-url');
getHeatmapData(url, "Stops");
}
this.getDriving = function () {
var url = $('#map').data('heatmap-driving');
getHeatmapData(url, "Speed");
}
})(this.jQuery, this.google.maps.MVCArray, this.google.maps.visualization.HeatmapLayer, this.google.maps.LatLng);
But at this point, we're really just being crazy. | {
"domain": "codereview.stackexchange",
"id": 27963,
"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#, javascript, jquery, asp.net",
"url": null
} |
c++, simulation, physics
// now we will convert va and vb back to original coordinate system
A.vel.i=(va.i*cos)-(va.j*sin);
B.vel.i=(vb.i*cos)-(vb.j*sin);
A.vel.j=(va.i*sin)+(va.j*cos);
B.vel.j=(vb.i*sin)+(vb.j*cos);
} | {
"domain": "codereview.stackexchange",
"id": 25619,
"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, physics",
"url": null
} |
c++, algorithm, circular-list, variadic, c++17
Title: Rotate a given number of variables in-place A very simple but useful algorithm: rotate the values of a given number of variables in-place to the left so that the first variable gets the value of the second, the second gets the value of the third, etc... and the last variable gets the value of the first one.
#include <type_traits>
#include <utility>
template<typename Head, typename... Tail>
struct are_same:
std::conjunction<std::is_same<Head, Tail>...>
{};
template<typename T, typename... Args>
auto rotate_left_inner(T& first, T& second, Args&... args)
-> T&
{
first = std::move(second);
if constexpr (sizeof...(Args) == 0) {
return second;
} else {
return rotate_left_inner(second, args...);
}
}
template<typename Head, typename... Tail>
auto rotate_left(Head& first, Tail&... args)
-> void
{
static_assert(are_same<Head, Tail...>::value,
"elements passed to rotate_left shall have the same type");
if constexpr (sizeof...(Tail) > 0) {
auto tmp = std::move(first);
auto& last = rotate_left_inner(first, args...);
last = std::move(tmp);
}
}
This function can be used as follows:
int a=0, b=1, c=2, d=3, d=4;
rotate_left(a, c, e);
rotate_left(b, d);
// Now (a, b, c, d, e) = (2, 3, 4, 1, 0) | {
"domain": "codereview.stackexchange",
"id": 25523,
"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++, algorithm, circular-list, variadic, c++17",
"url": null
} |
php, security, pdo
if (strtolower($mode) == 'debug') {
$patterns = array();
foreach ($boundValues as $value){
$patterns[] = '#\?#';
}
return preg_replace($patterns, $boundValues, $result->queryString, 1);
} else {
$i = 0;
foreach ($boundValues as $value){
$boundValues[$i] = $boundValues[$i];
$result->bindValue(($i+1), $boundValues[$i]);
$i++;
}
$result->execute();
return $this->db->lastInsertId() + $numInserts - 1;
}
}
/**
* Updates a database field with values obtained from magic methods representing the field names.
* Notes: Multiple table updates are currently not supported, nor are ordering or limiting result sets due to
* DBMS syntax inconsistencies
* @param string $mode - optional - If set to 'debug', returns the compiled SQL query
* @return int - The number of affected rows
*/
public function update($mode=NULL) {
$fields = array();
$boundValues = array();
foreach (array_keys($this->valueStorage) as $field) {
$fields[]= "$field=";
}
$parameters = implode("?, ", $fields).'?';
$i = 1;
foreach (array_keys($this->valueStorage) as $field){
$boundValues[$i]= $this->valueStorage[$field];
$i++;
}
$where = ($this->where) ? ' WHERE'.implode('', $this->where) : NULL;
$where = preg_replace('#(\s:[\w-]+[\s]?)#', ' ? ', $where);
$boundValues = array_merge($boundValues, array_values($this->boundValues));
$boundValues = $boundValues; | {
"domain": "codereview.stackexchange",
"id": 882,
"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, security, pdo",
"url": null
} |
ros, ros-kinetic
Originally posted by jo with karma: 46 on 2018-05-29
This answer was ACCEPTED on the original site
Post score: 2
Original comments
Comment by kaorusha on 2022-01-06:
For nodes running on multiple machine, robot_upstart is easier then manually write systemd to set the ROS_MASTER_URI, just remember to add the --master option. | {
"domain": "robotics.stackexchange",
"id": 30783,
"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, ros-kinetic",
"url": null
} |
# Why does the integral for the arc length of a polar curve have the boundaries it has?
So I've been working on the question below for a bit, and after arriving at what I thought was the answer, I found out that I was wrong, because the bounds I used for integration was incorrect.
Here is the problem statement.
~
So, the first thing I did was solve for the values of $\theta$ where an intersection occurs, and obviously these values are $\theta_1=\frac{\pi}{3}$ and $\theta_2=\frac{5}{3}\pi$. From here, I found the value of $(4\cos\theta)^2$ as well as the value of $\left(\frac{d}{dx}(4\cos\theta)\right)^2$, and then substituted these values into the formula for the arc length of a polar curve:
$$\implies \int_\alpha^\beta\sqrt{f(\theta)^2+f'(\theta)^2}~d\theta=\int_{\frac{1}{3}\pi}^{\frac{5}{3}\pi}\sqrt{16cos^2\theta+16\sin^2\theta}~d\theta$$
$$=4\int_{\frac{1}{3}\pi}^{\frac{5}{3}\pi}~d\theta$$
$$=4\left(\frac{5}{3}\pi-\frac{1}{3}\pi\right)$$
$$=\frac{16}{3}\pi$$
Although this answer was wrong, because according to the marking scheme, the correct bounds did not include $\frac{5}{3}\pi$, but rather included $\frac{2}{3}\pi$. Can someone perhaps explain to me why this is?
Any help is appreciated, thank you. | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.982287698703999,
"lm_q1q2_score": 0.8120688193983746,
"lm_q2_score": 0.8267117876664789,
"openwebmath_perplexity": 152.20669644063616,
"openwebmath_score": 0.9180081486701965,
"tags": null,
"url": "https://math.stackexchange.com/questions/2648854/why-does-the-integral-for-the-arc-length-of-a-polar-curve-have-the-boundaries-it"
} |
c#, .net, networking, socket
ISpecification
public interface ISpecification<T>
{
Expression<Func<T, bool>> Expression { get; set; }
bool IsSatisfiedBy(T o);
}
Approver
public class Approver<T> : IHandler<T>
{
private Action<T, object> _action;
private bool _isFallback;
private string _name;
private ISpecification<T> _specification;
private IHandler<T> _successor;
internal Approver(Action<T, object> action, bool isFallback, string name)
{
_name = name;
_action = action;
_isFallback = isFallback;
}
internal Approver()
{
_isFallback = false;
}
public void SetSuccessor(IHandler<T> handler)
{
_successor = handler;
}
public void HandleRequest(T o, object state)
{
if (CanHandle(o))
{
//o.Process();
Console.WriteLine("{0}: Request handled by {1}. ", o, _name);
_action.Invoke(o, state);
Console.WriteLine("****************************************");
return;
}
_successor?.HandleRequest(o, state);
}
public void SetSpecification(ISpecification<T> specification)
{
_specification = specification;
}
public bool CanHandle(T o)
{
if (_specification == null)
{
return false;
}
if (_isFallback)
{
return _specification.IsSatisfiedBy(o);
}
if (o != null)
{
return _specification.IsSatisfiedBy(o);
}
return false;
}
public IHandler<T> And(Func<T, bool> condition)
{
if (_specification == null)
{
_specification = new Specification<T>(arg => condition(arg));
}
else
{
_specification.Expression = _specification.Expression.And(arg => condition(arg));
}
return this;
} | {
"domain": "codereview.stackexchange",
"id": 25599,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, networking, socket",
"url": null
} |
thermodynamics, rocket-science
Title: rocket propulsion As I understand it, in rocket propulsion a converging/diverging nozzle is used to convert the random velocity vectors of the combustion chamber gases into a mostly unidirectional velocity field at the exhaust nozzle. What are the physics of this process? In a rocket, propulsion occurs when the combustion products are expelled in a direction opposite to the direction of intended thrust. Sending it sideways does not move you in the right direction - so it's important to have a coherent output.
You would also like the velocity of the exhaust gas to be as high as possible. It turns out that if your exhaust gas velocity is supersonic, then the shaped nozzle will cause further acceleration of the gas - in the process producing more thrust.
This is nicely explained on this NASA website from which I copy the following for ease of reference - but I recommend you read the original (which includes a detailed description): | {
"domain": "physics.stackexchange",
"id": 20359,
"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": "thermodynamics, rocket-science",
"url": null
} |
physical-chemistry, kinetics
Title: Ammonia decomposition on platinum surface I was given a problem I have to solve, unfortunately I cant wrap my head about it. I've searched the page for answers but they doesnt seem to fulfill my needs, so i'm asking for little guidance.
The problem:
When the decomposition of ammonia is carried out on platinum surface at 1000°C the
hydrogen binds strongly on the surface. Prove the that the rate is
equal to $\frac{dp(NH_3)}{dt}=-k\frac{p(NH_3)}{p(H_2)}$. | {
"domain": "chemistry.stackexchange",
"id": 13548,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "physical-chemistry, kinetics",
"url": null
} |
quantum-gate, programming, qiskit, gate-synthesis
Title: How do I build a gate from a matrix on Qiskit? I'm creating a gate for a project and need to test if it has the same results as the original circuit in a simulator, how do I build this gate on Qiskit? It's a 3 qubit gate, 8x8 matrix:
$$
\frac{1}{2}
\begin{bmatrix}
1 & 0 & 1 & 0 & 0 & 1 & 0 & -1 \\
0 & 1 & 0 & 1 & 1 & 0 & -1 & 0 \\
0 & 1 & 0 & -1 & 1 & 0 & 1 & 0 \\
1 & 0 & -1 & 0 & 0 & 1 & 0 & 1 \\
1 & 0 & 1 & 0 & 0 & -1 & 0 & 1 \\
0 & 1 & 0 & 1 & -1 & 0 & 1 & 0 \\
0 & 1 & 0 & -1 & -1 & 0 & -1 & 0 \\
1 & 0 & -1 & 0 & 0 & -1 & 0 & -1
\end{bmatrix}
$$ I don't think Qiskit has this simulation feature. You have to decompose it indeed.
However, there is another way to solve your problem.
To check if a quantum circuit (that you can submit in Qiskit) corresponds to a unitary matrix, you can use the unitary_simulator backend.
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
print(np.around(result.get_unitary(circ), 3))
This will print the unitary matrix that your circuit represents. And you can compare to yours. | {
"domain": "quantumcomputing.stackexchange",
"id": 2496,
"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-gate, programming, qiskit, gate-synthesis",
"url": null
} |
###### Example1.6.9.
Suppose that $f(x) = x^2\text{.}$ Determine the simplest possible expression you can find for $AV_{[3,3+h]}\text{,}$ the average rate of change of $f$ on the interval $[3,3+h]\text{.}$
Solution
By definition, we know that
\begin{equation*} AV_{[3,3+h]} = \frac{f(3+h)-f(3)}{h}. \end{equation*}
Using the formula for $f\text{,}$ we see that
\begin{equation*} AV_{[3,3+h]} = \frac{(3+h)^2-(3)^2}{h}. \end{equation*}
Expanding the numerator and combining like terms, it follows that
\begin{align*} AV_{[3,3+h]} &= \frac{(9+6h+h^2)-9}{h}\\ &= \frac{6h + h^2}{h}\text{.} \end{align*}
Removing a factor of $h$ in the numerator and observing that $h \ne 0\text{,}$ we can simplify and find that
\begin{align*} AV_{[3,3+h]} &= \frac{h(6 + h)}{h}\\ &= 6+h\text{.} \end{align*}
Hence, $AV_{[3,3+h]} = 6+h\text{,}$ which is the average rate of change of $f(x) = x^2$ on the interval $[3,3+h]\text{.}$ 1
Note that $6 + h$ is a linear function of $h\text{.}$ This computation is connected to the observation we made in Table 1.5.9 regarding how there's a linear aspect to how the average rate of change of a quadratic function changes as we modify the interval.
###### Activity1.6.4. | {
"domain": "activecalculus.org",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.987946222968067,
"lm_q1q2_score": 0.8007095743548547,
"lm_q2_score": 0.8104789063814617,
"openwebmath_perplexity": 165.54437221962357,
"openwebmath_score": 0.9033443927764893,
"tags": null,
"url": "https://activecalculus.org/prelude/sec-changing-composite.html"
} |
gap> m := 2;; n := 2;;
gap> f := FreeGroup( m + n );;
gap> s := GeneratorsOfGroup( f ){[ 1 .. m ]};;
gap> t := GeneratorsOfGroup( f ){[ m + 1 .. m + n ]};;
gap> st := Subgroup( f, ListX( s, t, \* ) );;
gap> ts := Subgroup( f, ListX( t, s, \* ) );;
gap> IsConjugate( f, st, ts );
true
gap> st^f.1 = ts;
true
Obviously, one conjectures this always holds, and in fact the proof was an easy calculation (at the top of the answer).
-
Hey Jack, what a GREAT answer and solution! Thanks very much, this problem kept me awake for a while. Quite surprising that it is true indeed. I also kept calculating in small groups. That's why I had the suspicion that it should be true. Something to go in textbooks in the future, because I have not seen this anywhere, did you? – Nicky Hekster Nov 17 '11 at 21:31
@Nicky: No, I had never seen it. I'm pretty sure I would have remembered it, since st conjugate to ts has always been useful to me, and this argument is so simple. Your set generalization sounded false to me, since you needed different conjugators to get one element of ST to one element TS, so I was most certainly looking for counterexamples. – Jack Schmidt Nov 17 '11 at 22:33 | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9787126488274565,
"lm_q1q2_score": 0.811292900944116,
"lm_q2_score": 0.8289388125473629,
"openwebmath_perplexity": 390.2354194553108,
"openwebmath_score": 0.7970017790794373,
"tags": null,
"url": "http://math.stackexchange.com/questions/82851/products-of-sets-in-a-group/83164"
} |
quantum-field-theory, renormalization, feynman-diagrams, perturbation-theory, scattering-cross-section
I also struggled in understanding P&S, actually it is not a very pedagogical textbook. I already read many respective comments on this. I hope this answer is satisfactory, any comments are welcome. | {
"domain": "physics.stackexchange",
"id": 43969,
"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, renormalization, feynman-diagrams, perturbation-theory, scattering-cross-section",
"url": null
} |
i}}^{n}\conjugate{a_i}a_j\lambda_j\innerproduct{\vect{x}_i}{\vect{x}_j}\\ &=\sum_{i=1}^{n}\conjugate{a_i}a_i\lambda_i \end{align*} | {
"domain": "ups.edu",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9918120900983037,
"lm_q1q2_score": 0.8286426670830648,
"lm_q2_score": 0.8354835309589074,
"openwebmath_perplexity": 339.0983849161965,
"openwebmath_score": 0.947689414024353,
"tags": null,
"url": "http://buzzard.ups.edu/scla2021/section-positive-semidefinite.html"
} |
c++, beginner, calculator, reference
There are two problems with it. First, the movie name I gave was not Journey to Mars so that's a basic problem that comes from not passing that value into printReport. The second problem is more subtle. Notice that the gross amount is $954.50, but the sum of the donated amount and the net sale is only $954.49. That missing $0.01 is going to drive an accountant insane! This is a fundamental problem with using double (or any floating-point representation) for money values. An alternative is to keep a number of cents as an integer value internally. For more depth about floating point issues, I'd recommend the excellent article "What every computer scientist should know about floating-point arithmetic" by David Goldberg.
Don't abuse using namespace std
Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.
Use objects
As mentioned in the other review, using one or more objects would help this code a lot. Here's a start. First you could have a class named Movie:
class Movie
{
public:
void getInput();
void calculate();
void printReport() const;
private:
std::string movieName;
double adultTicketPrice;
double childTicketPrice;
int noOfAdultTicketSold;
int noOfChildTicketSold;
double percentageDonation;
// calculated values
double grossAmount;
double amountDonated;
double netSale;
};
Now all of your functions are easily changed into member functions. For example, this:
void getInput(string& movieName, double& adultTicketPrice,
double& childTicketPrice, int& noOfAdultTicketSold,
int& noOfChildTicketSold, double& percentageDonation) {
becomes this:
void Movie::getInput() {
And your movieSalesReport() is considerably simplified:
void movieSalesReport() {
Movie movie;
movie.getInput();
movie.calculate();
movie.printReport();
}
It's not ideal, but it should get you started. | {
"domain": "codereview.stackexchange",
"id": 17593,
"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, calculator, reference",
"url": null
} |
thermodynamics, temperature
Title: Non uniform freezing of lakes Here's a problem from my physics textbook:
Why do lakes freeze first at the surface?
I'm not sure why this should happen, and my guess is that the only reason for this could be the temperature distribution with depth, inside water bodies. You need to know that water at $4^{\circ}$C achieve its highest density. So naturally, water at $4^{\circ}$C will tend to move to the bottom of the lake as it is heavier. When the temperature is cool enough to freeze the lake, eventually there will be some layer of ice forming at the surface but there is still liquid water below the ice layer. The ice also works as an insulation to keep the water below it from freezing to ice completely. Also, ice has a lower density than water so any ice forming will float to the surface. There are other factor like Earth's internal heating that constantly maintaining the water at the bottom of lake from freezing. | {
"domain": "physics.stackexchange",
"id": 43548,
"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": "thermodynamics, temperature",
"url": null
} |
python, networking, socket, server, tcp
Add graceful shutdown of all threads
Add a way to shut down threads in a graceful way. To shut down a _ClientHandler, add a special item to the queue that signals that this handler should return from run(). For the StreamServer(), add a flag named running for example that is True by default. In run(), check the flag each iteration of the loop. If it's no longer True, exit the loop. To shutdown in an orderly way, you have to set self.running = False, then create a connection to the listening socket in order to have sock.accept() return.
Don't attempt to just close client sockets or the listening socket. There is no guarantee that this will cause the threads to immediately receive an error.
Consider using non-blocking sockets
Instead of having a queue per client, you could instead make use of the TCP send buffer for each client connection. So instead of first enquing some data, you immediately send copies of the data on each client's socket. Now the problem is to know when the send buffer is full. You can do that by making the socket non-blocking using socket.setblocking(False). When you attempt to write to a non-blocking socket, you will receive an error. If that happens, you can just close the connection.
You can tune the size of the sendbuffer in this way:
socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, size) | {
"domain": "codereview.stackexchange",
"id": 35560,
"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, networking, socket, server, tcp",
"url": null
} |
c++, strings
Title: Serialization/Unserialization of a list of strings - C++ Are there any issues with below implementation?
Input: from STDIN, a list of strings
Output: serialize to a file called "out.txt" and then unserialize into a list of strings, and output to STDOUT
Goal is not here too much about code organization, but I would like to know if this code can fail for certain types of inputs
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
std::vector<std::string> input;
std::string tmp;
while (std::cin >> tmp)
{
input.push_back(tmp);
}
std::ofstream out("out.txt", std::ios::out);
for (std::vector<std::string>::const_iterator iter = input.begin();
iter != input.end();
++iter)
{
out << (*iter).size() << "|" << *iter;
}
out.close();
std::vector<std::string> output;
std::ifstream in("out.txt", std::ios::in);
if (in.is_open())
{
std::string tmp;
if (!in.eof())
{
getline(in, tmp);
size_t pos;
int length = 0;
std::string str;
while (!tmp.empty())
{
pos = tmp.find('|');
if (pos != std::string::npos)
{
length = atoi(tmp.substr(0, pos).c_str());
str = tmp.substr(pos+1, length);
tmp = tmp.substr(pos+str.size() + 1); | {
"domain": "codereview.stackexchange",
"id": 656,
"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",
"url": null
} |
continuous in time, with discontinuities in between. This email address is being protected from spambots. The spectrum contains only terms with b n. REFERENCES [1]. An improvement of the Beurling-Helson theorem. Fourier Series Of Piecewise Function 1 Orthogonal Functions 12. fourier does not transform piecewise. Fourier analysis has been applied to stock trading, but research examining the technique has found little to no evidence that it is useful in practice. It is also quite easy to show that if f(x) is piecewise smooth, then also is F(x). If f is piecewise continuous with piecewise continuous derivative on [0,L ), then its sine Fourier series converges to the odd periodic extension of f modified at discontinuities using averages. Before looking at further examples of Fourier series it is useful to distinguish two classes of functions for which the Euler-Fourier formulas for the coefficients can be simplified. function f (x) =π, π∈[]−π, π, , extended periodically on the real line; this function is discontinuous at x =(2k +1)π for all interger values of k. There are countless types of symmetry, but the ones we want to focus on are. November 2019; Issues properties of discrete and continuous finite Fourier series. Piecewise Constant Function. Travel and explore the world of cinema. Derivative numerical and analytical calculator. Free piecewise functions calculator - explore piecewise function domain, range, intercepts, extreme points and asymptotes step-by-step This website uses cookies to ensure you get the best experience. Sine series. In order to incorporate general initial or boundaryconditions into oursolutions, it will be necessary to have some understanding of Fourier series. In this article, f denotes a real valued function on which is periodic with period 2L. Again, using MathView to handle the detailed manipulation allows Let's have a look at a simple notebook example where the Fourier series approximates a unit step function at x=0 and calculate the coefficients. list_of_pairs is a list of pairs (I, fcn), where fcn is a Sage function (such as a polynomial over RR, or functions using the lambda notation), and I is an interval such as I = (1,3). In this section we will define piecewise smooth functions and the periodic | {
"domain": "mayoume.pl",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9852713878802045,
"lm_q1q2_score": 0.8413357977348968,
"lm_q2_score": 0.853912747375134,
"openwebmath_perplexity": 763.9511490232254,
"openwebmath_score": 0.8784337043762207,
"tags": null,
"url": "http://oqxl.mayoume.pl/fourier-series-of-piecewise-function.html"
} |
rosmake
Title: rosmake error:no such option
Hello, I am recently learning
http://wiki.ros.org/openni/Contests/ROS%203D/RGBD-6D-SLAM
My system is Ubuntu 12.04 and ros-libfreenect.
This is some error I don't know how to fix it:
root@ubuntu:~# rosmake --rosdep-install rgbdslam
Usage: rosmake [options] [PACKAGE]...
rosmake: error: no such option: --rosdep-install
Could you help me to try it out?
Thank you.
Originally posted by Battery on ROS Answers with karma: 25 on 2013-11-15
Post score: 0
Your error says to you "no such option". On a web site (http://wiki.ros.org/rosmake), it describes that option --rosdep-install is avalable for electric and earlier. I guess you use fuerte, groovy or hydro. So I think you should try next command, because a web site (http://wiki.ros.org/openni/Contests/ROS%203D/RGBD-6D-SLAM) describes Compile our package. rosmake rgbdslam
Originally posted by Ken_in_JAPAN with karma: 894 on 2014-04-04
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 16175,
"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": "rosmake",
"url": null
} |
python, beginner, time-limit-exceeded
def digits_solver():
column = [(x, a, d, (x + a + d) % 10, (x + a + d) // 10)
for x, a, d in product(range(2), range(1, 10), range(1, 10))
if len(set([a, d, (x + a + d) % 10])) == 3 and (x + a + d) % 10 != 0]
first_column = [(x, a, d, g) for x, a, d, g, z in column if z == 0 and a < d]
for x, a, d, g in first_column:
second_column = [(y, b, e, h) for y, b, e, h, xx in column if xx == x and not set([a,d,g]) & set([b,e,h])]
for y, b, e, h in second_column:
third_column = [(r, c, f, i) for r, c, f, i, yy in column
if yy == y and not set([a,d,g,b,e,h]) & set([c,f,i]) and r == 0 ]
for _, c, f, i in third_column:
yield (100 * g + 10 * h + i, 100 * d + 10 * e + f, 100 * a + 10 * b + c)
in above example for by for by for is bad idea, you can remove it by recursion. The code will be much less messy
if you want try 6-digits number, you can change check unique digits (using set at examples) to multiset (at python you can use Counter class from collections library to emulate it) | {
"domain": "codereview.stackexchange",
"id": 19191,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, time-limit-exceeded",
"url": null
} |
astrophysics, thermodynamics, soft-question
Title: What happens to internal energy in high-density materials? Normal-density materials have internal energy, which is the sum of the average energies associated to each of the degrees of freedom. Degrees of freedom can be described as vibrational, translational, and rotational. If you compress this material in such a way that matter cannot escape, you can detect energy escaping in the form of heat.
Now imagine an extremely high-density material such as a neutron star or black hole. I suspect it's not possible to describe the internal energy of (or anything about) an individual atom inside a black hole, since it's impossible to inspect beyond the event horizon, and since I assume that atoms don't exist in an distinguishable form there. But presumably the atoms had energy when they became part of the thing. How is that energy accounted for? The internal energy of a black hole is just its mass. You can measure the mass of a black hole by its gravitational effects on outside bodies, and then extrapolate an equivalent energy using $E=mc^{2}$.
An isolated Neutron star also has a well-defined total mass, (the ADM mass), which can be used to define an internal energy. In the case of a neutron star, since it has X numbers of neutrons, and baryon number is conserved in gravitational collapse, you can even divide the total energy by the number of baryons to get a 'total energy per baryon.' | {
"domain": "physics.stackexchange",
"id": 600,
"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, thermodynamics, soft-question",
"url": null
} |
javascript, array, ecmascript-6, memory-management
const ctx = document.querySelector('canvas').getContext("2d");
const particles = [];
function addParticle() {
particles.push({
x: Math.random() * 800,
y: Math.random() * 500,
width: Math.random() * 100 + 50,
height: Math.random() * 100 + 50,
color: '#' + Math.floor(Math.random() * 16777215).toString(16)
});
if (particles.length > 5) particles.shift();
draw();
}
function draw() {
ctx.clearRect(0, 0, 800, 500);
particles.forEach(({ color, x, y, width, height }) => {
ctx.fillStyle = color;
ctx.fillRect(x, y, width, height);
});
}
<button>Add</button>
<canvas width="800" height="500"></canvas> | {
"domain": "codereview.stackexchange",
"id": 39442,
"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, array, ecmascript-6, memory-management",
"url": null
} |
c, windows, gui, winapi
return 0;
}
ATOM WINAPI RegisterWCEX(
HINSTANCE hInstance
)
{
WNDCLASSEXW wcex;
ZeroMemory(&wcex, sizeof(WNDCLASSEXW));
wcex.cbSize = sizeof(WNDCLASSEXW);
wcex.hInstance = hInstance;
wcex.lpszClassName = g_wszClassName;
wcex.hbrBackground = (HBRUSH) COLOR_WINDOW;
wcex.hCursor = LoadCursorW(NULL, IDC_ARROW);
wcex.hIcon = wcex.hIconSm = LoadIconW(NULL, IDI_APPLICATION);
wcex.lpfnWndProc = WindowProc;
return RegisterClassExW(&wcex);
}
INT APIENTRY wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ INT nShowCmd
)
{
HWND hWnd;
MSG Msg;
if (RegisterWCEX(hInstance) == 0)
{
MessageBoxW(NULL, L"Window registration failed", L"Error", MB_OK | MB_ICONSTOP);
return -1;
}
hWnd = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, g_wszClassName, L"Windows Font Demo", WS_VISIBLE | WS_SYSMENU, 100, 100, 500, 350, NULL, NULL, hInstance, NULL);
if (NULL == hWnd)
{
MessageBoxW(NULL, L"Window creation failed", L"Error", MB_OK | MB_ICONSTOP);
return -1;
}
ShowWindow(hWnd, nShowCmd);
UpdateWindow(hWnd);
while (GetMessageW(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessageW(&Msg);
}
return Msg.wParam;
}
Will give us the following window: | {
"domain": "codereview.stackexchange",
"id": 43490,
"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, windows, gui, winapi",
"url": null
} |
Do you get the least-squares equation of part (b) with the symbols x and yexchanged?
YesNo
(e) In general, suppose we have the least-squares equation y = a + bx for a set of data pairs (xy). If we solve this equation for x, will we necessarily get the least-squares equation for the set of data pairs (yx), (with x and y exchanged)? Explain using parts (a) through (d).
In general, switching x and y values produces the same least-squares equation.Switching x and y values sometimes produces the same least-squares equation and sometimes it is different. In general, switching x and y values produces a different least-squares equation. | {
"domain": "bartleby.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9924227571633809,
"lm_q1q2_score": 0.8291528693588357,
"lm_q2_score": 0.8354835309589073,
"openwebmath_perplexity": 261.7875111281143,
"openwebmath_score": 0.822396457195282,
"tags": null,
"url": "https://www.bartleby.com/questions-and-answers/suppose-you-are-given-the-following-x-y-data-pairs.-x-1-2-6-y-4-3-9-find-the-leastsquares-equation-f/18fb2cb3-5dee-4497-9525-150a9c24a115"
} |
Therefore $\rm\: z\, =\, -1\pm\sqrt{{\it i}\,}\,=-1\pm \alpha\,(1 + {\it i})\, =\, -1\pm \alpha\, \pm\, \alpha\,{\it i}$
-
That's what I got with the quadratic formula, but I didn't know how to put it into exponential form. Now I see from the previous answer. – JKH Jul 11 '12 at 19:30
@JKH There's no need to use any high-powered transcendental methods such as exponentials. As I show above one can compute $\,\sqrt{\it i\,}\,$ purely algebraically, viz. $\rm\:\sqrt{{\it i}\,} = (1+{\it i})/\sqrt{2}\ \$ – Bill Dubuque Jul 11 '12 at 19:36
The answer in the back of the book is in exponential form, i.e. e^(iπ/4), which is why I wanted it in that form. I didn't realize my answer was correct because I didn't know how to put it in the form the answer was given in. – JKH Jul 11 '12 at 19:47
@JKH Ah, I missed that. In any case, now you know how to do it a couple ways. – Bill Dubuque Jul 11 '12 at 20:07 | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9787126469647338,
"lm_q1q2_score": 0.8218582522839747,
"lm_q2_score": 0.8397339656668286,
"openwebmath_perplexity": 314.5989647564834,
"openwebmath_score": 0.9091578722000122,
"tags": null,
"url": "http://math.stackexchange.com/questions/169486/roots-of-a-polynomial-with-a-complex-coefficient"
} |
If n r is less than r, then take (n r) factors in the numerator from n to downward and take (n r) factors in the denominator ending to 1. For all integers r and These problems are for YOUR benefit, so take stock in your work! Answer 1: There are two words that start with a, two that start with b, two that start with c, for a total of . Satisfactory completion of MATH 30 is recommended for students planning to take MATH 140, MATH 143, MATH 145, MATH 150, or MATH 151, while MATH 25 is sufficient for MATH 104, MATH 105, MATH 195, STAT 101 or STAT 105. Solution: 4. Discrete Mathematics. It is increasingly being applied in the practical fields of mathematics and computer science. box and whisker plot. Download Wolfram Player. Math; Advanced Math; Advanced Math questions and answers; Discrete Math Homework Assignment 6 The Binomial Theorem Work through the following exercises. The binomial theorem gives us a formula for expanding $$( x + y )^{n}\text{,}$$ where $$n$$ is a nonnegative integer. This is the place where you can find some pretty simple topics if you are a high school student. (n+1 r)= ( n r1)+(n r). discrete data. Binomial Coe cients and Identities Generalized Permutations and Combinations. First studied in connection with games of pure chance, the binomial distribution is now widely used to analyze data in virtually every field of human inquiry. what holidays is belk closed; 14, Dec 17. (2) Arguments in Discrete Mathematics. Binomial Theorem b. 03, Oct 17. ( x + y) n = k = 0 n n k x n - k y k, where both n and k are integers. Use the binomial theorem to expand (x Answer 2: There are three choices for the first letter and two choices for the second letter, for a total of . The coefficients nCr occuring in the binomial theorem are known as binomial coefficients. Arfken (1985, p. 307) calls the special case of this formula with a=1 the binomial theorem. The coefficients of this expansion are precisely the binomial coefficients that we have used to count combinations. Then In 4 dimensions, (a+b) 4 = a 4 | {
"domain": "abroadexport.com",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9632305318133553,
"lm_q1q2_score": 0.8005823600015395,
"lm_q2_score": 0.8311430478583168,
"openwebmath_perplexity": 593.3967928978907,
"openwebmath_score": 0.7726367712020874,
"tags": null,
"url": "http://abroadexport.com/tick-borne/padanaram/881839986717ae1ca61b6e607e-binomial-theorem-discrete-math"
} |
java, algorithm, beginner, matrix
Is a) Not part of the first pass. b) Totally unnecessary as the labels array is filled with zeros already. c) Buggy if matrix is not square.
int[][] matrix = {{0, 0, 0, 0, 1, ...
I'd highly recommend reading from a file instead of hardcoding into the code!
Your constructor and your main method is doing way too many things, break up the code into additional methods.
Some methods can include:
Read matrix from file / some input / code
One (or more) methods for doing the "first pass" (you can put the 2d outer loop in one method, which can call another method)
One method for the "second pass"
One method for the output
public int[][] labeledMatrix;
Don't use public fields like that, that one should be private. It's good to restrict the visibility as much as possible.
i and j vs. x and y
Sometimes 2d arrays are indexed as matrix[x][y] and sometimes as matrix[y][x], to make it clear which version you're using, don't use i and j. I really don't like those variable names when using 2d arrays.
It is a good practice to always use braces, even for one-liners: (Even I get told this from time to time!)
if(i+ni == 0 && i+nj == 0) continue;
if(labels[i+ni][j+nj] != 0) neighbors.add(labels[i+ni][j+nj]);
Is changed to:
if (i + ni == 0 && i + nj == 0) {
continue;
}
if (labels[i + ni][j + nj] != 0) {
neighbors.add(labels[i + ni][j + nj]);
}
Remember the comments about the naming though.
For your drawing an image plans, you should read up on Creating and Drawing to an Image and the chapter that follows it Writing/Saving an Image. You can use the Graphics2D object as shown in the first link to draw rectangles on the image.
if(neighbors.size() == 0) {
is the same as
if (neighbors.isEmpty()) { | {
"domain": "codereview.stackexchange",
"id": 8182,
"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, algorithm, beginner, matrix",
"url": null
} |
forces, kinematics, energy-conservation, momentum, collision
Think of the problem in three time steps:
1) Before contact:
Both bodies have mass ($m_{1}, m_{2}$) and velocity ($v_{1,i}, v_{2,i}$).
2) During contact:
The time interval begins at contact between bodies and ends at the instant $v_{f} = v_{1,f} = v_{2,f}$.
The final velocity is solved by Conservation of Momentum:
$$m_{1}(v_{f} - v_{1,i}) = m_{2}(v_{f} - v_{2,i}) \; \Rightarrow \; \therefore v_{f} = \frac {m_{1}v_{1,i}-m_{2}v_{2,i}}{m_{1}-m_{2}}$$
Next, apply Conservation of Energy and assume all energy is stored in strain energy (where no energy is lost to heat, sound, etc.). Strain energy is analogous to energy stored in a spring, where the effective spring constants, $k=\frac {EA}{L}$, depend on the geometry and material of the bodies.
$$\Delta E_{Kinetic} = E_{Strain}$$
$$[\frac {1}{2}m_{1}v_{1,i}^2 + \frac {1}{2}m_{2}v_{2,i}^2]_\text{i} - [\frac {1}{2}(m_{1} + m_{2})v_{f}^2]_\text{f} = \frac {1}{2}k_{1}\delta_{1}^2 + \frac {1}{2}k_{2}\delta_{2}^2$$ | {
"domain": "physics.stackexchange",
"id": 26679,
"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": "forces, kinematics, energy-conservation, momentum, collision",
"url": null
} |
python, algorithm
Title: Find all subranges of consecutive values in an array I was looking at a dataset with a year column. I wanted all the years with matching a particular event. I then get a list of years which is not easy to read:
2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020
It would be much better to display them as:
2010-2013, 2015, 2017-2020
I was looking for a builtin function in Python, but eventually, I wrote this:
import numpy as np
def ranges(array):
start = None
for i, k in zip(np.diff(array, append=[array[-1]]), array):
if i == 1:
if start is None:
start = k
continue
yield(k if start is None else (start, k))
start = None
Is there a more pythonic way that does the same with less?
At the end I could do this:
years = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020]
', '.join([f'{x[0]}-{x[1]}' if isinstance(x, tuple) else str(x)
for x in ranges(years)]) I'm glad you asked this question, as I've had a difficult time finding the solution recently as well. However, I have now found that the solution is to use the more_itertools consecutive_groups function:
from more_itertools import consecutive_groups
x = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020]
# create an intermediate list to avoid having unnecessary list calls in the next line
subsets = [list(group) for group in consecutive_groups(x)]
result = [f"{years[0]}-{years[-1]}" if len(years) > 1 else f"{years[0]}" for years in subsets]
# ['2010-2013', '2015', '2017-2020'] | {
"domain": "codereview.stackexchange",
"id": 41484,
"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",
"url": null
} |
optics, everyday-life, polarization, vision
Title: Why do sun glasses shield more sunlight from a specific angle? I started recently wearing sunglasses during my online classes as laptop screens started taking a toll on my poor eyesight (of course my physics teacher wanted it removed but that's beside the point).
I noticed on one occasion when I stretched my neck nearly 45 degrees towards my left, the screen went completely dark and I couldn't see a thing on my laptop. I thought that the battery must have died and so as I reached for my charger I saw the screen reappear. I also observed the same happening when I looked at the screen from the corner of my eye as I faced the left side of the laptop (from my peripheral vision). In the image the laptop would come towards the my right side, around 10-20 degrees. | {
"domain": "physics.stackexchange",
"id": 77596,
"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": "optics, everyday-life, polarization, vision",
"url": null
} |
newtonian-mechanics, forces, mass, inertia
Title: What is the minimum force needed to overcome Inertia? This question arose from this statement:
On Mars, weights would be different but the amount of force needed to overcome inertia would be the same. | {
"domain": "physics.stackexchange",
"id": 75977,
"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, forces, mass, inertia",
"url": null
} |
Thus my work continues as follows:
$$\frac{1}{2}\int\frac{x+2}{\sqrt{1-\frac{1}{4}x^2}}\,dx = \frac{1}{2}\int\frac{(2\cdot\sin(\theta)+2)}{\sqrt{1-\sin^2(\theta)}}\cdot(2\cdot \cos(\theta))\,d\theta = \\[30pt] \frac{1}{2}\int\frac{(2\cdot\sin(\theta)+2)}{\sqrt{\cos^2(\theta)}}\cdot(2\cdot \cos(\theta))\,d\theta = \frac{1}{2}\int\frac{(2\cdot\sin(\theta)+2)}{\cos(\theta)}\cdot(2\cdot \cos(\theta))\,d\theta = \\[30pt] \int (2\cdot\sin(\theta)+2)\,d\theta = 2\int (\sin(\theta)+1)\,d\theta = 2(\theta-\cos(\theta))+C = \\[30pt] 2\theta - 2\cos(\theta)+C \\[30pt]$$
Now solving for $\theta$ I get $\theta = \sin^{-1}\big(\frac{x}{2}\big)$ and solving with a right triangle I find that $\cos(\theta) = \sqrt{4-x^2} \\[30pt]$.
Thus -- substituting back in for x -- the final answer would seem to be:
$$2\cdot \sin^{-1}\Big( \frac{x}{2}\Big)-2\sqrt{4-x^2}+C \\[30pt]$$ | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9683812299938006,
"lm_q1q2_score": 0.8250151059068279,
"lm_q2_score": 0.8519528057272543,
"openwebmath_perplexity": 199.62762079649457,
"openwebmath_score": 0.8964992165565491,
"tags": null,
"url": "https://math.stackexchange.com/questions/1153521/are-there-restrictions-i-have-forgotten-for-integration-by-trigonometric-substit/1153547"
} |
# Math Help - need help.
1. ## need help.
A long rope is pulled out between two opposite shores of a lake. It's pulled so tight that it's perfectly straight.
Because the earth is spherical most of the rope is under water.
The length of the portion of rope that is under water is 70 km long.
How many meters below the surface is the rope at its deepest point?
The earths radius is assumed to be 6370 km.
2. Hello, Bobby!
A long rope is pulled out between two opposite shores of a lake.
It's pulled so tight that it's perfectly straight.
Because the earth is spherical most of the rope is under water.
The length of the portion of rope that is under water is 70 km long.
How many meters below the surface is the rope at its deepest point?
The earths radius is assumed to be 6370 km.
Code:
C
* * *
* :x *
* : 35 *
A * - - - - -+- - - - - * B
\ D: /
\ :R-x /
R \ : / R
\ : /
\:/
*
O
The center of the earth is $O.$ . $OA = OB = OC = R$ (radius of the earth).
The 70-km rope is $AB.$ .We see that: $AD = DB = 35.$
Let $x = CD$ be the distance the rope is underwater at its center.
Then $DO = R - x.$
From right triangle $ODB:\;\;DO^2 + DB^2\:=\:OB^2$
So we have: . $(R - x)^2 + 35^2\:=\:R^2\quad\Rightarrow\quad x^2 - 2Rx + 1225\;=\;0$
Quadratic Formula: . $x\;=\;\frac{2R \pm\sqrt{4R^2 - 4900}}{2}\;=\;R \pm \sqrt{R^2 - 1225}$
Since $R = 6370$, we have: . $x \;= \;6370 \pm \sqrt{6370^2 - 1225}$ | {
"domain": "mathhelpforum.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9859363750229257,
"lm_q1q2_score": 0.8457047760442272,
"lm_q2_score": 0.8577681049901037,
"openwebmath_perplexity": 3070.497869548478,
"openwebmath_score": 0.9438750147819519,
"tags": null,
"url": "http://mathhelpforum.com/geometry/3550-need-help.html"
} |
electromagnetism, maxwell-equations, magnetic-moment, dipole-moment
-x_0 (\nabla\cdot\bar{F})
+
\bar{r}\cdot (-i\bar{\nabla}\times\bar{F})
=\\
-x_0 (4\pi \rho)
+
\bar{r}\cdot \left(\dfrac{4\pi}{c} \bar{J}
+
\partial_{0}
\bar{F}\right)
=\\
\dfrac{4\pi}{c} (\bar{r}\cdot\bar{J} - x_0\rho c)
+
\partial_{0}
(\bar{r}\cdot\bar{F})
=\\
\bar{\nabla} \cdot (i\bar{r}\times\bar{F} - x_0\bar{F})
,
\end{align}
which reduces to the following expression
\begin{align}
\bar{\nabla} \cdot (i\bar{r}\times\bar{F} - x_0\bar{F})
-
\partial_{0}
(\bar{r}\cdot\bar{F})
=
\dfrac{4\pi}{c} (\bar{r}\cdot\bar{J} - x_0\rho c)
.
\end{align}
One can perform the following substitutions $R_0 = (\bar{r}\cdot\bar{J} - x_0\rho c)/c$ to obtain
\begin{align}
\bar{\nabla} \cdot \bar{G}
-
\partial_{0}G_0
=
4\pi R_0
.
\tag{Gauss Dipole}
\end{align} No explicit complexification is needed to derive this breakdown of Maxwell's equations. This can be understood wholly through the real vector space of special relativity.
Let's start with Maxwell's equations for the EM field, in the clifford algebra language called STA: the spacetime algebra. Maxwell's equations take the form
$$\nabla F = -J$$ | {
"domain": "physics.stackexchange",
"id": 12535,
"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, maxwell-equations, magnetic-moment, dipole-moment",
"url": null
} |
c++, playing-cards
Rather than having to think in reverse iteration, you could think of the top of the deck as being 0. This would likely simplify a lot of the logic.
Are you happy being stuck with a 52 card deck? What if you don't want Jokers? What if you want some completely different kind of card system? A
Basically what I'm saying is that a deck shouldn't be responsible for filling itself up with cards.
In fact, constructing objects in a construct tends to be an anti-pattern: http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/. Note that "new" in this context is talking about Java, not C++. Though the terminology is Java centric, what it actually means is is construction in general. Constructing objects in a construct tends to imply that the objects should be provided to the constructor rather than be created in there.
Rather than having the deck populate itself with a traditional set of cards, have a utility method:
Deck classDeck = Deck::makeClassicDeck();
This lets you have the convenience that you currently have, but it doesn't hold you to a certain set of cards (you could also go the two constructors route).
Why are you trying to hide the Card class? You should probably trust your consuming code to handle cards. How do you know that the code isn't going to be used for some very odd game that involves a deck composed of a normal deck and 6 extra jokers? If you let the consumer of Deck decide what to put it in, it's a lot more flexible.
As a person about to make a program that involves card game logic, why should I use your Deck class? What does it offer me over using a simple std::deqeue (or std::stack or std::vector) of Card? The way I see it at the moment, it offers basically nothing over a vector. It just has a more convenient shuffle.
MAX_SIZE should be a std::size_t
empty should return a bool
size should return a std::size_t
I'm not sure if I'd bother defining an ostream<<. Might be more useful to let each application determine how it wants to print a deck rather than tie it to one format. | {
"domain": "codereview.stackexchange",
"id": 3982,
"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++, playing-cards",
"url": null
} |
python, inheritance, meta-programming
Title: Using a decorator to apply an inherited method to all child objects of the inherited type I wanted to share this and get some feedback. My goal was to be able to have an object with methods:
class Thing(object):
def __init__(self, data=123):
self.data = data
def add_one(self):
self.data += 1
def add_number(self, number):
self.data += number
And then a collection object, MetaThing that can hold several Thing objects, which inherits from Thing like this:
class MetaThing(Thing):
def __init__(self):
super(MetaThing, self).__init__()
self.list = [1, 2, 3, 4, 5]
self.things = []
self.setupThings()
def setupThings(self):
for i in self.list:
thing = Thing(data=i)
self.things.append(thing)
Finally, I want to be able to apply the methods in Thing to all the Thing instances stored in MetaThing.things when those same methods are called on MetaThing.
Doing this explicitly creates methods like this:
def add_one(self):
for t in self.things:
t.add_one()
def add_number(self, number):
for t in self.things:
t.add_number(number)
So I started wondering if this would be a good situation for a decorator, so I wrote one that I think does what I want:
def allthings(func):
def new_func(*args, **kwargs):
self = args[0]
for thing in self.things:
arglist = list(args)
arglist[0] = thing
func(*arglist, **kwargs)
return new_func
So now, the MetaThing method can use the @allthings decorator to call an inherited method on all child objects without rewriting the for loop every time:
class MetaThing(Thing):
def __init__(self):
super(MetaThing, self).__init__() | {
"domain": "codereview.stackexchange",
"id": 8166,
"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, inheritance, meta-programming",
"url": null
} |
# Function $\mathbb{R}\to\mathbb{R}$ that is continuous and bounded, but not uniformly continuous
I found an example of a function $f: \mathbb{R}\to\mathbb{R}$ that is continuous and bounded, but is not uniformly continuous. It is $\sin(x^2)$. I think it's not uniformly continuous because the derivative is bigger and bigger as $x$ increases. But I don't know how to prove this is uniformly continuous. Is $\sin(x^2)$ uniformly continuous then? if it isn't, can you guys think of any other examples? thanks
-
To prove that $f(x)=\sin(x^2)$ is not uniformly continuous, let $\epsilon=\frac{1}{2}$. You want to show that for every $\delta\gt 0$ there exists $x$ and $y$ (which may depend on $\delta$) such that $|x-y|\lt \delta$, but $|f(x)-f(y)|\geq \frac{1}{2}$. Suggestion: try to pick a $y$ where $f(y)=0$, and a very nearby $x$ where $f(1)=\pm 1$. You want $y^2=n\pi$ for some integer $n$, and $x^2$ to be $\frac{1}{2}\pi$ away. If you cannot produce a pair explicitly, maybe you can show that you can pick them as close as you want anyway, provided $x$ and $y$ are large enough (which agrees with your observation that the derivative is unbounded). | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.970687766704745,
"lm_q1q2_score": 0.8109936487495161,
"lm_q2_score": 0.8354835371034368,
"openwebmath_perplexity": 126.9768867020721,
"openwebmath_score": 0.938330352306366,
"tags": null,
"url": "http://math.stackexchange.com/questions/23443/function-mathbbr-to-mathbbr-that-is-continuous-and-bounded-but-not-unifo"
} |
cc.complexity-theory, ds.algorithms, complexity-classes, time-complexity, sat
We have $2^{o(n)} = \bigcap_{c > 0} O(2^{cn})$.
Proof: For the inclusion $2^{o(n)} \subseteq \bigcap_{c > 0} O(2^{cn})$.
Let $f \in o(n)$, then we know that for each $c > 0$ we can find an $N_c$ such that for $n > N_c$ we have $f(n) < cn$, or $2^{f(n)} < 2^{cn}$ which gives this inclusion. For the inclusion $\bigcap_{c > 0} O(2^{cn}) \subseteq 2^{o(f)}$. Let be some function $g : \mathbb N \to \mathbb N \in \bigcap_{c > 0} O(2^{cn})$, i.e., for each $c > 0$ we have some $N_c$ such that for $n > N_c$ we have $g(n) < 2^{cn}$. Taking logarithms this gives $\log g(n) < cn$. So we have $\log g(n) \in o(n)$.
But ETH is about algorithms, so if we can find for each $c > 0$ some algorithm running in time $O(2^{cn})$, this does not imply that we have a single algorithm running in the intersection of those times, i.e., in $2^{o(n)}$ by the above. So there is still the possiblity that we cannot solve a problem in $2^{o(n)}$, but we can solve it by giving for each $c > 0$ some algorithm $A_c$ that solves it in $O(2^{cn})$. So claiming that something is not solvable in $2^{o(n)}$ is actually a stronger claim than saying we have a $c > 0$ such that the problem cannot be solved in $O(2^{cn})$. | {
"domain": "cstheory.stackexchange",
"id": 4588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "cc.complexity-theory, ds.algorithms, complexity-classes, time-complexity, sat",
"url": null
} |
optics, reflection, geometric-optics
or written in terms of focal lengths: $$f_{calculated}=f_{given}\sqrt2$$
And so a horizontal ray that will reflect $90^{\circ}$ must reflect at a point with horizontal position $\frac{R\sqrt{2}}{2}$ which is also the horizontal positon of the intersection of the ray and principal axis. This disagrees with the book's claim that the intersection happens at a point with horizontal postion $\frac{R}{2}$. | {
"domain": "physics.stackexchange",
"id": 83026,
"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": "optics, reflection, geometric-optics",
"url": null
} |
satisfiability, sat-solvers, constraint-satisfaction
So my question is whether this is not used simply for empirical reasons (say, it would be slower for most benchmarks), or if there is a deeper flaw about it that I am missing.
A secondary question is: if this is a merely empirical issue, then is there some simple argument predicting this from the description of the technique alone, or is it something that would need to be observed in practice? Or, in other words, if this is a bad idea, is it so in principle, or just empirically?
Addendum:
It has been suggested by an answer that the notion of watched literals implies the use of DPLL which implies tracking which clauses have been satisfied, and that therefore the question does not make sense. It is true that watched literals are used in the context of DPLL, but it is not true that this means tracking satisfied clauses.
The paper on Chaff, which defined watched literals, describes DPLL in pseudo-code as
while (true) {
if (!decide()) // if no unassigned vars
return(satisifiable);
while (!bcp()) {
if (!resolveConflict())
return(not satisfiable);
}
} | {
"domain": "cs.stackexchange",
"id": 4665,
"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": "satisfiability, sat-solvers, constraint-satisfaction",
"url": null
} |
# integrate hyperbolic sine
#### bowlbase
##### New member
integrate Sinh4(x)
I have been struggling with this problem for a week. I know the answer because of wolfram but I cannot see how it gets it. Honestly, I can't even decide what to make my substitution as. I haven't really had problems with any other questions from our homework but this one and its killing me. Thanks for any help or guidance!
#### dwsmith
##### Well-known member
integrate Sinh4(x)
I have been struggling with this problem for a week. I know the answer because of wolfram but I cannot see how it gets it. Honestly, I can't even decide what to make my substitution as. I haven't really had problems with any other questions from our homework but this one and its killing me. Thanks for any help or guidance!
Are you aware that the integral of sinhx is coshx?
Then try this identity
$\sinh^2x = \dfrac{\cosh(2x) - 1}{2}$
and
$\cosh^2x=\dfrac{1+\cosh(2x)}{2}$
Last edited:
#### bowlbase
##### New member
(sorry for lack of latex, not sure how to start that on the new forums and I'm a bit out of practice)
Yes, so I originally thought that I should substitute u for sinh. therefore u4 dx, du/dx sinh(x) = cosh(x), then du= cosh(x) dx
so integrate (cosh(x) u4 du)?
how do I get rid of the x?
#### Prove It
##### Well-known member
MHB Math Helper
integrate Sinh4(x) | {
"domain": "mathhelpboards.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9763105238756898,
"lm_q1q2_score": 0.8071274185108681,
"lm_q2_score": 0.8267117876664789,
"openwebmath_perplexity": 911.2899165377761,
"openwebmath_score": 0.9813542366027832,
"tags": null,
"url": "https://mathhelpboards.com/threads/integrate-hyperbolic-sine.199/"
} |
programming-challenge, interview-questions, objective-c, ios
- (id)init {
if (self = [super init]) {
mustUseGPSHardware = YES;
firstTimeGPSDataRequested = YES;
lastReportedLocation = nil; // This is updated periodically, set to nil to prevent access to uknown address until update
_locationManager = [[CLLocationManager alloc] init];
if (_locationManager) {
// Attempt to force the device to use the GPS rather than WiFi or Radio Triagulation
self.locationManager.desiredAccuracy = [ @"AccuracyBest" doubleValue];
// If the user moves 100 meters then a location update should occur.
self.locationManager.distanceFilter = [@100.0 doubleValue];
// The following code checks to see if the user has authorized GPS use.
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
// Now that the configuration of the CLLocationManager has been completed start updating the location.
[self.locationManager startUpdatingLocation];
}
self.locationManager.delegate = self;
}
return self;
}
@end
PCIBatteryDataModel.h
//
// PCIBatteryDataModel.h
// PCIDataModelLibrary
//
//
// Provides public interfaces to get the battery level and battery state from the device.
#import <Foundation/Foundation.h>
@interface PCIBatteryDataModel : NSObject
- (id)init;
- (NSString *)provideBatteryLevelAndState;
- (NSString *)provideBatteryLevel;
- (NSString *)provideBatteryState;
@end
PCIBatteryDataModel.m
//
// PCIBatteryDataModel.m
// PCIDataModelLibrary
//
// Provides public interfaces to get the battery level and battery state from the device.
#import <UIKit/UIKit.h>
#import "PCIBatteryDataModel.h" | {
"domain": "codereview.stackexchange",
"id": 25534,
"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-challenge, interview-questions, objective-c, ios",
"url": null
} |
php, rest, curl, phpunit
// set option to add request header information to curl_getinfo output
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
// set option to return content body
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// set redirect options
if (true === $this->followRedirects) {
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
if ($this->maxRedirects > 0) {
curl_setopt($curl, CURLOPT_MAXREDIRS, $this->maxRedirects);
}
}
return $curl;
}
/**
* Method to reset curl handle
*
* @return void
*/
protected function curlTeardown() {
$this->curlClose($this->curl);
$this->curl = null;
}
/**
* Method to close cURL handle
*
* @return void
*/
protected function curlClose($curl = null) {
curl_close($curl);
}
/**
* Method to execute cURL call
*
* @return void
* @throws \Exception
*/
protected function curlExec() {
$curlResult = curl_exec($this->curl);
if($curlResult === false) {
// our cURL call failed for some reason
$curlError = curl_error($this->curl);
$this->curlTeardown();
throw new \Exception('cURL call failed with message: "' . $curlError. '"');
}
// set object properties for request/response
$curlInfo = curl_getinfo($this->curl);
$this->responseInfo = $curlInfo;
$this->requestHeader = $this->responseInfo['request_header'];
$this->responseCode = $this->responseInfo['http_code'];
$this->responseBody = $curlResult;
$this->curlTeardown();
} | {
"domain": "codereview.stackexchange",
"id": 24574,
"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, rest, curl, phpunit",
"url": null
} |
python, classes, extension-methods
accp1 = Accuracy(p1)
accp1.data
[3.0, 3.0, 4.0, 8.0, -9999, -9999, -9999, -9999, -9999] If you plan on calling the four functions ra_or, ra_os, sim_size and AFI outside of Accuracy then it is good to keep them as functions. If they never get called except through Accuracy, then they should be made methods.
Classes can help organize complex code, but they generally do not make your code faster. Do not use a class unless there is a clear advantage to be had -- through inheritance, or polymorphism, etc.
If you want faster code which uses less memory, avoid using a class here. Just define functions for each attribute.
If you want "luxurious" syntax -- the ability to reference each statistic via an attribute, then a class is fine.
If you plan on instantiating instances of Accuracy but not always accessing all the attributes, you don't need to compute them all in __init__. You can delay their computation by using properties.
@property
def area(self):
return self.ref.area
Note that when you write accp1.area, the area method above will be called. Notice there are no parentheses after accp1.area.
To be clear, the advantage to using properties is that each instance of Accuracy will not compute all its statistical attributes until they are needed. The downside of using a property is that they are recomputed everytime the attribute is accessed. That may not be a downside if self.ref or self.seg ever change.
Moreover, you can cache the result using Denis Otkidach's CachedAttribute decorator. Then the attribute is only computed once, and simply looked up every time thereafter.
Don't use an arbitrary value for noData like noData = -9999. Use noData = np.nan, or simply skip noData and use np.nan directly.
import numpy as np
from shapely.geometry import Polygon
nan = np.nan
class Accuracy(object):
def __init__(self, ref, seg=None):
self.ref = ref
self.seg = seg
@property
def area(self):
return self.ref.area | {
"domain": "codereview.stackexchange",
"id": 3456,
"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, classes, extension-methods",
"url": null
} |
concurrency, parallel-computing, threads, multi-tasking
Title: Can Multiprocessor Systems Implement Both Temporal Multithreading and Simultaneous Multithreading? I am aware that multiprocessor systems often implement simultaneous multithreading in order to allow multiple threads to run on different CPUs. I am also aware that uni-core systems often implement temporal multithreading (fine-grained/preemptive or coarse-grained/cooperative) to allow for a more efficient use of the CPU through the use of context switches.
However, I am curious whether it is possible (or logical) to have a simultaneously multithreaded system also allow for the time-sharing between threads on each CPU, which is prevalent in temporal multithreading systems. Sure. You can simultaneously run multiple threads on different CPUs in parallel; and also a single CPU can context switch between threads (i.e., both what you are calling simultaneous multithreading + temporal multithreading). Nothing prevents it. | {
"domain": "cs.stackexchange",
"id": 12113,
"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": "concurrency, parallel-computing, threads, multi-tasking",
"url": null
} |
electric-circuits, electric-current, electrical-resistance, capacitance, inductance
$$\vec E_c \ne \vec E_p$$
But what is $\vec E_p$ then? It doesn't seem like an electrostatic field since the voltage $V(t)$ provided by the capacitor is time dependent.
What is the mechanism that keeps accelerating the particles, so drifting velocity increases to its maximum, as the voltage drops to zero? And how does this mechanism correspond to $\vec E_p$? Your assumption that the current "keeps increasing" while the capacitor electric field is decreasing does not seem to correspond to what happens.
Let's start with a charged capacitor at a voltage Vo, in a circuit where the discharging resistor is separated by a switch.
Before the switch is flipped, the capacitor has a charge +Qo on one plate and a charge -Qo on the other one. Well, more or less because the wire and the switch contact will become part of the conducting body and some charge will be present there, too, but let's not look into this now.
When you flip the switch, the opposite charges on the two plates will start to flow (it's only electrons, in reality), and the plate with an excess of electrons will start to lose them while the opposite plate will start to gain them. All of this through the switch and the resistor which limit the maximum current to Vo/R.
So the current starts at this value (note 1) with an abrupt step, and then as the plates get depleted it decreases as the voltage across the capacitor decreases.
Note 1: if your question is about the initial rising step in the current, you need to leave circuit theory and solve Maxwell's equations and take into account the role of surface charge - not only in the capacitor, but in the wires as well.
Things get fairly complicated pretty quick.
The small field E = j/sigma inside the conducting wires is the result of the superposition of the electric fields due to all surface and interface charges, and it is quite different from the field between the plates of the capacitor. | {
"domain": "physics.stackexchange",
"id": 90898,
"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-circuits, electric-current, electrical-resistance, capacitance, inductance",
"url": null
} |
c, database, circular-list, embedded
The conventional, well-understood means is to use a break statement:
for(int i = 0 ; i < BUCKET_MAX_FEEDS ; i++) {
//found it?
if(data == registeredFeed[i]) {
//Get the slot index
slotIdx = i;
break;
}
}
In this case, it's probably best to simply return from the function instead.
int8_t BucketCheckDataAvailable(void){
//Bucket is empty?
if(cBucketBufTail == cBucketBufHead){
return(false);
}
return(true);
}
The patter if (c) return true; else return false; is over complex - just return the condition directly (and why are we returning a bool as int8_t?):
bool BucketCheckDataAvailable(void)
{
// Bucket is not empty?
return cBucketBufTail != cBucketBufHead;
}
Also, no need for redundant comparisons against false:
if(BucketCheckDataAvailable() == false){
return(false);
}
becomes simply
if (!BucketCheckDataAvailable()) {
return false;
}
What's going on here?
/****************************************************************
* Function Name : BucketGetTimeStamp
* Params : None.
****************************************************************/
int8_t BucketPutGetTimeStamp(uint32_t *timestamp){
That's one reason not to repeat code information in comments!
Here's a loop that has a lot of duplication: | {
"domain": "codereview.stackexchange",
"id": 40696,
"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, database, circular-list, embedded",
"url": null
} |
javascript, jquery, functional-programming, ajax
//Icons logic
if (description == "broken clouds" || "scattered clouds") {
$("i").addClass("wi-cloudy");
} else if (description == "few clouds") {
$("i").addClass("wi-cloud");
} else if (description == "clear sky") {
$("i").addClass("wi-day-sunny");
} else if (description == "shower rain" || "rain") {
$("i").addClass("wi-rain");
} else if (description == "thunderstorm") {
$("i").addClass("wi-storm-showers");
} else if (description == "snow") {
$("i").addClass("wi-snowy");
} else if (description == "mist") {
$("i").addClass("wi-dust");
};
});
});
}
You can find the rest of my code in the gist here.
Move your APPID and API url from your code an into constants. That way, they're readily visible and easily configurable.
Move the creation of your API url into a function, that way it's easily modifiable. In addition, use $.param to construct the query portion of your URL. jQuery encodes the params for you. If you can do ES6, you can simplify using shorthand literal notation and template strings
function getApiUrl(lat, lon){
return `${API_URL}?${$.param({lat, lon, APPID})}`;
} | {
"domain": "codereview.stackexchange",
"id": 18047,
"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, functional-programming, ajax",
"url": null
} |
performance, c, matrix, cryptography
Title: Encryption/decryption by matrix multiplication in C I need to encrypt and decrypt text, image and video with a program in C with a matrix.
My program is working but it's really slow, how can I improve its speed ?
specially for the decrypt part.
Each matrix have an identity part and a filling part.
For encryption, I only do a matrix multiplication of each hex of ascii I get from files.
There is my code for decryption:
In source_decode I have the name of the file I need to decrypt.
In matrice_identity I have an array that contain the order of the matrix identity hidden in the matrix.
For example for a matrix like:
10001111
11000111
10100100
10010010
The matrice_identity will contain {4,1,2,3}, because the column 4 (where columns are numbered starting from 0) is 1000, the column 1 is 0100, column 2 is 0010, and column 3 is 0001. Other columns are just here to fill.
void decode_it(char* source_decode ,int* matrice_identity){
FILE* source_file = NULL;
source_file = fopen(source_decode, "rb");
// that's to make difference between the original one, and the decrypted one.
char* exetention = "d";
strcat(source_decode, exetention);
FILE* decoded_file = NULL;
decoded_file = fopen(source_decode, "wb");
if(decoded_file != NULL){
int carac;
if(source_file != NULL){
int i = 0;
int j = 0;
int octet1[8] = {0};
int octet2[8] = {0};
int result[8] = {0};
//encrypted file are writed in acsii, so here, i get an ascii number.
carac = fgetc(source_file);
while(feof(source_file) == 0){ | {
"domain": "codereview.stackexchange",
"id": 28471,
"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": "performance, c, matrix, cryptography",
"url": null
} |
javascript, performance, jquery
Title: Slow Javascript code to get Taxonomy terms from Sharepoint We have the following code which takes about 5 seconds in a modern computer, however the application is also executed on old PCs with Windows XP, and in there it takes 5 minutes to load. I know the old pcs are slow, but 5 minutes its just ridiculous slow, this code was developed by someone else and now we have to improve it.
Any suggestion is welcome.
<script type="text/javascript">
$(document).ready(function () {
// limpia la localStorage con cambios anteriores
if (sessionStorage.getItem("limp")==null){
localStorage.clear();
sessionStorage.setItem("limp","1");
}
var scriptbase = "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js");
ExecuteOrDelayUntilScriptLoaded(re, "SP.Runtime.js");
})
function re (){
$("div[webpartid=608c8fe4-e5db-49de-8550-840b1706ba1c]").hide();
var scriptbase = "/_layouts/15/";
$.getScript(scriptbase + "SP.js", function(){
$.getScript(scriptbase + "SP.Taxonomy.js");
});
SetFullScreenMode(true);
PreventDefaultNavigation();
}
var metaFieldName = "SIG"; //Change to your site column names
var lvl; //Handle the different pages
var anterior;
var filterOutput1;
var TaxConfiguration = {
SspId: "",
GroupId: "",
TermSetId: "",
Configuration: "",
FieldName: "",
ParseConfiguration: function () {
xmlDoc = $.parseXML(this.Configuration);
xml = $(xmlDoc);
var fieldDef = xml.find("Field");
this.FieldName = $(fieldDef).attr("DisplayName"); | {
"domain": "codereview.stackexchange",
"id": 11209,
"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, performance, jquery",
"url": null
} |
ros
ros-indigo-tf2-msgs ros-indigo-tf2-py ros-indigo-tf2-ros ros-indigo-urdf
ros-indigo-urdf-parser-plugin ros-indigo-urdf-tutorial ros-indigo-xacro
shiboken sip-dev x11proto-composite-dev x11proto-core-dev
x11proto-damage-dev x11proto-dri2-dev x11proto-fixes-dev x11proto-gl-dev
x11proto-input-dev x11proto-kb-dev x11proto-randr-dev x11proto-render-dev
x11proto-xext-dev x11proto-xf86vidmode-dev x11proto-xinerama-dev
xorg-sgml-doctools xtrans-dev
The following packages will be upgraded:
curl fontconfig-config libcurl3 libfontconfig1 libgcrypt11 libharfbuzz-icu0
libharfbuzz0b libidn11
8 to upgrade, 258 to newly install, 0 to remove and 44 not to upgrade.
Need to get 490 kB/98.2 MB of archives.
After this operation, 399 MB of additional disk space will be used.
Do you want to continue? [Y/n] | {
"domain": "robotics.stackexchange",
"id": 25719,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros",
"url": null
} |
c#, object-oriented, design-patterns, unity3d
ListRange.ItemsList = numList;
ListRange.Index = Random.Range(1, 11);
}
} Use Strategy pattern:
Example:
public interface RangeControlLogic {
void ChangeValue(int direction);
void UpdateValue();
void OnValueChanged();
}
public class NoneListRangControl : RangeControlLogic {
public float Stepping = 5;
float m_fMinRange = 10;
float m_fMaxRange = 1000;
float m_fValue;
public float Value
{
get { return m_fValue; }
set
{
m_fValue = value;
UpdateValue();
}
}
public float MinRange
{
get { return m_fMinRange; }
set
{
m_fMinRange = value;
UpdateValue();
}
}
public float MaxRange
{
get { return m_fMaxRange; }
set
{
m_fMaxRange = value;
UpdateValue();
}
}
public void ChangeValue (int direction)
{
// your code here...
}
public void UpdateValue ()
{
// your code here...
}
void OnValueChanged ()
{
// your code here..
}
}
public class ListRangControl : RangeControlLogic {
// simillar to NoneListRangControl but with different implementation
}
Then you use composition to plug those objects in the RangControl:
public class RangeControl : MonoBehaviour {
public RangeControlLogic logic;// this will be either NoneListRangControl or ListRangControl
public void ChangeValue(int direction)
{
logic.ChangeValue(direction);
}
public void UpdateValue()
{
logic.UpdateValue();
}
} | {
"domain": "codereview.stackexchange",
"id": 24810,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, design-patterns, unity3d",
"url": null
} |
The expected value is the weighted average. "Normally" (in daily life), when you take an average, all the values have the same weight. The average salary of your family members, for instance. But say you wanted the average salary in your country, then it's nice to work with, say, the probability of a certain salary being had. Making this latter problem more concrete, you could approximate the average national salary by taking every integer multiple of $1000, and finding out the proportion of people with this salary. Then the weighted average gives you the true national average salary. - There were two questions. The first question: Why don't we square the$x$values in the calculation for the expected value of$X^2$. Suppose$Y = g(X). \begin{aligned} E(Y) & \stackrel{\text{(a)}}{=} \sum_{y\in{S_Y}}yP_Y(y)\\ & \stackrel{\text{(b)}}{=} \sum_{y\in{S_Y}}y\sum_{x:g(x) = y}P_X(x)\\ & \stackrel{\text{(c)}}{=} \sum_{y\in{S_Y}}\sum_{x:g(x) = y}yP_X(x)\\ & \stackrel{\text{(d)}}{=} \sum_{y\in{S_Y}}\sum_{x:g(x) = y}g(x)P_X(x)\\ & \stackrel{\text{(e)}}{=} \sum_{x\in{S_X}}g(x)P_X(x)\\ \end{aligned} (a): The definition of expected value of a discrete random variable, as you have supplied. (b): Because the probability of random variableY$taking on a value$g(x)$is equal to the sum of the probability of all the values of$x$which will map to$g(x)$. (c): Interchanging the summation. (d): Because of the condition | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9848109538667758,
"lm_q1q2_score": 0.8882213565726966,
"lm_q2_score": 0.9019206712569267,
"openwebmath_perplexity": 282.1667617092513,
"openwebmath_score": 0.9639572501182556,
"tags": null,
"url": "http://math.stackexchange.com/questions/306425/expected-value-function"
} |
0.3807 0.2807 0.1799 0.1273 0.0157 0.5000 0.5000
Columns 8 through 10
0.5000 0.5000 0.2689
Back to the top
## Lab exercises
Associate each of the Matlab functions min, max, sum, prod, cumsum, cumprod, mean, median, std with exactly one mathematical expression below. Then, compute the value of each mathematical expression by two different ways:
1. Using a single Matlab function
2. Using a for loop
Compare your results to make sure you get the same result for each case.
Put all of your commands into a script containing your solution to each problem. To start, first create an array $x$ of 100 random values using the rand function. For example,
x = rand(100,1);
You will use this array for each of the exercises. | {
"domain": "boisestate.edu",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9825575121992375,
"lm_q1q2_score": 0.81878934325781,
"lm_q2_score": 0.8333245973817159,
"openwebmath_perplexity": 983.0283971704114,
"openwebmath_score": 0.47825124859809875,
"tags": null,
"url": "https://math.boisestate.edu/~calhoun/teaching/scientific-computing-math-365/labs/lab_4/html/lab_4.html"
} |
ros, rosbag, syncronization, timer, clock
Title: Rosbag and simulated time
Hello all,
I am trying to run a bag file if simulated time but I am not succeeding on it. Here is what happens:
After I run the bag file with the command
rosbag play --clock -l laser_scanner3.bag
I am checking the timestamp published by the topic \clock, i.e. the simulated time, and the timestamp presented in another topic, which is not the same as the one from the \clock topic. I need to solve this dyssynchrony, because, otherwise, I will not be able to use the transformations from TF.
I know that this file were originally recorded with ORCA and after transformed in .bag format. Maybe, the issue is here.
Any guess on how I can solve this issue?
Thanks!
Originally posted by Randerson on ROS Answers with karma: 236 on 2016-09-19
Post score: 0
The problem was related with a lack of sync between the several timetamps from the proper bagfile. The solution is well documented here!!!
Originally posted by Randerson with karma: 236 on 2016-09-19
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 25796,
"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, rosbag, syncronization, timer, clock",
"url": null
} |
\end{align} Therefore, \begin{align} f(x) &=a+a(x-a)+\frac{(x-a)^2}{2a}-\frac{(x-a)^3}{6a^4}+\frac{(1+3a)(x-a)^4}{24a^8}\\[6pt] &-\frac{(1+3a+10a^2+15a^3)(x-a)^5}{120a^{13}}\\ &+\frac{\left(1+3a+10a^2+30a^3+55a^4+105a^5+105a^6\right)(x-a)^6}{720a^{19}}+\dots\tag{8} \end{align} | {
"domain": "stackexchange.com",
"id": null,
"lm_label": "1. YES\n2. YES",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9744347838494567,
"lm_q1q2_score": 0.8243157398324636,
"lm_q2_score": 0.8459424411924673,
"openwebmath_perplexity": 368.3900823405286,
"openwebmath_score": 0.9637298583984375,
"tags": null,
"url": "https://math.stackexchange.com/questions/1438651/first-order-differential-equation-involving-inverses"
} |
ros2, clion, ros-crystal
add_subdirectory(src/ros2/rosidl_typesupport_opensplice/opensplice_cmake_module)
add_subdirectory(src/ros2/rosidl_typesupport_opensplice/rosidl_typesupport_opensplice_c)
add_subdirectory(src/ros2/rosidl_typesupport_opensplice/rosidl_typesupport_opensplice_cpp)
add_subdirectory(src/ros2/rosidl_typesupport/rosidl_typesupport_c)
add_subdirectory(src/ros2/rosidl_typesupport/rosidl_typesupport_cpp)
add_subdirectory(src/ros2/rviz/rviz)
add_subdirectory(src/ros2/rviz/rviz2)
add_subdirectory(src/ros2/rviz/rviz2/test)
add_subdirectory(src/ros2/rviz/rviz2/test/tools)
add_subdirectory(src/ros2/rviz/rviz_assimp_vendor)
add_subdirectory(src/ros2/rviz/rviz_common)
add_subdirectory(src/ros2/rviz/rviz_default_plugins)
add_subdirectory(src/ros2/rviz/rviz_ogre_vendor)
add_subdirectory(src/ros2/rviz/rviz_rendering)
add_subdirectory(src/ros2/rviz/rviz_rendering_tests)
add_subdirectory(src/ros2/rviz/rviz/src)
add_subdirectory(src/ros2/rviz/rviz/src/image_view) | {
"domain": "robotics.stackexchange",
"id": 32769,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ros2, clion, ros-crystal",
"url": null
} |
general-relativity, black-holes, event-horizon
Title: Is it possible to escape from within event horizon? I always think that it is not possible to escape from within event horizon. However, some one recently told me with deep conviction that it is possible with sustained energy output. I countered with calculations in Schwarzschild metric showing that any objects below event horizon in the simplistic black hole will hit the singularity within a finite proper time, and was met with the response that Schwarzschild metric was a bad choice for coordinate system.
Now I understand that the singularity at $r=\frac{2GM}{c^2}$ in Schwarzschild metric is an artifact of the coordinate choice, and thus it seems that he could have a point. So my question is, can one prove that it is (or not) possible to escape from within the event horizon of a simple static black hole using a better metric? See Why is a black hole black?
It's quite true that the Schwarzschild coordinates misbehave near the horizon, but there are plenty of other coordinate systems we can use. My answer to the question I've linked above uses Gullstrand-Painlevé coordinates, but you can also use Eddington-Finkelstein or Kruskal-Szekeres coordinates. The conclusion is the same in all coordinate systems - once you have crossed the event horizon there is no way back. | {
"domain": "physics.stackexchange",
"id": 11794,
"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": "general-relativity, black-holes, event-horizon",
"url": null
} |
gazebo, gazebo-9
<gazebo reference="bumper">
<sensor name="bumper_sensor" type="contact">
<always_on>true</always_on>
<update_rate>30</update_rate>
<contact>
<collision>sensor_collision</collision>
</contact>
<plugin name="bumper_plugin" filename="libgazebo_ros_bumper.so">
<bumperTopicName>bumper_sensor</bumperTopicName>
<frameName>bumper</frameName>
</plugin>
</sensor>
</gazebo>
</robot>
simple.world
<?xml version="1.0" encoding="utf-8"?>
<sdf version="1.4">
<world name="default">
<include>
<uri>model://sun</uri>
</include>
<gravity>0 0 -9.8</gravity>
<include>
<uri>model://ground_plane</uri>
</include>
</world>
</sdf>
launch file
<launch>
<include file="$(find gazebo_ros)/launch/empty_world.launch">
<arg name="world_name" value="$(find simulation_app)/worlds/simple.world"/>
<arg name="paused" value="false"/>
<arg name="use_sim_time" value="true"/>
<arg name="gui" value="true"/>
<arg name="headless" value="false"/>
<arg name="debug" value="false"/>
<arg name="verbose" value="true"/>
</include> | {
"domain": "robotics.stackexchange",
"id": 4445,
"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, gazebo-9",
"url": null
} |
scrnaseq, seurat, splitseq
Title: What column and row naming requirements exist with Seurat (context: when loading SPLiT-Seq data) I'm trying to use Seurat for the first time and am learning about single-cell analysis for the first time, and I'm doing so with split-seq data. (Full disclosure: I'm also a lightweight when it comes to R.)
When Read10X didn't work on the mtx and associated files output by the split-seq-pipeline no matter how much I tried to make it look exactly like a 10x dataset (based on numerous examples and descriptions), I tried converting my sparse market matrix format into a dense tsv format (see update below for a sample of the file) and I read it in using:
dge_data <- as.matrix(read.table("DGE.tsv", sep="\t", header=TRUE))
pbmc <- CreateSeuratObject(counts = dge_data, min.cells = 3, min.features = 200, project = "SPLITSEQ_TT", assay = "RNA") | {
"domain": "bioinformatics.stackexchange",
"id": 1374,
"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": "scrnaseq, seurat, splitseq",
"url": null
} |
javascript, html5, ajax, async-await, ecmascript-8
A clearer separation of roles with fetch and parsing as functions rather than the single async function.
Data is also all over the place with the graph settings declared at the top and then more in the function that creates the graph.
General points | {
"domain": "codereview.stackexchange",
"id": 32883,
"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, html5, ajax, async-await, ecmascript-8",
"url": null
} |
Yes ;)
- 3 months, 3 weeks ago
That was easy.. $2^{16}$
- 3 months, 3 weeks ago
So, the question which I gave is of no use?
- 3 months, 3 weeks ago
The problem hasn't got a unique solution. A more interesting problem would be: How many solutions are there? But I think this is a very time expensive problem (at least if you don't want to program it).
- 3 months, 3 weeks ago
I don't know programming :(
- 3 months, 3 weeks ago
I think it's possible that I don't understand the question. (edit: Narrator: "He didn't understand the question.")
The lowest composite number I can generate with $2$ distinct factors is $2 \times 3 = 6 ( = 3! )$
The lowest composite number I can generate with $3$ distinct factors is $2 \times 3 \times 4 = 24 ( = 4! )$
...
The lowest composite number I can generate with $n$ distinct factors is $(n+1)!$
...
The lowest composite number I can generate with $28$ distinct factors is $29! = 8841761993739701954543616000000$. This has a lot more than 6 digits. What is it that I don't understand here?
(Additional, just for laughs, if I insist that the $28$ factors are prime factors, I get: $2566376117594999414479597815340071648394470$.)
- 3 months, 3 weeks ago
@Stef Smith, Sir, I did not understand what you mean. Please elaborate!
- 3 months, 3 weeks ago
A misunderstading of how factors work. Some days my brain doesn't work so well. :)
- 3 months, 3 weeks ago
Oh no problem then :)
- 3 months, 3 weeks ago
Hey Stef, The number 24 has more than 3 factors. It has 8 factors: 1, 2, 3, 4, 6, 8, 12, 24. Therefore, applying the factorial function does not work because 29! factorial has way more factors than 29.
I hope this helps :)
- 3 months, 3 weeks ago
Ah... I understand. Thanks. | {
"domain": "brilliant.org",
"id": null,
"lm_label": "1. YES\n2. YES\n\n",
"lm_name": "Qwen/Qwen-72B",
"lm_q1_score": 0.9843363540453381,
"lm_q1q2_score": 0.8586832244515898,
"lm_q2_score": 0.8723473647220787,
"openwebmath_perplexity": 900.9216498143144,
"openwebmath_score": 0.6608328223228455,
"tags": null,
"url": "https://brilliant.org/discussions/thread/how-to-find-an-n-digit-number-with-m-number-of/"
} |
bert
Title: Building BERT tokenizer with custom data I'm wondering if there is a way to train our own Bert tokenizer instead of using pre-trained tokenizer provided by huggingface? Yes, of course, it is possible, but that implies that you need to train again the whole model, not only the tokenizer.
Here you can find the steps to do everything with the HuggingFace libraries, including a complete example. | {
"domain": "datascience.stackexchange",
"id": 11773,
"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": "bert",
"url": null
} |
java, algorithm, combinatorics
Title: Generalizing a choose operation Consider the following piece of code.
public static String[] choosePatterns(int total, int toChoose, int numOfPatterns1) {
String[] patterns = new String[numOfPatterns1];
int x = 0;
StringBuilder data = new StringBuilder("");
List<Integer> indices = IntStream.range(1, toChoose + 1).mapToObj(i -> Integer.valueOf(0)).collect(Collectors.toList());
resetIndex(indices, 0, 1, total);
while (true) {
for (Integer i = 1; i <= total; i++) {
if (! indices.contains(Integer.valueOf(i))) {
data.append(i.toString());
}
}
patterns[x++] = data.toString();
data = new StringBuilder("");
if (! incrementIndices(indices, indices.size() - 1, total)) {
break;
}
}
return patterns;
}
public static boolean resetIndex(List<Integer> indices, int posn, int value, int total) {
if (value <= total) {
indices.set(posn, value);
return posn == indices.size() - 1 ? true : resetIndex(indices, posn + 1, value + 1, total);
} else {
return false;
}
}
public static boolean incrementIndices(List<Integer> indices, int posn, int total) {
if (indices.get(posn) < total) {
indices.set(posn, indices.get(posn) + 1);
} else {
int resetPosn = posn;
do {
if (resetPosn-- == 0) return false;
} while (! resetIndex(indices, resetPosn, indices.get(resetPosn) + 1, total));
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 22469,
"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, algorithm, combinatorics",
"url": null
} |
c++, optimization, object-oriented
This will actually output
test1: 0.9 / 1
test2: 0.9 / 10.8 / 2
test3: 0.9 / 10.8 / 20.7 / 3
which is probably not what you want. So, I suggest that you convert Math into a namespace and define ostringstream s locally in each calc function.
You're using both std::cout and printf. Stick to one of them. Since you are already invested in string streams, I suggest the former.
The quit variable is redundant. You're already returning from main when chosenCalc == 4 is true. Speaking of which, I suggest that you get in the habit of writing 4 == chosenCalc instead. This way, you will get a nice compiler error if you accidentally write 4 = chosenCalc.
You're using a switch statement. Excellent! Stick to it. Add a case 4 instead of having the if(chosenCalc == 4) before the switch. Even better, add a default case so that if the user presses 5, he gets a nice error message. E.g.:
default:
std::cout << "Invalid input. Please try again." << std::endl;
continue;
Cool that you have the hang of function pointers. They have a lot of uses. However, you can do without them in this case. Simply remove FuncChosen and call the calc functions directly inside the switch. Just move the /* User Input */ section up before the switch and you got all the arguments you need. Calling a function directly is also more efficient than calling it through a pointer (since it is one less layer of indirection).
You've already got some decent C++ code. I hope that the above will get you even further. Just comment if you need some elaboration of my suggestions.
Edit:: As per you comment, I've added a little extra. If you have access to a C++11 compiler you can: | {
"domain": "codereview.stackexchange",
"id": 10394,
"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++, optimization, object-oriented",
"url": null
} |
python, python-3.x, combinatorics, math-expression-eval
# Print header
print('\t'.join(vars + [expr]))
# Print body
for vals in product(range(2), repeat=len(vars)):
locals = dict(zip(vars, vals))
result = eval(expr, NO_GLOBALS, locals)
print('\t'.join([str(v) for v in vals] + [str(result)]))
def prompt_expr():
print(__doc__)
print()
return input()
if __name__ == '__main__':
truth_table(prompt_expr()) | {
"domain": "codereview.stackexchange",
"id": 11500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, combinatorics, math-expression-eval",
"url": null
} |
newtonian-mechanics, forces, pressure
Title: Do you need less force to pick same mass having greater surface area comparison to other? Suppose a object having mass 10kg and surface area of 2cm² and another other object having same mass and surface area of 4cm². What is the pressure required to lift the object? Which one will need more force to lift the object and how surface area relates in term of lifting the object? You will need the same force to pick up the object regardless of its surface area, because you are lifting a mass in a force field, and mass does not depend on any geometrical properties the object may have. Pressure, however, is defined as $P=\frac{F}{S}$ and therefore you would need twice as much pressure to lift an object with half the other's surface. If you want to expand on this subject, I recommend Pearson's University Physics Volume I, which covers Classical (Newtonian) Mechanics with some mentions to pressure, if I remember correctly | {
"domain": "physics.stackexchange",
"id": 99704,
"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, forces, pressure",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.