source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange | llm_judgeable_groundtruth_similarity | 13991099 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am writing a program so that to click a button and according to the time you have kept your mouse down the linked note is printed. My problem is that the first click works fine but when I hold on for the second time it doesn't update and it is driving me crazy. Any help will be much appreciated. Below find the following code I am using. Thanks For the Form1: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace NoteShape{ public partial class Form1 : Form { public int duration = 0; MusicNote mn; public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { duration++; } private void button1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { timer1.Enabled = true; duration = 0; } } private void button1_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { timer1.Enabled = false; } duration = duration % 20; string bNoteShape = ""; if (duration >= 12) { bNoteShape = "SemiBreve"; } if ((duration >= 6) && (duration <= 11)) { bNoteShape = "Minim"; } if ((duration >= 3) && (duration <= 5)) { bNoteShape = "Crotchet"; } if ((duration >= 1) && (duration <= 2)) { bNoteShape = "Quaver"; } if (duration == 0) { bNoteShape = "SemiQuaver"; } mn = new MusicNote(1, bNoteShape); MessageBox.Show(bNoteShape); this.Controls.Add(this.mn); } }} For the according class: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;using System.Drawing;namespace NoteShape{ class MusicNote: PictureBox { public string path = "ImagesName\\"; public int pitch; public string noteShape; public MusicNote(int iPitch, string iNoteShape) : base() { pitch = iPitch; noteShape = iNoteShape; Location = new Point(150, 50); Size = new Size(40, 40); Bitmap bmp1 = new Bitmap(path + noteShape + ".bmp"); Image = bmp1; BackColor = Color.Transparent; } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); } }}
Now provide the response and nothing else.
| I found out a solution that could work based on JMSSecurityBundle . Instead of testing the configuration, I test the extension which will add coverage for the configuration by the way. That way, I can assert that a default configuration was set. For instance, this Extension . #My\Bundle\DependencyInjection\MyBundleExtensionclass MyBundleExtension extends Extension{ /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter("crak_landing_frontend.scalar", $config["scalar"]); $container->setParameter("crak_landing_frontend.array_node", $config["array_node"]); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); }} Could be tests like: #My\Bundle\Tests\DependencyInjection\MyBundleExtensionTestclass MyBundleExtensionTest extends \PHPUnit_Framework_TestCase{ /** * @var MyBundleExtension */ private $extension; /** * Root name of the configuration * * @var string */ private $root; public function setUp() { parent::setUp(); $this->extension = $this->getExtension(); $this->root = "my_bundle"; } public function testGetConfigWithDefaultValues() { $this->extension->load(array(), $container = $this->getContainer()); $this->assertTrue($container->hasParameter($this->root . ".scalar")); $this->assertEquals("defaultValue", $container->getParameter($this->root . ".scalar")); $expected = array( "val1" => "defaultValue1", "val2" => "defaultValue2", ); $this->assertTrue($container->hasParameter($this->root . ".array_node")); $this->assertEquals($expected, $container->getParameter($this->root . ".array_node")); } public function testGetConfigWithOverrideValues() { $configs = array( "scalar" => "scalarValue", "array_node" => array( "val1" => "array_value_1", "val2" => "array_value_2", ), ); $this->extension->load(array($configs), $container = $this->getContainer()); $this->assertTrue($container->hasParameter($this->root . ".scalar")); $this->assertEquals("scalarValue", $container->getParameter($this->root . ".scalar")); $expected = array( "val1" => "array_value_1", "val2" => "array_value_2", ); $this->assertTrue($container->hasParameter($this->root . ".array_node")); $this->assertEquals($expected, $container->getParameter($this->root . ".array_node")); } /** * @return MyBundleExtension */ protected function getExtension() { return new MyBundleExtension(); } /** * @return ContainerBuilder */ private function getContainer() { $container = new ContainerBuilder(); return $container; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13991099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1921637/']} | jdg_80841 |
stackexchange | llm_judgeable_groundtruth_similarity | 4483769 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
for example, say n = Integer.MAX_VALUE or 2^123 then O(log(n)) = 32 and 123 so a small integer. isn't it O(1) ? what is the difference ? I think, the reason is O(1) is constant but O(log(n)) not. Any other ideas ?
Now provide the response and nothing else.
| If n is bounded above, then complexity classes involving n make no sense. There is no such thing as "in the limit as 2^123 approaches infinity", except in the old joke that "a pentagon approximates a circle, for sufficiently large values of 5". Generally, when analysing the complexity of code, we pretend that the input size isn't bounded above by the resource limits of the machine, even though it is. This does lead to some slightly odd things going on around log n , since if n has to fit into a fixed-size int type, then log n has quite a small bound, so the bound is more likely to be useful/relevant. So sometimes, we're analysing a slightly idealised version of the algorithm, because the actual code written cannot accept arbitrarily large input. For example, your average quicksort formally uses Theta(log n) stack in the worst case, obviously so with the fairly common implementation that call-recurses on the "small" side of the partition and loop-recurses on the "big" side. But on a 32 bit machine you can arrange to in fact use a fixed-size array of about 240 bytes to store the "todo list", which might be less than some other function you've written based on an algorithm that formally has O(1) stack use. The morals are that implementation != algorithm, complexity doesn't tell you anything about small numbers, and any specific number is "small". If you want to account for bounds, you could say that, for example, your code to sort an array is O(1) running time, because the array has to be below the size that fits in your PC's address space, and hence the time to sort it is bounded. However, you will fail your CS assignment if you do, and you won't be providing anyone with any useful information :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4483769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_80842 |
stackexchange | llm_judgeable_groundtruth_similarity | 26014 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm reading Hatcher and I'm doing exercise 9 on page 19. Can you tell me if my answer is correct? Exercise: Show that a retract of a contractible space is contractible. Proof: Let $X$ be a contractible space, i.e. $\exists f :X \rightarrow \{ * \}$ , $g: \{ * \} \rightarrow X$ continuous such that $fg \simeq id_{\{ *\}}$ and $gf \simeq id_X$ and let $r:X \rightarrow X$ be a retraction of $X$ i.e. $r$ continuous and $r(X) = A$ and $r\mid_A = id_A$ . ( Edited using Anton's answer) Define $f^\prime := f\mid_A$ and $g^\prime := r \circ g$ . Now we need to show $f^\prime \circ g^\prime \simeq id_{ \{ * \} }$ and $g^\prime \circ f^\prime \simeq id_A$ . $f^\prime \circ g^\prime \simeq id_{ \{ * \} }$ follows from $f^\prime \circ g^\prime = id_{ \{ * \} }$ (because there is only one function $\{ * \} \rightarrow \{ * \}$ ). From $gf \simeq id_X$ we have a homotopy $H: I \times X \rightarrow X$ such that $H(0,x) = g \circ f (x)$ and $H(1,x) = id_X$ . From this we build a homotopy $H^\prime : I \times A \rightarrow A$ by defining $H^\prime := r \circ H \mid_{I \times A}$ . Then $H^\prime (0,x) = g^\prime \circ f\mid_A (x)$ and $H^\prime (1,x) = id_A$ . I'm particularly dis satisfied with the amount of detail in my reasoning but I can't seem to produce what I'm looking for. Many thanks for your help!
Now provide the response and nothing else.
| You're glossing over the most important things. You are given the information that $X$ is contractible. This means that there exists a specific homotopy $H:I\times X\to X$ which contracts the identity map. Your goal is to construct a specific homotopy $H':I\times A\to A$ which contracts the identity map. Your proof never explicitly makes use of $H$ and never explicitly (maybe not even implicitly) defines $H'$. This makes it feel like a bunch of symbol-pushing. (This isn't meant to be insulting; I'm just explaining why the proof feels unsatisfying.) Two preliminary points: $\newcommand{\pt}{{\{\ast\}}}f'=f\circ r$ isn't a map between the right things; it should be a map $A\to\pt$, but it's a map $X\to \pt$. This isn't too important since there's only one map from anything to a point, but the algebraic manipulation will be clearer if you set $f':=f|_A$. You don't need to check $f'\circ g'\cong id_\pt$ since there's only one map $\pt\to\pt$. So you only need to find a homotopy from $id_A$ to $g'\circ f'$. That is, you need to make a movie (homotopy) which continuously crushes $A$ to a point. But you already have a movie $H:I\times X\to X$ which crushes $X$ to a point (i.e. $H(0,-)=id_X$ and $H(1,-)=g\circ f$), and you have a way to retract anything in $X$ to something in $A$, so you can just retract your movie, setting $H' = r\circ H|_{I\times A}$. Then $H'(0,-) = r\circ H(0,-)|_A = r\circ id_A = id_A$ and $H'(1,-)=r\circ H(1,-)|_A = r\circ (g\circ f)|_A = r\circ g\circ f|_A = g'\circ f'$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/26014', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5798/']} | jdg_80843 |
stackexchange | llm_judgeable_groundtruth_similarity | 4066125 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Lets say I am fetching a specific episode of a series.What would be the best way to get the surrounding episodes by episode number? Simplified model: class Episode(models.Model): series = models.ForeignKey(Series) number = models.IntegerField() For example, episode 10 would fetch episodes 8-12. Episode 1 would fetch episodes 1-5.
Now provide the response and nothing else.
| You can do this via RemoveAll using Contains: list.RemoveAll( item => !list2.Contains(item)); Alternatively, if you just want the intersection, using Enumerable.Intersect would be more efficient: list = list.Intersect(list2).ToList(); The difference is, in the latter case, you will not get duplicate entries. For example, if list2 contained 2, in the first case, you'd get {2,2,4,5} , in the second, you'd get {2,4,5} . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4066125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111874/']} | jdg_80844 |
stackexchange | llm_judgeable_groundtruth_similarity | 39644473 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was taught, that data, by default, is immutable in F#. When we reassign value to some variable, what really happens is that it rebinds the value of variable, but setting a new value is different thing. Rebinding is called Shadowing whilst setting new value is impossible if we don't say explicitly, that value of the variable is mutable. Can anyone explain to me this concept in a bit more details? What is the difference between shadowing (rebinding): let var = "new_value" and setting a new value, as: var <- "new_value" Is this a moment, that during rebinding we create another object and we assign that object's address to the variable, whereas in the second example we change the value itself? I brought that from heap/stack concept.. but I may be wrong. Thanks.
Now provide the response and nothing else.
| Shadowing is when you create a new binding that uses the same name as a previous binding. This "shadows" the original name, which hides it but doesn't change or replace it. Try this in FSI to see: let foo = 42let printFoo () = printfn "%i" foo printFoo() ;; This will print: 42val foo : int = 42val printFoo : unit -> unitval it : unit = () Then add: // ... more codelet foo = 24printfn "%i" foo // prints 24printFoo ();; This will print: 2442val foo : int = 24val it : unit = () Note that it still prints 42 when you call printFoo() - the function sees the original (unshadowed) binding, but the new print shows the new value. Using <- to mutate a value requires a mutable binding: let mutable bar = 42let printBar () = printfn "%i" barprintBar ();; This, like above, prints 42. Note that you override the default immutable behavior here with the mutable keyword. You then change the value within the mutable binding: bar <- 24printfn "%i" barprintBar ();; This will print 24 twice, since, unlike the shadowed version, the mutation changes the original binding. If you leave mutable off in the original binding, you'll get an error when using <- . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39644473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1553537/']} | jdg_80845 |
stackexchange | llm_judgeable_groundtruth_similarity | 29935915 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have as example the following code: Foo( "Test1" );void Foo(const char* const i_Test ){ // Some logic} The i_Test pointer in Foo() hold a pointer to the string in the .rodata section . Is there any way to search the i_Text pointer value in the binary file to find the related String? Or can I produce any debug info using the gcc that will hold that info?
Now provide the response and nothing else.
| If you are talking about the ELF file format, constant strings are stored in the .rodata (read-only-data) section. Basically, only instructions (code) of your program are stored in the .text section in that binary file. You can investigate these sections by using an object dump program (e.g. objdump ) like the following: objdump -drS program.o // to see .text section of your programobjdump -s -j .rodata program.o // to see .rodata section of your program In your example code above, the "Test1" string that you are passing to your Foo function will be treated as a constant string by the compiler . Thus, you can find its relative memory address before the loading stage and the i_Test pointer will be pointing to this constant string. However, if you have compiled your code as position independent (by using the -fPIC option in gcc ), you may also find that the compiler will add a writable attribute to that read-only .rodata section. Furthermore, you may also use the readelf binary utility to display detailed information about the sections of your ELF formatted object file. More information about the ELF file format can be found here | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29935915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/927768/']} | jdg_80846 |
stackexchange | llm_judgeable_groundtruth_similarity | 9779151 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i have this function in my code and I'm using throw to create meaningful errors (rather than failing silently). However, when i structure my function this way, if i call defineSandbox() with an error, it stops the whole script. //defineSandbox is in an object, for now i name "myObj"var defineSandbox = function (sandboxName,SandboxDefinition) { //validation if(!is.validString(sandboxName)) { throw statusMessages.sandbox.invalidName; } if(!is.validFunction (SandboxDefinition)) { throw statusMessages.sandbox.invalidDefinition; } //...some more validation here //...sandbox builder code if validation passes (code wasn't returned) registered.sandboxes[sandboxName] = newSandbox;};//intentional error, non-string namemyObj.defineSandbox(false); //...and so the rest of the script from here down is not executed //i can't build this sandbox anymoremyObj.defineSandbox('mySandbox',function(){...}); what i would like to have is if one call fails, it gives out an error but still tries to continue to run the script. how do i structure this code so that i can achieve that?
Now provide the response and nothing else.
| Typically, you don't want to continue execution when you manually throw a new error. If you want to have it for a logging purpose, you should consider an self-created internal solution. However, to catch a thrown error you need to invoke a try / catch statement. try { myObj.defineSandbox(false); } catch( ex ) { // execution continues here when an error was thrown. You can also inspect the `ex`ception object} By the way, you can also specify which kind of error you want to throw, for instance a type error or a reference error like throw new TypeError();throw new ReferenceError();throw new SyntaxError();etc. Complete list: MDN | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9779151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/575527/']} | jdg_80847 |
stackexchange | llm_judgeable_groundtruth_similarity | 54020250 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to combine the following three SELECT statements into a single SQL Statement: 1. SELECT TotalTime FROM Session WHERE device_uid = ${my_uid} ORDER BY StartTime DESC LIMIT 1;2. SELECT HoursAtService FROM Service WHERE device_uid = ${my_uid} ORDER BY StartTime DESC LIMIT 1;3. SELECT ServiceHours FROM Type WHERE type_uid = ${my_type_uid}; Preferably, I want to get my result as a single row with the following fields: Result:----------------------------------------------------------------uid, TotalTime, HoursAtService, ServiceHours I'm thinking that I probably need to do an inner join, but I'm not 100% sure how to approach it. Something like: SELECT uid, TotalTime, HoursAtService, ServiceHours FROM Device AS t1 INNER JOIN (... -> continues Doing a join between tables is easy enough, but how do you approach doing the join with multiple WHERE clauses for the various tables? Could someone show me how I would structure the query? EDIT - Table Schemas Device:---------------------device_uid, type_uid, ....Session:---------------------device_uid, session_uid, TotalTime, StartTime, EndTime, SessionTimeService:---------------------device_uid, service_uid, StartTime, EndTime, HoursAtServiceType:---------------------type_uid, Name, ServiceHours
Now provide the response and nothing else.
| Problem is pandas need datetime s or timedelta s for diff function, so first converting by to_timedelta , then get total_seconds and divide by 60 : df['Time_diff'] = pd.to_timedelta(df['Time'].astype(str)).diff(-1).dt.total_seconds().div(60)#alternative#df['Time_diff'] = pd.to_datetime(df['Time'].astype(str)).diff(-1).dt.total_seconds().div(60)print (df) Dev_id Time Time_diff0 88345 13:40:31 19.9666671 87556 13:20:33 15.5500002 88955 13:05:00 49.5333333 85678 12:15:28 NaN If want floor or round per minutes: df['Time_diff'] = (pd.to_timedelta(df['Time'].astype(str)) .diff(-1) .dt.floor('T') .dt.total_seconds() .div(60))print (df) Dev_id Time Time_diff0 88345 13:40:31 19.01 87556 13:20:33 15.02 88955 13:05:00 49.03 85678 12:15:28 NaN | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54020250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2427492/']} | jdg_80848 |
stackexchange | llm_judgeable_groundtruth_similarity | 56550713 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
enum SectionType: String, CaseIterable { case top = "Top" case best = "Best"}struct ContentView : View { @State private var selection: Int = 0 var body: some View { SegmentedControl(selection: $selection) { ForEach(SectionType.allCases.identified(by: \.self)) { type in Text(type.rawValue).tag(type) } } }} How do I run code (e.g print("Selection changed to \(selection)") when the $selection state changes? I looked through the docs and I couldn't find anything.
Now provide the response and nothing else.
| You can't use didSet observer on @State but you can on an ObservableObject property. import SwiftUIimport Combinefinal class SelectionStore: ObservableObject { var selection: SectionType = .top { didSet { print("Selection changed to \(selection)") } } // @Published var items = ["Jane Doe", "John Doe", "Bob"]} Then use it like this: import SwiftUIenum SectionType: String, CaseIterable { case top = "Top" case best = "Best"}struct ContentView : View { @ObservedObject var store = SelectionStore() var body: some View { List { Picker("Selection", selection: $store.selection) { ForEach(FeedType.allCases, id: \.self) { type in Text(type.rawValue).tag(type) } }.pickerStyle(SegmentedPickerStyle()) // ForEach(store.items) { item in // Text(item) // } } }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/56550713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_80849 |
stackexchange | llm_judgeable_groundtruth_similarity | 238461 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The Fourier transform $\hat u$ is defined on the Schwartz space $\mathscr S(\mathbb R^n)$by$\hat u(\xi)=\int e^{-2iΟ x\cdot \xi} u(x) dx.$It is an isomorphism of $\mathscr S(\mathbb R^n)$ and the inversion formula is$u(x)=\int e^{2iΟ x\cdot \xi} \hat u(\xi) d\xi.$The Fourier transformation can be extended to the tempered distributions$\mathscr S'(\mathbb R^n)$ with the formula$$\langle \hat T,\phi\rangle_{\mathscr S'(\mathbb R^n), \mathscr S(\mathbb R^n)}=\langle T, \hat \phi\rangle_{\mathscr S'(\mathbb R^n), \mathscr S(\mathbb R^n)}.$$Below we note $\mathcal F$ the Fourier transformation on $\mathscr S'(\mathbb R^n)$. We find easily that $\mathcal F^4=Id$, so that if $T\in\mathscr S'(\mathbb R^n)$ is such that$\mathcal F T=\lambda T$, then $\lambda$ is a fourth root of unity. Question : Are all the tempered distributions $T$ such that $\mathcal FT=T$ known? Two examples are very classical: first the Gaussians $e^{-Ο\vert x\vert^2},e^{-Ο\langle Ax,x\rangle } $ where $A$ is a positive definite matrix with determinant 1, second the case $$T_0=\sum_{k\in \mathbb Z^n}\delta_k,$$ where the equality $\mathcal FT_0=T_0$ is the Poisson summation formula. I think that, thanks to your answers and a reference, I found the answer: using What are fixed points of the Fourier Transform which deals with the $L^2$ case, one may guess that the fixed points of $\mathcal F$ in $\mathscr S'(\mathbb R^n)$ are$$\Bigl\{S+\mathcal F S+\mathcal F^2 S+\mathcal F^3 S\Bigr\}_{S\in \mathscr S'(\mathbb R^n)}=(Id+\mathcal F+\mathcal F^2+\mathcal F^3)(\mathscr S'(\mathbb R^n)).$$Since $\mathcal F^4=Id$ on $\mathscr S'(\mathbb R^n)$, the above distributions are indeed fixed points and if $\mathcal F T=T$, then$$T=\frac14\bigl(T+\mathcal F T+\mathcal F^2 T+\mathcal F^3 T\bigr),$$conluding the proof.
Now provide the response and nothing else.
| Given a square-integrable, positive semi-definite function $f$, with its Fourier transform $\hat{f}$, then the function $$F=f^2+\hat{f}\star\hat{f},$$ with $\star$ the convolution, is its own Fourier transform: $\hat{F}=F$. If we require that $F$ is a probability density (absolutely integrable and positive semi-definite), then any $F$ with $\hat{F}=F$ is of this form, see A. Nosratinia, Self-characteristic distributions. The decomposition $F=f^2+\hat{f}\star\hat{f}$ for a given probability density $F=\hat{F}$ is not unique, one realization is $f=\sqrt{F/2}$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/238461', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21907/']} | jdg_80850 |
stackexchange | llm_judgeable_groundtruth_similarity | 23945784 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently doing a lot of stuff with BigQuery, and am using a lot of try... except... . It looks like just about every error I get back from BigQuery is a apiclient.errors.HttpError, but with different strings attached to them, i.e.: <HttpError 409 when requesting https://www.googleapis.com/bigquery/v2/projects/some_id/datasets/some_dataset/tables?alt=json returned "Already Exists: Table some_id:some_dataset.some_table"> <HttpError 404 when requesting https://www.googleapis.com/bigquery/v2/projects/some_id/jobs/sdfgsdfg?alt=json returned "Not Found: Job some_id:sdfgsdfg"> among many others. Right now the only way I see to handle these is to run regexs on the error messages, but this is messy and definitely not ideal. Is there a better way?
Now provide the response and nothing else.
| BigQuery is a REST API, the errors it uses follow standard HTTP error conventions. In python, an HttpError has a resp.status field that returns the HTTP status code.As you show above, 409 is 'conflict', 404 is 'not found'. For example: from googleapiclient.errors import HttpErrortry: ...except HttpError as err: # If the error is a rate limit or connection error, # wait and try again. if err.resp.status in [403, 500, 503]: time.sleep(5) else: raise The response is also a json object, an even better way is to parse the json and read the error reason field: if err.resp.get('content-type', '').startswith('application/json'): reason = json.loads(err.content).get('error').get('errors')[0].get('reason') This can be:notFound, duplicate, accessDenied, invalidQuery, backendError, resourcesExceeded, invalid, quotaExceeded, rateLimitExceeded, timeout, etc. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23945784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392975/']} | jdg_80851 |
stackexchange | llm_judgeable_groundtruth_similarity | 4367737 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following value in my XML -1.8959581529998104E-4. I want to format this to the exact number it should be using XSL to give me -0.000189595815299981. format-number(-1.8959581529998104E-4,'0.000000;-0.000000') gives me NaN. Any ideas? Cheers Andez
Now provide the response and nothing else.
| XSLT 1.0 does not have support for scientific notation. This: number('-1.8959581529998104E-4') Result: NaN This: number('-0.000189595815299981') Result: -0.000189595815299981 XSLT 2.0 has support for scientific notation This: number('-1.8959581529998104E-4') Result: -0.000189595815299981 EDIT : A very simple XSLT 1.0 workaround: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="number[substring-after(.,'E')]"> <xsl:variable name="vExponent" select="substring-after(.,'E')"/> <xsl:variable name="vMantissa" select="substring-before(.,'E')"/> <xsl:variable name="vFactor" select="substring('100000000000000000000000000000000000000000000', 1, substring($vExponent,2) + 1)"/> <xsl:choose> <xsl:when test="starts-with($vExponent,'-')"> <xsl:value-of select="$vMantissa div $vFactor"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="$vMantissa * $vFactor"/> </xsl:otherwise> </xsl:choose> </xsl:template></xsl:stylesheet> With this input: <number>-1.8959581529998104E-4</number> Output: -0.00018959581529998104 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4367737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/405022/']} | jdg_80852 |
stackexchange | llm_judgeable_groundtruth_similarity | 8778492 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Haskell, like in many other functional languages, the function foldl is defined such that, for example, foldl (-) 0 [1,2,3,4] = -10 . This is OK, because foldl (-) 0 [1, 2,3,4] is, by definition, ((((0 - 1) - 2) - 3) - 4) . But, in Racket, (foldl - 0 '(1 2 3 4)) is 2, because Racket "intelligently" calculates like this: (4 - (3 - (2 - (1 - 0)))) , which indeed is 2. Of course, if we define auxiliary function flip, like this: (define (flip bin-fn) (lambda (x y) (bin-fn y x))) then we could in Racket achieve the same behavior as in Haskell: instead of (foldl - 0 '(1 2 3 4)) we can write: (foldl (flip -) 0 '(1 2 3 4)) The question is: Why is foldl in racket defined in such an odd (nonstandard and nonintuitive) way, differently than in any other language?
Now provide the response and nothing else.
| The Haskell definition is not uniform . In Racket, the function to both folds have the same order of inputs, and therefore you can just replace foldl by foldr and get the same result. If you do that with the Haskell version you'd get a different result (usually) β and you can see this in the different types of the two. (In fact, I think that in order to do a proper comparison you should avoid these toy numeric examples where both of the type variables are integers.) This has the nice byproduct where you're encouraged to choose either foldl or foldr according to their semantic differences. My guess is that with Haskell's order you're likely to choose according to the operation. You have a good example for this: you've used foldl because you want to subtract each number β and that's such an "obvious" choice that it's easy to overlook the fact that foldl is usually a bad choice in a lazy language. Another difference is that the Haskell version is more limited than the Racket version in the usual way: it operates on exactly one input list, whereas Racket can accept any number of lists. This makes it more important to have a uniform argument order for the input function). Finally, it is wrong to assume that Racket diverged from "many other functional languages", since folding is far from a new trick, and Racket has roots that are far older than Haskell (or these other languages). The question could therefore go the other way : why is Haskell's foldl defined in a strange way? (And no, (-) is not a good excuse.) Historical update: Since this seems to bother people again and again, I did a little bit of legwork. This is not definitive in any way, just my second-hand guessing. Feel free to edit this if you know more, or even better, email the relevant people and ask. Specifically, I don't know the dates where these decisions were made, so the following list is in rough order. First there was Lisp, and no mention of "fold"ing of any kind. Instead, Lisp has reduce which is very non-uniform, especially if you consider its type. For example, :from-end is a keyword argument that determines whether it's a left or a right scan and it uses different accumulator functions which means that the accumulator type depends on that keyword. This is in addition to other hacks: usually the first value is taken from the list (unless you specify an :initial-value ). Finally, if you don't specify an :initial-value , and the list is empty, it will actually apply the function on zero arguments to get a result. All of this means that reduce is usually used for what its name suggests: reducing a list of values into a single value, where the two types are usually the same. The conclusion here is that it's serving a kind of a similar purpose to folding, but it's not nearly as useful as the generic list iteration construct that you get with folding. I'm guessing that this means that there's no strong relation between reduce and the later fold operations. The first relevant language that follows Lisp and has a proper fold is ML. The choice that was made there, as noted in newacct's answer below, was to go with the uniform types version (ie, what Racket uses). The next reference is Bird & Wadler's ItFP (1988), which uses different types (as in Haskell). However, they note in the appendix that Miranda has the same type (as in Racket). Miranda later on switched the argument order (ie, moved from the Racket order to the Haskell one). Specifically, that text says: WARNING - this definition of foldl differs from that in older versions of Miranda. The one here is the same as that in Bird and Wadler (1988). The old definition had the two args of `op' reversed. Haskell took a lot of stuff from Miranda, including the different types. (But of course I don't know the dates so maybe the Miranda change was due to Haskell.) In any case, it's clear at this point that there was no consensus, hence the reversed question above holds. OCaml went with the Haskell direction and uses different types I'm guessing that "How to Design Programs" (aka HtDP) was written at roughly the same period, and they chose the same type . There is, however, no motivation or explanation β and in fact, after that exercise it's simply mentioned as one of the built-in functions . Racket's implementation of the fold operations was, of course, the "built-ins" that are mentioned here. Then came SRFI-1 , and the choice was to use the same-type version (as Racket). This decision was question by John David Stone, who points at a comment in the SRFI that says Note: MIT Scheme and Haskell flip F's arg order for their reduce and fold functions. Olin later addressed this : all he said was: Good point, but I want consistency between the two functions. state-value first: srfi-1, SML state-value last: Haskell Note in particular his use of state-value , which suggests a view where consistent types are a possibly more important point than operator order. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8778492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1137126/']} | jdg_80853 |
stackexchange | llm_judgeable_groundtruth_similarity | 4589731 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I "abuse" blame (or some better suited function, and/or in conjunction with shell commands) to give me a statistic of how much lines (of code) are currently in the repository originating from each committer? Example Output: Committer 1: 8046 LinesCommitter 2: 4378 Lines
Now provide the response and nothing else.
| Update git ls-tree -r -z --name-only HEAD -- */*.c | sed 's/^/.\//' | xargs -0 -n1 git blame \--line-porcelain HEAD |grep -ae "^author "|sort|uniq -c|sort -nr I updated some things on the way. For convenience, you can also put this into its own command: #!/bin/bash# save as i.e.: git-authors and set the executable flaggit ls-tree -r -z --name-only HEAD -- $1 | sed 's/^/.\//' | xargs -0 -n1 git blame \ --line-porcelain HEAD |grep -ae "^author "|sort|uniq -c|sort -nr store this somewhere in your path or modify your path and use it like git authors '*/*.c' # look for all files recursively ending in .c git authors '*/*.[ch]' # look for all files recursively ending in .c or .h git authors 'Makefile' # just count lines of authors in the Makefile Original Answer While the accepted answer does the job it's very slow. $ git ls-tree --name-only -z -r HEAD|egrep -z -Z -E '\.(cc|h|cpp|hpp|c|txt)$' \ |xargs -0 -n1 git blame --line-porcelain|grep "^author "|sort|uniq -c|sort -nr is almost instantaneous. To get a list of files currently tracked you can use git ls-tree --name-only -r HEAD This solution avoids calling file to determine the filetype and uses grep to match the wanted extension for performance reasons. If all files should be included, just remove this from the line. grep -E '\.(cc|h|cpp|hpp|c)$' # for C/C++ filesgrep -E '\.py$' # for Python files if the files can contain spaces, which are bad for shells you can use: git ls-tree -z --name-only -r HEAD | egrep -Z -z '\.py'|xargs -0 ... # passes newlines as '\0' Give a list of files (through a pipe) one can use xargs to call a command and distribute the arguments. Commands that allow multiple files to be processed obmit the -n1 . In this case we call git blame --line-porcelain and for every call we use exactly 1 argument. xargs -n1 git blame --line-porcelain We then filter the output for occurences of "author " sort the list and count duplicate lines by: grep "^author "|sort|uniq -c|sort -nr Note Other answers actually filter out lines that contain only whitespaces. grep -Pzo "author [^\n]*\n([^\n]*\n){10}[\w]*[^\w]"|grep "author " The command above will print authors of lines containing at least one non-whitespace character. You can also use match \w*[^\w#] which will also exclude lines where the first non-whitespace character isn't a # (comment in many scripting languages). | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4589731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_80854 |
stackexchange | llm_judgeable_groundtruth_similarity | 2626533 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So basically I want to show: $\aleph_{\alpha}^{\aleph_{1}} = \aleph_{\alpha}^{\aleph_{0}}\cdot2^{\aleph_1}$, Where $\omega\leq\alpha<\omega_1$ There is a proof that I found; $\aleph_\alpha^{\aleph_1} = \aleph_\alpha^{\aleph_0}\cdot 2^{\aleph_1}$ for all $\omega \le \alpha < \omega_1$ But I don't understand his proof for the limit case of $\alpha$. To be more specific, I dont understand why $ \left( \sup_{\omega \le \beta < \alpha} \aleph_{\beta}\right)^{\aleph_1} \le \left( \prod_{\omega \le \beta < \alpha} \aleph_{\beta}\right)^{\aleph_1}$ Any insights or help is deeply appreciated. Cheers
Now provide the response and nothing else.
| For each $\beta$ satisfying $\omega \leq \beta < \alpha$, $$\aleph_\beta \leq \prod_{\omega \leq \beta < \alpha} \aleph_\beta$$ therefore $$\sup_{\omega \leq \beta < \alpha} \aleph_\beta \leq \prod_{\omega \leq \beta < \alpha} \aleph_\beta$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2626533', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/306068/']} | jdg_80855 |
stackexchange | llm_judgeable_groundtruth_similarity | 86262 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose a list of items such as: L1 = RandomReal[{0, 100}, 1000]; I need to find the position of each k-neighbor in the original list. And very quickly if possible. As we can see, the problem is divided into two main parts : - The search for k-neighbors. - The search for their positions in the original list. Mathematica code On Mathematica 9.0 Doedalos : KPosition1[x_, y_] := Block[ {step0, step1, step2}, step0 = Range[1, Length@x, 1]; step1 = (Nearest[x, x[[#]], y][[2 ;; -1]]) & /@ step0; step2 = Map[Position[x, #][[1, 1]] &, step1, {2}] ];KPosition2[x_, y_] := Block[ {step0, step1, step2}, step0 = Thread[x -> Range[1, Length@x, 1]]; step1 = Nearest[step0 , #, y] & /@ x ]; Bill s : KPosition3[x_, y_] := Block[ {step0, step1, step2}, step0 = Thread[x -> Range[1, Length@x, 1]]; step1 = Nearest[step0]; step2 = Map[step1[#, y][[2 ;; -1]] &, x] ]; On Mathematica 10.0 kale : KPosition4[x_, y_] := With[ {p = PositionIndex[x]}, Map[p[#][[1]] &, Nearest[x, x, y][[All, 2 ;; -1]], {2}] ]; Mr.Wizard : KPosition5[x_, y_] := Nearest[x -> Range@Length@x, x, y]; Benchmarking Warning : Only Kposition1, Kposition2 and Kposition3 are tested. 1) By varying the length of the lists. 2) By varying the dimension of the points. Commentary On Mathematica 9.0 Sort by execution's speed : Kposition3 > Kposition2 > Kposition1 On Mathematica 10.0 If somebody wants to make the benchmarks... Currently, I has not the version 10 of Mathematica.
Now provide the response and nothing else.
| You can speed it up by only invoking the NearestFunction once: KPosition3[x_, y_] := Module[{step0, step1, nf}, step0 = Thread[x -> Range[1, Length@x, 1]]; nf = Nearest[step0]; step1 = nf[#, y] & /@ x]; Running your three timing tests gives: {0.003057, 0.004344, 0.051009} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/86262', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13407/']} | jdg_80856 |
stackexchange | llm_judgeable_groundtruth_similarity | 451558 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to find the sum of the following series? $$1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \dots + \frac{1}{n}$$ This is a harmonic progression. So, is the following formula correct? $\frac{(number ~of ~terms)^2}{sum~ of~ all ~the~ denominators}$ $\Rightarrow $ if $\frac{1}{A} + \frac{1}{B} +\frac{1}{C}$ are in H.P. Therefore the sum of the series can be written as : $\Rightarrow \frac{(3)^3}{(A+B+C)}$ Is this correct? Please suggest.
Now provide the response and nothing else.
| The exact expression for $\displaystyle H_n:=1+\frac{1}{2}+\frac{1}{3}+\cdots\ +\frac{1}{n} $ is not known, but you can estimate $H_n$ as below Let us consider the area under the curve $\displaystyle \frac{1}{x}$ when $x$ varies from $1$ to $n$ . Now note that $\displaystyle H_{n}-\frac{1}{n}=1+\frac{1}{2}+\frac{1}{3}+\cdots\ +\frac{1}{n-1}$ is an overestimation of this area by rectangles. See below And $\displaystyle H_n-1=\frac{1}{2}+\frac{1}{3}+\cdots\ +\frac{1}{n} $ is an underestimation of the area. See below (source: uark.edu ) Hence $$\large H_n-1<\int_{1}^n\frac{1}{x}dx<H_n-\frac{1}{n}\\\Rightarrow \ln n+\frac{1}{n}<H_n<\ln n+1$$ Also, Euler discovered this beautiful property of harmonic number $H_n$ that $$\large \lim_{n\rightarrow \infty}\left(H_n-\ln n\right)=\gamma\approx 0.57721566490153286060651209008240243104215933593992β¦$$ $\gamma$ is called the Euler-Mascheroni constant. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/451558', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68597/']} | jdg_80857 |
stackexchange | llm_judgeable_groundtruth_similarity | 194248 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently checking the logs an Android app creates. There, I found an interesting entry: In android's /data/data/app.being.checked/cache/ok_http_cache_dir There are quite a lot of files and there are entries where an attacker could easily read the user's E-Mail address First name Customer Id These files persist even after logging out, exiting the app and restarting the phone. Now the question remains: Is this a vulnerability which an real-world attacker would use to gain access to the user's data or would it take too much effort to do so, because he has to gain access to the user's phone, root it and then read the files or use a malicious program if the phone is already rooted. I'm asking because I'm currently checking the app in scope of a bug bounty program and it specifies that any vulnerabilities have to be usable in a real-world scenario to do damage (including getting access to sensitive data) to a user. Would this qualify for such a program?
Now provide the response and nothing else.
| The accepted solution to this is to not store the logs locally, but on a log server. Once the logs are there, you can restrict or limit access as you see fit. In some log server/aggregator solutions, you can limit a user from seeing entries that contain references to certain data (like their user accounts or machine IPs). This means that you can enable admins to see other admin activity, but not their own. You typically want to place alerts within the log server/aggregator to trigger if logs from any one machine stop coming in or are reduced below certain thresholds, which helps to detect if a local admin has prevented the logs from being shipped to the log server/aggregator. Syslog servers, SIEMs, log aggregators, ELK stacks etc. There are numerous options for you to explore. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/194248', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/187133/']} | jdg_80858 |
stackexchange | llm_judgeable_groundtruth_similarity | 169732 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Due to a security scan, I was told to not use TLS1.0. I found a link that gave me commands to use to check if a specific protocol is used/enabled. The command I ran (with output is) (Output from TLS1.0 disabled) $ openssl s_client -connect localhost:8443 -tls1CONNECTED(00000003)139874418423624:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1275:SSL alert number 40139874418423624:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl handshake failure:s3_pkt.c:598:---no peer certificate available---No client certificate CA names sent---SSL handshake has read 7 bytes and written 0 bytes---New, (NONE), Cipher is (NONE)Secure Renegotiation IS NOT supportedCompression: NONEExpansion: NONESSL-Session: Protocol : TLSv1 Cipher : 0000 Session-ID: Session-ID-ctx: Master-Key: Key-Arg : None Krb5 Principal: None PSK identity: None PSK identity hint: None Start Time: 1505770082 Timeout : 7200 (sec) Verify return code: 0 (ok)--- The link said if the protocol is enabled, it will say "Connected", else "handshake failure". However, as you can see the messages above, it says both even though I configured Tomcat to use TLS1.2. My config in the server.xml file: <Connector port="8443" protocol="HTTP/1.1" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" keystoreFile="/glide/bigdata/bdapi/keys/bdapi_keystore.jks" keystorePass="bdapi123" clientAuth="false" sslProtocol="TLSv1.2" sslEnabledProtocols="TLSv1.2"/> If I allow Tomcat to use TLS1.0, I still see CONNECTED but I also see the certificate info. (Output from TLS1.0 enabled) openssl s_client -connect localhost:8443 -tls1CONNECTED(00000003)<snip snip><snip snip>(certificate info)verify error:num=21:unable to verify the first certificateverify return:1---Certificate chain<snip snip><snip snip>(certificate info)---Server certificate-----BEGIN CERTIFICATE-----<snip snip><snip snip>(public key)-----END CERTIFICATE-----<snip snip><snip snip>(certificate info)---No client certificate CA names sentServer Temp Key: ECDH, secp521r1, 521 bits---SSL handshake has read 2121 bytes and written 357 bytes---New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-SHAServer public key is 2048 bitSecure Renegotiation IS supportedCompression: NONEExpansion: NONESSL-Session:Β Β ProtocolΒ : TLSv1Β Β CipherΒ Β : ECDHE-RSA-AES256-SHAΒ Β Session-ID: 59C0448146B0A18DE52D99C630C896E12BA9861702AB2582C2AA0658E6458B04Β Β Session-ID-ctx:Β Β Β Master-Key: <some random key>Β Β Key-Arg Β : NoneΒ Β Krb5 Principal: NoneΒ Β PSK identity: NoneΒ Β PSK identity hint: NoneΒ Β Start Time: 1505772673Β Β Timeout Β : 7200 (sec)Β Β Verify return code: 21 (unable to verify the first certificate)---read:errno=0 How do I interpret the output from openssl? Did I successfully disable TLS1.0 with the config above or since it says "CONNECTED" in both output, I didn't disable it and I'll fail the security scan again?
Now provide the response and nothing else.
| TL;TR: It is far from trivial to verify from the client that a server is not supporting TLS 1.0. You can be sure that the server supports TLS 1.0 if you get a successful connection with TLS 1.0. But you cannot be sure that the server does not support TLS 1.0 if this attempt fails. As you already realized the information given in the link you cite are at least partly wrong. Also, they are incomplete. Checking if a server has really TLS 1.0 disabled is not that simple. To understand what need to be checked to be really sure it is better to have at least a basic understanding of how the TLS-Handshake works. Note that most of what I say here is also true for SSL, which is mainly the earlier name for the same protocol family now known as TLS. Initially, the client needs to create a TCP connection to the server. This has nothing to do with TLS itself yet. And already if the TCP connection succeeds you will get CONNECTED(00000003) . If you don't get this CONNECTED then the server might be down or might not be reachable from your site, for example because a firewall is blocking the access. Thus, not getting the CONNECTED says nothing about the ability of the server to support TLS 1.0 . After the TCP connection is created the TLS part begins. In the simplest case the client sends at the beginning of the TLS handshake inside the ClientHello message the best TLS version it can and the ciphers it supports. The server replies with the best SSL/TLS protocol it supports which is equal or lower to the protocol version offered by the client. And the server picks the common cipher based on what the client offers and and what is configured to be acceptable for the server. In your specific case the client offers TLS 1.0 as the best protocol (due to the -tls1 option) and the default cipher set. The handshake will fail if the server does not support TLS 1.0 or lower OR if the server does not support any of the ciphers offered by the client. Because of the last part it is possible that the server fails with your specific client even if the server has TLS 1.0 enabled because the server does not like the ciphers offered by the client . And it gets more complex. It is common that servers support multiple certificates on the same IP address today. This is done by including the target hostname using the SNI TLS extension inside the ClientHello at the start of the TLS handshake. If there is no SNI extension or if the extension does not match any configured hostname the server will usually either send some default certificate or abort the handshake. Because of the last part it is possible that the server fails with your specific client even if the server has TLS 1.0 enabled because no SNI extension was used or it was used with the wrong hostname . openssl s_client will not use SNI by default so your attempt might simply have failed just because of a missing SNI extension. You have to use the -servername option for this and of course you need to use a hostname properly configured at the server with this option. And so far we dealt only with sane TLS stacks and a direct connection to the server. If the TLS stack is broken or if there is some broken middlebox in between (like load balancers, firewalls etc) they might make the handshake fail accidentally or on purpose even though the server supports TLS 1.0. And if you have some SSL termination in front of your server (some firewalls, load balancers or a CDN) you will not even test the properties of the server but of the system in front of it. In other words: if you get a successful TLS 1.0 connection to the server you can be sure that the server or some SSL terminator in front of it supports TLS 1.0. If the TLS 1.0 connection fails instead it does not mean for sure that the server does not support TLS 1.0. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/169732', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/19885/']} | jdg_80859 |
stackexchange | llm_judgeable_groundtruth_similarity | 32501541 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My application currently use Spring Session together with Redis as the backend. I searched into the official documentation for Spring Session but was not able to find what the default session timeout is when using that module. Also I am not sure how to change that default timeout if necessary. Can someone please advise?
Now provide the response and nothing else.
| The easiest way to configure session timeout when using redis repository is @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60) OR @EnableRedissonHttpSession(maxInactiveIntervalInSeconds = 1200) if redisson dependency is there. The session expires when it is no longer available in the repository.Timeout can be configured with setDefaultMaxInactiveInterval(int) on both RedisOperationsSessionRepository and MapSessionRepository . Default value is 30 minutes . If you are using spring boot, then as of version 1.3 it will automatically sync the value with the server.session.timeout property from the application configuration. Note that one of the shortcomings when using spring session is that javax.servlet.http.HttpSessionListener s are not invoked. If you need to react on session expiration events you can subscribe to SessionDestroyedEvent application event of your spring application. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32501541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536299/']} | jdg_80860 |
stackexchange | llm_judgeable_groundtruth_similarity | 403173 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm designing a system which reads values from a microphone and feeds it to the Arduino to calculate a few sound parameters. The measuring happens during a couple of milliseconds. The problem is that it's way faster than the processing speed of the Arduino. So I was wondering if it was a good idea to first feed all the data to a memory and then the Arduino would get it at its pace?What kind of memories do you recommend to this application?
Now provide the response and nothing else.
| You have two problems Paralleling MOSEFTs in this mode is unstable. However, you could parallel the outputs of several totally independent current sources, each with its own power device, Rs and opamp. Most MOSFETs will not like operating in linear mode like this, they are designed and specified for switching operation. Internally, MOSFETs are hundreds, if not thousands, of separate small FETs. When switched fully on, they share current nicely, their resistance changes with temperature so that any hotspots on the die shed current and cool. When operating in linear mode, they are unstable, with \$V_{GS}\$ changing with temperature so that any hotspots on the die get hotter and quickly run away thermally. If you check out the Safe Operating Area (SOA) graph for many power MOSFETs, you will find curves for various pulse lengths, but rarely a DC curve, they are simply not specified for dissipating significant power under DC conditions. During a short pulse in the linear region, or during a transition between off to on, the die does start to run away, but the linear event is over before any damage is done. If you check the SOA graph for BJTs, you will always find a DC line, they will work to DC. You have three options. Find FETs that are specified for DC operation in the linear region. These are few and far between, and relatively expensive. They are usually intended for audio amplifiers. Operate the FET at a fraction of its rated switching dissipation, perhaps 20%. This is probably safe. Use BJTs. Darlingtons often have current gains above 1000, so do not present too much of a load to your current servo opamp. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/403173', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/188772/']} | jdg_80861 |
stackexchange | llm_judgeable_groundtruth_similarity | 5960 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to debug a friend's AMP6 audio amp kit . It seems that an electrolytic smoothing cap on the output of a 5 V regulator has been soldered in backwards. This seems bad, but the component is going to be a little tricky to desolder because of its physical location. Because of this, I'm trying to be certain that this is the problem before attempting the job. Before it explodes, how does a backwards cap behave? Like a 100 ohm resistor?
Now provide the response and nothing else.
| I have actually intentionally blown up an electrolytic capacitor in order to demonstrate to students the concern of putting them in properly. When I applied 5v to it, my power supply was current limiting at over 5amps. Clearly the effective resistance is much lower then 1 ohm. However, when using a DMM to measure resistance, the DMM will only be applying a very small amount of current, small enough that you wont hurt the capacitor. As for the actual resistance shown, I am not sure of this and expect it will depend on many aspects including how the DMM is measuring and the fab process of the cap. If you have a DMM with a diode tester, I would try to use this to determine the polarity. This will put more current through the capacitor, but it shouldn't be large enough to cause it to go pop. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/5960', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/712/']} | jdg_80862 |
stackexchange | llm_judgeable_groundtruth_similarity | 7761 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There seems to be some misconceptions regarding what a switched network will protect us from, and what technologies/precautions a secure environment requires when segmenting trusted users from hostile users. Can anyone elaborate on what the real risks of switched networks, and if there are any real benefits from a security perspective?
Now provide the response and nothing else.
| Switches are not meant for security. A switch differs from a hub in that it observes packets to deduce where each host is, so that a packet aimed at a given host will be written only on the physical cable leading to that host. This is a performance optimization in that it allows more traffic to happen concurrently on a given network. The side-effect of packets not being generally broadcasted (physically) on the whole network has been historically mistaken as a security feature. But there is no guarantee that a given packet will not be copied on unwanted links; the switch operates on its own knowledge of the network layout, which is backed by a necessarily limited amount of RAM within the switch (the "ARP cache"). By "spamming" the switch you can overflow the ARP cache, leading the switch to fallback to hub-like behaviour (incoming packets are copied on every link); you can also misinform the switch with fake ethernet packets (so-called "ARP cache poisoning"). These limitations demonstrate that switched networks are not secured networks, they are just optimized networks. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/7761', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/396/']} | jdg_80863 |
stackexchange | llm_judgeable_groundtruth_similarity | 212267 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't understand how to calculate the voltage between a and b in this open circuit. Resistances like the 9 Ohms and 13 Ohms can be ignored since no current is passing through (In case we connect a Voltmeter, we consider infinite resistance). But, how can I analise or simplify the other circuits?
Now provide the response and nothing else.
| Hints What does the 13 ohm resistor bring to the party? What does the 9 ohm resistor bring to the party? What effect does the 18 ohm resistor have on the 15V source? What does the 4 ohm and 11 ohm bring to the party? The voltage across the 10 ohm resistor is ONLY due to which current source? Ditto the 5 ohm resistor Simplify based on these hints. The answer is 35V from a brief mental add-up of things - it is THAT simple (assuming I've read your scrawl correctly). | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/212267', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/97614/']} | jdg_80864 |
stackexchange | llm_judgeable_groundtruth_similarity | 1534748 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Design an efficient algorithm to sort 5 distinct - very large - keys less than 8 comparisons in the worst case. You can't use radix sort.
Now provide the response and nothing else.
| Compare A to B and C to D. WLOG, suppose A>B and C>D.Compare A to C. WLOG, suppose A>C.Sort E into A-C-D. This can be done with two comparisons.Sort B into {E,C,D}. This can be done with two comparisons, for a total of seven. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1534748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177883/']} | jdg_80865 |
stackexchange | llm_judgeable_groundtruth_similarity | 42714719 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Working on JavaScript app and need help in creating a new object from response received from ajax call. The output received is array of objects, sample format below: { "items": [ { "id": "02egnc0eo7qk53e9nh7igq6d48", "summary": "Learn to swim", "start": { "dateTime": "2017-03-04T19:00:00+05:30" } } ]} However, my component expects JS Object in the following format: {id: "e1",title: "Express",start: "Jan 13, 2010",description: "Jan 13, 2010"} Is following approach correct, please suggest better approach if any var content = { "items": [{ "id": "02egnc0eo7qk53e9nh7igq6d48", "summary": "Learn to code", "start": { "dateTime": "2017-03-04T19:00:00+05:30" } } } }; var gcalEvents = {}; var jsonObj = { "id": "e1", "title": "Oracle Application Express", "start": "Jan 13, 2010", "description": "Jan 13, 2010" }; console.log(content.items.length); for (var index = 0; index < content.items.length; index++) { var obj = content.items; console.log(obj); jsonObj.id = obj[index]["id"]; jsonObj.title = obj[index].summary; jsonObj.start = obj[index].start.dateTime; jsonObj.description = ""; console.log(jsonObj); gcalEvents[index] = jsonObj; } console.log(gcalEvents);
Now provide the response and nothing else.
| You could take a more functional approach with the following: var parsed = content.items.map(function (item) { return { id: item.id, title: item.summary, start: item.start.dateTime, description: item.start.dateTime }}) This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects. Take a look at this fuller example . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42714719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/649994/']} | jdg_80866 |
stackexchange | llm_judgeable_groundtruth_similarity | 7477679 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to ask question about DDD features. Lets say we have two aggregates and each of them contains value-object Address. Accordingly to Eric Evans DDD, we should isolate aggregates from each other, so aggregate root of first aggregate can't have a link to Address. Frankly, it doesn't seem to make sense for me, so question is how to resolve such situation? Which aggregate should contain Address? Thanks
Now provide the response and nothing else.
| You could have it using the same value object. But only do this if the aggregate roots exist in the same bounded context and hence has the same meaning for both aggregates. If the aggregates exist in different bounded contexts, then have 2 separate ones and duplicate. Leaking one bounded context's concerns into another is what Eric is trying to fight. To most, the concerns of entity vs. value object boil down to people having issues with duplication of data. We have been so trained to think in 3rd normal form of a single canonical model. DDD fights the inevitable complexity that that brings by forcing duplication where it's needed and allowing concepts that were once thought to be one into many. Hope this helps | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7477679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/167809/']} | jdg_80867 |
stackexchange | llm_judgeable_groundtruth_similarity | 11497378 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need a cross-architecture way to ensure that a float will be 4 bytes (as is on 32-bit windows). For instance, in the structs I'm creating, I'm using __int32 instead of int to ensure an integer value that is 4 bytes long. How could I do this with a float? I know that I can just substitute the value with an __int32 type; however, when casting to a float on 64-bit systems, won't I have issues?
Now provide the response and nothing else.
| I need a cross-architecture way to ensure that a float will be 4 bytes There is no analog to int32_t for floating-point values. The only cross-platform way to achieve what you want is to test for it with either runtime or static asserts. #include <cassert>int main () { assert(sizeof(float) == 4); // If control reaches this line, then you've // ensured that float is 4 bytes. // rest of your program goes here} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11497378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/510036/']} | jdg_80868 |
stackexchange | llm_judgeable_groundtruth_similarity | 166439 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two lists start = {{1},{1},{1},{2},{3},{1}} end = {{1},{2},{2},{3},{3},{1}} And I want to create a Sankey diagram. Which looks something like So, lines should join the start value to the corresponding end value. I tried using Graph[] but it didn't work very well - producing this oddly phallic shape. start = Flatten[start]end = Flatten[end] f[x_, y_] := Module[{}, Return[{x <-> y}]]result = Flatten[MapThread[f, {start, end}]]Graph[result]
Now provide the response and nothing else.
| Here's the start of a SankeyDiagram function: Options[SankeyDiagram] = Join[ {ColorFunction -> {"Start" -> ColorData[97], "End" -> ColorData["GrayTones"]}}, Options[Graphics]];SankeyDiagram[rules_, opts:OptionsPattern[]]:=Module[ { startcolors, svalues, slens, startsplit, endcolors, evalues, elens, endsplit, len, endpos, linecolors }, len = Length[rules]; endpos = Ordering @ Ordering @ Sort[rules][[All, 2]]; startcolors = OptionValue[ColorFunction->"Start"]; endcolors = OptionValue[ColorFunction->"End"]; {svalues, slens} = Through @ {Map[First], Map[Length]} @ Split[Sort @ rules[[All, 1]]]; startsplit = Accumulate @ Prepend[-slens, len-.5]; linecolors = Flatten @ Table[ ConstantArray[startcolors[i], slens[[i]]], {i, Length[slens]} ]; {evalues, elens} = Through @ {Map[First], Map[Length]} @ Split[Sort @ rules[[All, 2]]]; endsplit = Accumulate @ Prepend[-elens, len-.5]; Graphics[ { Table[ { startcolors[i], Rectangle[Offset[{-40, 0}, {0, startsplit[[i]]}], Offset[{-10, 0}, {0, startsplit[[i+1]]}]] }, {i, Length[startsplit]-1} ], Table[ { endcolors[(i-1)/(Length[endsplit]-1)], Rectangle[Offset[{40, 0}, {1, endsplit[[i]]}], Offset[{10, 0}, {1, endsplit[[i+1]]}]] }, {i, Length[endsplit]-1} ], Table[ { White, Text[ svalues[[i]], Offset[{-23, 0}, {0, (startsplit[[i]]+startsplit[[i+1]])/2}], {0, 0}, {0, 1} ] }, {i, Length[slens]} ], Table[ { LightGreen, Text[ evalues[[i]], Offset[{23, 0}, {1, (endsplit[[i]]+endsplit[[i+1]])/2}], {0, 0}, {0, -1} ] }, {i, Length[elens]} ], Thickness[.03], Opacity[.7], Table[ {linecolors[[i]], Line[connector[len-i, len-endpos[[i]]]]}, {i, len} ] }, opts, AspectRatio->1 ]]connector[y1_, y2_] := Table[ {t, y1+(y2-y1) LogisticSigmoid[Rescale[t, {0,1}, {-10,10}]]}, {t, Subdivide[0, 1, 30]}] Here is a fair approximation of your desired diagram: SankeyDiagram[{ 1->1,1->2,1->3,1->4,1->5, 2->1,2->2,2->3,2->4,2->5, 3->1,3->2,3->3,3->4,3->5}] | {} | {'log_upvote_score': 7, 'links': ['https://mathematica.stackexchange.com/questions/166439', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/36939/']} | jdg_80869 |
stackexchange | llm_judgeable_groundtruth_similarity | 1815 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
An oft repeated conspiracy theory asserts officials in the US military had prior knowledge of the Japanese attack on Pearl Harbor and allowed the attack to occur anyway. The conspiracy theorists point to early radar warnings being ignored, the absence of the carrier fleet on the day of the attack, et cetera. Also, some suggest FDR intentionally held out Pearl Harbor as bait, hoping an attack would shore up support for interventionism. To state the question clearly; Does credible historical analysis support the theory that the United States government intentionally allowed Japan to bomb Pearl Harbor and/or manipulated circumstances to goad or bait Japan into attacking Pearl Harbor in order to manipulate its population?
Now provide the response and nothing else.
| There were US officers that expected a Japanese air attack on Pearl Harbor, but they were generally low-ranking officers, and you can typically find low-ranking officers who will believe anything. (Gordon Prange, At Dawn We Slept ). The best account I've found of exactly what went on is Lee & Clausen's Pearl Harbor: the Final Judgment . There are so many conspiracy theories that it is hard to refute them all in one book, but reading a few good books on the subject will be useful. One thing that most conspiracy theorists ignore is that the US Army and US Navy sent messages to Pearl Harbor ordering preparation for imminent war ten days before the Japanese attack. It seems to me that, if you warn somebody of an impending attack, there's always the possibility they'll do something about it. Another fallacy thatis sometimes used is the confusion of US officials expecting imminent war (whichthey did) with US officials expecting an attack on Pearl Harbor (which they didn't). The second question is covered thoroughly in Feis' Road to Pearl Harbor (I haven't found a better source yet). In brief, Roosevelt was dragging his heels on sanctions and the like against Japan, in the hope that the US could stay at peace with Japan. (Roosevelt wanted to get into a war with Germany, and in September 1941 ordered the US Navy to fight the war in the Atlantic (Morison, The Battle of the Atlantic ). Roosevelt was advised that the materials sent to Japan would delay US rearmament, and allowed them to be shipped anyway. The tl;dr version of the above: No high US official expected an attack on Pearl Harbor. Roosevelt was taking measures to not provoke Japan, in the hopes that he could avoid that war. | {} | {'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/1815', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/1540/']} | jdg_80870 |
stackexchange | llm_judgeable_groundtruth_similarity | 33311 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm (very!) new to Mathematica , and trying to use it plot a set in $\mathbb{R}^3$. In particular, I want to plot the set $$ \big\{ (x,y,z) : (x,y,z) = \frac{1}{u^2+v^2+w^2}(vw,uw,uv) \text{ for some } (u,v,w) \in \mathbb{R}^3\setminus\{0\} \big\}. $$This is just the image of function from $\mathbb{R}^3\setminus\{0\} \to \mathbb{R}^3$. I haven't been able to make any of the plot functions display this. Any advice would be greatly appreciated. If it makes it easier, the set above is also$$ \big\{ (x,y,z) : (x,y,z) = \frac{1}{u^2+v^2+w^2}(vw,uw,uv) \text{ for some } (u,v,w) \in \mathbb{S}^2 \big\}. $$Alternatively, one could plot the three sets$$ \big\{ (x,y,z) : (x,y,z) = \frac{1}{1+v^2+w^2}(vw,w,v) \text{ for some } (v,w) \in \mathbb{R}^2 \big\}, $$$$ \big\{ (x,y,z) : (x,y,z) = \frac{1}{1 +u^2+w^2}(w,uw,u) \text{ for some } (u,w) \in \mathbb{R}^2 \big\}, $$$$ \big\{ (x,y,z) : (x,y,z) = \frac{1}{1+u^2+v^2}(v,u,uv) \text{ for some } (u,v) \in \mathbb{R}^2 \big\}. $$
Now provide the response and nothing else.
| In such cases, you can get better flexibility by switching to a DynamicModule and building up the GUI yourself. Then, you can pull the data generating step out of the plotting dynamic, so that the latter can be manipulated freely without regenerating the data. DynamicModule[{function = Sin, start, stop = 300, x = Range[-10 Pi, 10 Pi, Pi/100]}, Dynamic@With[{data = function[x], s = Spacer@10, f = Print@10}, Panel@Column[{ Row[{"function", s, Control[{function, {Sin, Cos, Tan}}]}], Row[{"start", s, Slider[Dynamic@start, {1, Length@data}]}], Row[{"stop", s, Slider[Dynamic@stop, {1, Length@data}]}], Dynamic@ListPlot[data, PlotRange -> {{start, stop}, Automatic}, ImageSize -> 400, Background -> White] }] ]] Note that the f = Print@10 is there just to observe evaluation of data . You can check for yourself that nothing is printed when you move the sliders and prints only when the tabs are changed. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/33311', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9797/']} | jdg_80871 |
stackexchange | llm_judgeable_groundtruth_similarity | 5022067 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to implement strlen() in the C preprocessor? Given: #define MYSTRING "bob" Is there some preprocessor macro, X , which would let me say: #define MYSTRING_LEN X(MYSTRING)
Now provide the response and nothing else.
| It doesn't use the preprocessor, but sizeof is resolved at compile time. If your string is in an array, you can use that to determine its length at compile time: static const char string[] = "bob";#define STRLEN(s) (sizeof(s)/sizeof(s[0])) Keep in mind the fact that STRLEN above will include the null terminator, unlike strlen() . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5022067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283981/']} | jdg_80872 |
stackexchange | llm_judgeable_groundtruth_similarity | 190950 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to solve this. I already got the answer but my doubt is if I am doing it right. There are two solutions for $x$ in the equation, to 2 decimal places. What is the value of the greater of the two solutions? $$a|x+b|+c = 0$$ $a = 10$, $b = 4$ and $c = -46$ my solution's as follows: Step 1, Substitute the values: $$10|x+4|-46 = 0$$ Step 2, solve: $$10|x+4| = 46$$ $$|x+4| = +4.6$$ or $$|x+4| = -4.6$$ Hence $x$ can be $x = 0.60$ or $x = -8.60$. is that the correct way of doing it?
Now provide the response and nothing else.
| Your solutions are correct, but I have a quibble. It is not true that $$|x + 4| = 4.6 \text{ or } -4.6$$ since the absolute value is always non-negative. Rather, you mean to say$$|x + 4| = 4.6$$which implies$$x+4 = 4.6 \text{ or } x+4 = -4.6$$(since applying the absolute value either did nothing or it removed the negative sign). Now you have two simpler equations to solve, which give $x = 0.6$ or $x = -8.6$ as solutions. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/190950', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39341/']} | jdg_80873 |
stackexchange | llm_judgeable_groundtruth_similarity | 22199741 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to print the data type of a user input and produce a table like following: ABCDEFGH = String1.09 = float0 = inttrue = bool etc. I'm using Python 3.2.3 and I know I could use type() to get the type of the data but in Python all user inputs are taken as strings and I don't know how to determine whether the input is a string or Boolean or integer or float. Here is that part of the code: user_var = input("Please enter something: ")print("you entered " + user_var)print(type(user_var)) which always returns str for string.
Now provide the response and nothing else.
| from ast import literal_evaldef get_type(input_data): try: return type(literal_eval(input_data)) except (ValueError, SyntaxError): # A string, so return str return strprint(get_type("1")) # <class 'int'>print(get_type("1.2354")) # <class 'float'>print(get_type("True")) # <class 'bool'>print(get_type("abcd")) # <class 'str'> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22199741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/963860/']} | jdg_80874 |
stackexchange | llm_judgeable_groundtruth_similarity | 3393687 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to specify a default sort order in my model. So that when I do a .where() without specifying an .order() it uses the default sort. But if I specify an .order() , it overrides the default.
Now provide the response and nothing else.
| default_scope This works for Rails 4+: class Book < ActiveRecord::Base default_scope { order(created_at: :desc) }end For Rails 2.3, 3, you need this instead: default_scope order('created_at DESC') For Rails 2.x: default_scope :order => 'created_at DESC' Where created_at is the field you want the default sorting to be done on. Note: ASC is the code to use for Ascending and DESC is for descending ( desc , NOT dsc !). scope Once you're used to that you can also use scope : class Book < ActiveRecord::Base scope :confirmed, :conditions => { :confirmed => true } scope :published, :conditions => { :published => true }end For Rails 2 you need named_scope . :published scope gives you Book.published instead of Book.find(:published => true) . Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed . With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries. You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this: scope :recent_books, lambda { |since_when| where("created_at >= ?", since_when) } # Note the `where` is making use of AREL syntax added in Rails 3. Finally you can disable default scope with: Book.with_exclusive_scope { find(:all) } or even better: Book.unscoped.all which will disable any filter (conditions) or sort (order by). Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+ So ... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are! They are like having def self.method_name ...code... end but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you! In fact they are Class level methods as they operate on the 1 set of 'all' records. Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') } . As a side note, when used incorrectly, default _scope can be misused/abused. This is mainly about when it gets used for actions like where 's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results. For where selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published where published is a named scope. In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/3393687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/609/']} | jdg_80875 |
stackexchange | llm_judgeable_groundtruth_similarity | 48365 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some custom theme settings like (package-initialize)(load-theme 'leuven t)(custom-theme-set-faces 'leuven '(Man-overstrike ((t (:foreground "red3" :bold t))) t) '(Man-underline ((t (:foreground "green3" :underline t)))) ;; ... ignored '(yas-field-highlight-face ((t (:background "#D4DCD8" :foreground "black" :box (:line-width -1 :color "#838383")))))) in my init.el of a emacs -q session. It works perfectly in emacs 26.1, but not in emacs 27, that's no matter how many times I evaluate the code, there's no custom face changes. I searched google but I can't find if there's some API changes in emacs 27. Work Eamcs Version: GNU Emacs 26.1.92 (build 2, x86_64-apple-darwin18.2.0, Carbon Version 158 AppKit 1671.2) of 2019-02-26 Unwork Emacs version: GNU Emacs 27.0.50 (build 1, x86_64-apple-darwin18.2.0, NS appkit-1671.20 Version 10.14.3 (Build 18D109)) of 2019-03-10 Any help will be appreciated.
Now provide the response and nothing else.
| Put this line in your init. Theme changes will take effect immediately in Emacs 27. (setq custom--inhibit-theme-enable nil) Presumably the automatic theme changing was disabled for a good reason. I haven't looked into the reason, but to set the value temporarily for just 1 statement you could do this. (let ((custom--inhibit-theme-enable nil)) (custom-theme-set-faces 'leuven ;; theme settings )) The double dashes -- in the name mean it is a "private" variable. So it is subject to change at any time and may not work forever. I haven't looked into it too deeply. And there are a few other ways to make the color take effect immediately. But setting this variable to nil is the most straight forward way to get the old behavior back. | {} | {'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/48365', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/8373/']} | jdg_80876 |
stackexchange | llm_judgeable_groundtruth_similarity | 16563115 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
On my Debian server I have a user called "deployer" that does not have sudo access, and has RVM installed. When installing Ruby using "deployer", like 1.9.3, it triggers a task to install dependencies "Installing requirements for debian, might require sudo password." which fails and stops installation because "deployer" can not sudo. I don't want to add "deployer" into the sudoers list, and don't want to install RVM for some other user just for a one-time use for installing dependencies. What is the correct way to install that dependencies? Or how do I list them to install manually?
Now provide the response and nothing else.
| This is indeed a new feature of RVM called autolibs , which automatically installs dependencies. If you have already installed RVM, and it is asking you for your sudo password, you can disable autolibs: $ rvm autolibs disable$ rvm requirements # manually install these$ rvm install ruby Otherwise, you can install RVM without autolibs with this command: $ \curl -L https://get.rvm.io | bash -s -- --autolibs=read-fail I understand the motivation, but find it rather annoying. I do not want to put my sudo password into RVM, nor for that matter Bundle! Please community, stop doing this. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16563115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/709986/']} | jdg_80877 |
stackexchange | llm_judgeable_groundtruth_similarity | 3525822 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Assuming that the distance between an intersection and the adjacent ones is equal for all intersections, how many possible ways are there to reach at the "goal" walking from the "start"? You are allowed to take a roundabout way only once (you can move down or left, including backtracking, only once), but you are not allowed to move once you get the goal. Every time I calculate, I get different answers.
Now provide the response and nothing else.
| Case 1: No backtrack. There are ten total steps, $5$ east, $5$ north. Total for this case: ${{10}\choose{5}}$ routes. Case 2: One West step: So there will be $5$ north steps, $6$ east steps, and $1$ west step. However we have to be sure not to go off the grid. So the west step can't be before the first or after the last east step. Choose $5$ slots for the north steps ${{12}\choose{5}}$ routes. Fill the first and last remaining slot with east steps. ( $1$ way). Choose one of the five remaining slots for the west step. ( $5$ ways). The remaining slots are east steps. (1 way). Total for case 2: ${{12}\choose{5}}\cdot 5$ Case 3: Similar to case 2 but with a south step (and a corresponding extra north step). Same total as case 2. Edit as suggested by Harry K. (Thanks!) The problem statement says that you can't move once the goal has been reached. Hence each of cases 2 and 3 should have their count reduced by $1$ (they can't end with east, west; or south, north respectively, as either of these would violate the rule of don't move after goal is reached). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3525822', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/669231/']} | jdg_80878 |
stackexchange | llm_judgeable_groundtruth_similarity | 976257 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find the number of triplets $(a,b,c)$ satisfying $(a^3+b)(b^3+a)=2^c$, where $a,b,c\in \mathbb{N}$ A trivial solution is $(1,1,2)$. I think there aren't any other such triplets, so I've been trying to prove that but haven't been able to do so. How can other solutions be found?
Now provide the response and nothing else.
| shaurya gupta already noted the solution $(a,b,c) = (1,1,2)$; rogerl found another pair, $(3,5,12)$ and $(5,3,12)$, and conjecturedthat there are no others. I prove that this conjecture is correct. [The question required that $a,b,c \in \mathbb N$; this notation"$\mathbb N$" is sometimes used for nonnegative integers,but I assume that zero is not allowed here, else$(a,b,c) = (0,2^r,4r)$ is a solution for every nonnegative integer.] rogerl shows that $a,b$ must be odd.Assume without loss of generality that $a \leq b$, and write$$a^3 + b = 2^d, \quadb^3 + a = 2^e $$for some integers $d,e$ with $d \leq e$ and $c = d+e$.Then $b = \lfloor 2^{e/3} \rfloor$, which makes it easy to check that the three known solutions are the only ones with $e \leq 15$ (for each $e$, solve for $b$, recover $a = 2^e - b^3$,and check whether $0 < a \leq b$). Thus any other solutionmust have $e>15$, and therefore $d>5$ (because $b^3+a < (a^3+b)^3$). Now $a,b$ satisfy $a^3 \equiv -b$ and $b^3 \equiv -a$ mod $2^d$.Therefore $a^9 \equiv a \bmod 2^d$. Since $a$ is odd it follows that $a^8 \equiv 1$,so $a \equiv \pm 1 \bmod 2^{d-3}$. Hence $a=1$, else $a \geq 2^{d-3}-1$and $a^3 > 2^d$. But then $b=2^d-1$, and (since $d>5$) we have reached acontradiction because $b^3+a$ is strictly between $2^{3d-1}$ and $2^{3d}$. QED P.S. For the record: @ $a,b$ are odd because if a power of $2$ is the sum of two positive integersthen their 2-valuations are equal, and this would not be possible with$a,b$ even. @ One proof of the implication$a^8 \equiv 1 \bmod 2^d \Longrightarrow a \equiv \pm1 \bmod 2^{d-3}$ is towrite $\pm a = 1 + 4n$ and expand $(a^8-1)/32$ as a polynomial in $n$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/976257', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/102986/']} | jdg_80879 |
stackexchange | llm_judgeable_groundtruth_similarity | 152758 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What would be the advantage of adopting ZF over other set theories such as New Foundation? I am very curious, since it seems that there is no reason just to stick with ZF. Edit: What about set theories other than NF? And why is NF's finite axiomatization possbility not attractive?
Now provide the response and nothing else.
| There are two very good reasons to stick with ZF: Historical reasons which really amount to " if it ain't broken, don't fix it. " sort of argument. We have a very adequate foundation with ZF[C] for most mathematics, and large cardinals axioms also "tame" the modern parts which require collections whose size is too big. I was told by a prominent set theorist once during a break between lectures that a "good axiomatic system" is one that you don't feel you are using. That is, the axioms describe perfectly how you perceive the objects you axiomatize. ZF has this property, and the only axiom in ZF which makes "no sense" at the beginning is the axiom of regularity, which if you think about it enough, you understand that it really is a reasonable axiom from a philosophical point of view. Other set theories, especially set theories from the first half of the previous century, often "lose" to ZF over one of the following reasons: Being weaker or equivalent to ZF (in consistency strength), which means that you either can find things provable from ZF; or that you could have used ZF from the start. Having too many types of objects, whereas ZF is simple: we only have sets. Unclear axioms, which require a lot of careful attention, which counter the second point: clarity of the axioms. Bad timing. Perhaps if NF was the first set theory we would have found it more natural. It came later, and it was strange... ill-founded; no choice; no power sets; universal set ... all those clash with how we perceive sets (the ZF way). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/152758', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32600/']} | jdg_80880 |
stackexchange | llm_judgeable_groundtruth_similarity | 53146810 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Writing dumb code, I've just found something weird. for(const [[[[[fancy, loop]]]]] in [0, 0]) { console.log(fancy, loop);} // Chrome 70.0.3538.77 says:// 0 undefined// 1 undefined It's like assigning 0 and 1 to [[[[[fancy, loop]]]]] , which, is array destructurings taking place and supposed to throw an error, isn't it? Or not. It's just my thought getting me confused right now. Could you please tell me how it is valid and works with no error? What am I missing?
Now provide the response and nothing else.
| It's not assigning 0 and 1 to [[[[[fancy, loop]]]]] . You're looping over the keys of [0, 0] , because you used in instead of of , and those keys are strings . The string "0" is an iterable whose sole element is "0" . Assigning "0" to [[[[[fancy, loop]]]]] repeatedly unpacks "0" and gets "0" , until eventually it gets down to [fancy, loop] = "0" at which point the final unpacking assigns "0" to fancy and undefined to loop . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53146810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4510033/']} | jdg_80881 |
stackexchange | llm_judgeable_groundtruth_similarity | 2077667 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So I was watching this video and at 1:35, I found out that: $$e^x > x^e,\quad{}x > 0$$ is a unique property of $e$. No other number does that. It seems legit, and probably is, anyway. But I find it a bit weird because $\pi$ seems to fit in place of $e$ just fine. In fact, many numbers do. For example, $3^4 > 4^3$. But at some point, there is an exception like if the inequality is flipped, $4^3 < 3^4$ . Another one would be $2^5 < 5^2$. But I can't seem to be able to find out why ${\pi}$ seems to fit in too. In fact, my understanding is that it indeed should. What makes $e$ special? It's pretty similar to $\pi$. Then why is $e$ supposed to be the only number with that property? Also, I stumbled upon this answer according to which $e$ has another unique property: $$e^x\ge x+1,\quad\text{for all }x$$ which again $\pi$ seems to fulfill too. So what exactly am I missing here?
Now provide the response and nothing else.
| [Corrected] Hint: can you show that the maximal value of $f(x) = \frac{\ln{x}}{x}$ on $(0, \infty)$ is attained for $x=e$? Because $a^x \geqslant x^a$ for all $x>0$ $\Longleftrightarrow$ $x\ln{a} \geqslant a\ln{x}$ for all $x > 0$ $\Longleftrightarrow$ $\frac{\ln{a}}{a} \geqslant \frac{\ln{x}}{x}$ for all $x > 0$. [There's a typo in the title and text: it should be $n^x \geqslant x^n$ not $n^x > x^n$.] | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2077667', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/238718/']} | jdg_80882 |
stackexchange | llm_judgeable_groundtruth_similarity | 27266907 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a strong reason why Microsoft chose not to support AppDomains in .NET Core? AppDomains are particularly useful when building long running server apps, where we may want to update the assemblies loaded by the server is a graceful manner, without shutting down the server. Without AppDomains, how are we going to replace our assemblies in a long running server process? AppDomains also provide us a way to isolate different parts of server code. Like, a custom websocket server can have socket code in primary appdomain, while our services run in secondary appdomain. Without AppDomains, the above scenario is not possible. I can see an argument that may talk about using VMs concept of Cloud for handling assembly changes and not having to incur the overhead of AppDomains. But is this what Microsoft thinks or says? or they have a specific reason and alternatives for the above scenarios?
Now provide the response and nothing else.
| The point of the .NETCore subset was to keep a .NET install small . And easy to port. Which is why you can, say, run a Silverlight app on both Windows and OSX and not wait very long when you visit the web page. Downloading and installing the complete runtime and framework takes a handful of seconds, give or take. Keeping it small inevitably requires features to be cut. Remoting was very high on that list, it is quite expensive. Otherwise well hidden, but you can for example see that delegates no longer have a functional BeginInvoke() method. Which put AppDomain on the cut list as well, you can't run code in an app domain without remoting support. So this is entirely by design. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27266907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4319075/']} | jdg_80883 |
stackexchange | llm_judgeable_groundtruth_similarity | 36839838 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Working on a Symfony2 project using phpStorm IDE, I have added couple of files to git ignore but one file despite being added to git ignore is always appearing....I have tried multiple times but its always there .gitignore file: /app/config/parameters.yml/bin//build//composer.phar/vendor//web/bundles//app/bootstrap.php.cache/app/cache/*!app/cache/.gitkeep/app/config/parameters.yml/app/logs/*!app/logs/.gitkeep/app/phpunit.xml#IDE metadata**.idea/**#Bash filesrun.sh And it is the .idea folder/files that git just will not ignore: On branch developChanges not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: .idea/workspace.xmlno changes added to commit (use "git add" and/or "git commit -a") Any idea why git will just not ignore the whole directory like i have specyfied in gitignore...?
Now provide the response and nothing else.
| Git never ignores changes to tracked files. As it appears as modified, the file is under version control (the idea/workspace.xml file usually should not be) and thus changes to it are tracked. Delete it from the index, leaving your local copy intact with git rm --cached .idea/workspace.xml and commit this change. From then on it will be ignored unless you force-add it back to the repository or change your gitignore settings. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36839838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5127919/']} | jdg_80884 |
stackexchange | llm_judgeable_groundtruth_similarity | 41545123 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Anyone who can tell me how to get pods under the service with client-go the client library of kubernetes? thanks
Now provide the response and nothing else.
| I have found the answer: services, err := clientset.Core().Services(name).List(api.ListOptions{})if err != nil { log.Errorf("Get service from kubernetes cluster error:%v", err) return}for _, service := range services.Items { if name == "default" && service.GetName() == "kubernetes" { continue } log.Infoln("namespace", name, "serviceName:", service.GetName(), "serviceKind:", service.Kind, "serviceLabels:", service.GetLabels(), service.Spec.Ports, "serviceSelector:", service.Spec.Selector) // labels.Parser set := labels.Set(service.Spec.Selector) if pods, err := clientset.Core().Pods(name).List(api.ListOptions{LabelSelector: set.AsSelector()}); err != nil { log.Errorf("List Pods of service[%s] error:%v", service.GetName(), err) } else { for _, v := range pods.Items { log.Infoln(v.GetName(), v.Spec.NodeName, v.Spec.Containers) } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41545123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1233410/']} | jdg_80885 |
stackexchange | llm_judgeable_groundtruth_similarity | 12417085 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I made a demo of a photo concept that toggles between two images to show a difference between between them. I've got an onMouseClick event that works fine, except on the iPad. The response is instant on my desktop, but is quite delayed on the tablet, maybe 500ms? Is this normal? Is there another way I can handle this? Javascript: var img1 = new Image();img1.src = "http://watkinsfilm.com/wp-content/uploads/2012/09/19mm.jpg";var img2 = new Image();img2.src = "http://watkinsfilm.com/wp-content/uploads/2012/09/200mm.jpg";function test() { if (document.pic.src == 'http://watkinsfilm.com/wp-content/uploads/2012/09/19mm.jpg') { document.pic.src = 'http://watkinsfilm.com/wp-content/uploads/2012/09/200mm.jpg'; } else if (document.pic.src == 'http://watkinsfilm.com/wp-content/uploads/2012/09/200mm.jpg') { document.pic.src = 'http://watkinsfilm.com/wp-content/uploads/2012/09/19mm.jpg'; }} Body: <div> <table id="table-1" > <tr><td> <img id="img" src="http://watkinsfilm.com/wp-content/uploads/2012/09/19mm.jpg" name="pic" onMouseDown="test()"/> <img id="png1" src="http://www.thedigitaltrekker.com/wp-content/uploads/2012/03/logo-6smA.png"/>Click on the image above to toggle between 19mm and 200mm <br> </td></tr> </table></div> Also on jsfiddle: http://jsfiddle.net/ntmw/R4pey/5/
Now provide the response and nothing else.
| iOS purposefully delays click events so that gestures/swiping work correctly. For example, when you touch an element you might mean to scroll the whole page, not fire the click event on an element. To achieve finer-grained control, use touch events. See: https://developer.mozilla.org/en-US/docs/DOM/Touch_events Example using touchstart : http://jsfiddle.net/R4pey/7/ . Note that capturing touch events has consequences, e.g. you may override a behavior that the user expects (like swiping). Also note that you should usually bind your events independently of your markup (not inline) to achieve a cleaner separation of markup and script. Here's an example using jQuery which binds the events separate from the markup, and handles both click and touchstart events. Tested in Chrome 21, FF 15, IE9, and on the iPad 3. var url1 = "http://watkinsfilm.com/wp-content/uploads/2012/09/19mm.jpg";var url2 = "http://watkinsfilm.com/wp-content/uploads/2012/09/200mm.jpg";// preload from original codevar img1 = new Image();img1.src = url1;var img2 = new Image();img2.src = url2;// bind the click and touchstart events$("#img").on("click touchstart", function(e){Β Β if (this.src == url1) {Β Β Β Β this.src = url2;Β Β }Β Β else if (this.src == url2) {Β Β Β Β this.src = url1;Β Β }Β // When touch event fires, this is needed to prevent the click // event from firing as well as @RyanWheale noted in the comments.Β Β e.preventDefault(); }); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12417085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1642708/']} | jdg_80886 |
stackexchange | llm_judgeable_groundtruth_similarity | 15959 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We know that everybody's DNA pattern is different in the world. Then how can Β΄we transfer blood from one person to another person and this person can survive ?
Now provide the response and nothing else.
| A few components to my answer. Red blood cells do not contain a nucleus, therefore, they do not harbour DNA. The major determinant of blood compatibility is the blood antigen. There are only 4 types: O, A, B, AB. This is genetically encoded, and is expressed as a set of sugar coats on the blood cell membrane. However, the enzymes that encode for A or B should be identical from person to person. I hope this gives you a preliminary answer to work off. | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/15959', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/6096/']} | jdg_80887 |
stackexchange | llm_judgeable_groundtruth_similarity | 1512990 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Is there a difference in C++ between copy initialization and assignment initialization? I am new to C++, I seldom see people using this syntax to declare and initialize a variable: int x(1); I tried, the compiler did not complain and the output is the same as int x=1, are they actually the same thing? Many thanks to you all.
Now provide the response and nothing else.
| Yes, for built in types int x = 1; and int x(1); are the same. When constructing objects of class type then the two different initialization syntaxes are subtly different. Obj x(y); This is direct initialization and instructs the compiler to search for an unambiguous constructor that takes y , or something that y can be implicitly converted to, and uses this constructor to initialize x. Obj x = y; This is copy initialization and instructs the compiler to create a temporary Obj by converting y and uses Obj 's copy constructor to initalize x . Copy initalization is equivalent to direct initialization when the type of y is the same as the type of x . For copy initalization , because the temporary used is the result of an implicit conversion, constructors marked explicit are not considered. The copy constructor for the constructed type must be accessible but the copy itself may be eliminated by the compiler as an optmization. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1512990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182349/']} | jdg_80888 |
stackexchange | llm_judgeable_groundtruth_similarity | 213119 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
(Running on an Ubuntu 10.04 64-bit server) Yesterday, I made the mistake of starting a process (which I didn't realize was going to take several days to run) over SSH without using screen. I've spent all day today trying to figure out some way that I can pry the process's output from SSH's iron grasp so that I can reboot my client machine, but am not getting anywhere. I tried using gdb and following the instructions at the bottom of this page , but when I run the first gdb command to create a file, I get an error message stating No symbol table is loaded. Use the "file" command. From what I gathered, this means I have to recompile the program whose output I'm trying to redirect, which of course is absolutely no help to me now that it's already running. I also thought I might be able to use retty to redirect output to another terminal, but evidently it does not compile on 64-bit platforms. How can I redirect this process's output to another terminal or to a file?
Now provide the response and nothing else.
| It looks like those instructions given for gdb are incorrect and incomplete in several ways. First, you need to use gdb [executablefile] [pid] so that GDB knows what the program it's connecting to actually is . I just tested this, and it can use a stripped executable. Note that while gdb is attached to the process the process will be suspended. If this process is communicating over a network, type quickly or the network connection will probably timeout. Second, the commands given don't explain what they're doing, and the instruction that you should cd "to a directory that you want your program to write files to" is wrong, since gdb is asking the original program to execute the creat() function. The example given will create myprog.stderr and myprog.stdout files in the Current Working Directory of the running program, not in the directory you ran gdb. Use absolute pathnames here if you don't know what that program's CWD is (or look at ls -l /proc/[pid]/cwd ). Third, running with the lack of explanation, it's important to know that the first parameter to dup2() is the file descriptor number returned by the previous creat() so if this running program had several files open you might end up with an exchange like (gdb) call creat("/home/me/myprog.stdout",0600)$1 = 7(gdb) call dup2(7,1)$2 = 1(gdb) call creat("/home/me/myprog.stderr",0600)$3 = 8(gdb) call dup2(8,2)$4 = 2 When you quit gdb, it'll ask you if you want to "quit anyway (and detach it)" the answer is yes. Finally, bg and disown are bash builtins. If you weren't using bash, then you're on your own from here. bg moves a suspended job to the background as if it were started there using somecommand & , and disown removes the program from bash's list of active programs to SIGHUP when bash exits. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/213119', 'https://serverfault.com', 'https://serverfault.com/users/63794/']} | jdg_80889 |
stackexchange | llm_judgeable_groundtruth_similarity | 7387217 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an easy solution to POST dynamically aggregated data into a new tab? chrome.tabs.create does not have a 'POST' option. Normally I would use chrome.browserAction.onClicked.addListener(function (t) { chrome.tabs.create( { "url" : "http://super.url", "method" : "POST" // oops.. no option. });});
Now provide the response and nothing else.
| You can simply combine these two techniques: You may execute JavaScript commands by adding javascript: prefix at your address bar or in href values of <a> tags. Only with JavaScript, you can create a form element and fill it with your data then POST it. function fakePost() { var form = document.createElement("form"); // Create a POST dump at ptsv2.com and change the code form.setAttribute("action", "http://ptsv2.com/t/dcgex-1614815819/post"); form.setAttribute("method", "post"); var params = { userId: 2, action: "delete" }; for(var key in params) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } // Appending the form might not be necessary document.body.appendChild(form); form.submit();};const source = fakePost.toString().replace(/(\n|\t)/gm,'').replace(/\s\s/gm,' '), url = `javascript:${source}; fakePost();`;chrome.browserAction.onClicked.addListener(() => chrome.tabs.create({ url })); Of course, that's just a dirty hack. If you need something more elaborate you can use a XHR Object or @Xan's answer. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7387217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591939/']} | jdg_80890 |
stackexchange | llm_judgeable_groundtruth_similarity | 11714069 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using datagridview bound to BindingSource control bound to a LINQΒ toΒ SQL class, I wonder how to position the bindingSource to a specific record, that is, when I type a Product name in a textbox, the bindingsource should move to that specific product. Here is my code: In my form FrmFind: NorthwindDataContext dc; private void FrmFind_Load(object sender, EventArgs e) { dc = new NorthwindDataContext(); var qry = (from p in dc.Products select p).ToList(); FindAbleBindingList<Product> list = new FindAbleBindingList<Product>(qry); productBindingSource.DataSource = list.OrderBy(o => o.ProductName); } private void textBox1_TextChanged(object sender, EventArgs e) { TextBox tb = sender as TextBox; int index = productBindingSource.Find("ProductName", tb.Text); if (index >= 0) { productBindingSource.Position = index; } } In the program class: public class FindAbleBindingList<T> : BindingList<T> { public FindAbleBindingList() : base() { } public FindAbleBindingList(List<T> list) : base(list) { } protected override int FindCore(PropertyDescriptor property, object key) { for (int i = 0; i < Count; i++) { T item = this[i]; //if (property.GetValue(item).Equals(key)) if (property.GetValue(item).ToString().StartsWith(key.ToString())) { return i; } } return -1; // Not found } } How can I implement the find method to make it work?
Now provide the response and nothing else.
| You can combine the BindingSource.Find() method with the Position property. For example, if you have something like this in your TextBox changed event handler: private void textBox1_TextChanged(object sender, EventArgs e){ TextBox tb = sender as TextBox; int index = bs.Find("Product", tb.Text); if (index >= 0) { bs.Position = index; }} This of course will depend on a lot of things like the particular implementation of the Find method the data source for the binding source has. In a question you asked a little while ago I gave you an implementation for Find which worked with full matches. Below is a slightly different implementation that will look at the start of the property being inspected: protected override int FindCore(PropertyDescriptor property, object key){ // Simple iteration: for (int i = 0; i < Count; i++) { T item = this[i]; if (property.GetValue(item).ToString().StartsWith(key.ToString())) { return i; } } return -1; // Not found} Do note that the above method is case sensitive - you can change StartsWith to be case insensitive if you need. One key thing to note about the way .Net works is that the actual type of an object is not sufficient all the time - the declared type is what consuming code knows about. This is the reason why you get a NotSupported exception when calling the Find method, even though your BindingList implementation has a Find method - the code that receives this binding list doesn't know about the Find. The reason for that is in these lines of code: dc = new NorthwindDataContext();var qry = (from p in dc.Products select p).ToList();FindAbleBindingList<Product> list = new FindAbleBindingList<Product>(qry);productBindingSource.DataSource = list.OrderBy(o => o.ProductName); When you set the data source for the binding source you include the extension method OrderBy - Checking this shows that it returns IOrderedEnumerable, an interface described here on MSDN. Note that this interface has no Find method, so even though the underlying FindableBindingList<T> supports Find the binding source doesn't know about it. There are several solutions (the best is in my opinion to extend your FindableBindingList to also support sorting and sort the list) but the quickest for your current code is to sort earlier like so: dc = new NorthwindDataContext();var qry = (from p in dc.Products select p).OrderBy(p => p.ProductName).ToList();FindAbleBindingList<Product> list = new FindAbleBindingList<Product>(qry);productBindingSource.DataSource = list; In WinForms there are no entirely out of the box solutions for the things you are trying to do - they all need a little bit of custom code that you need to put together to match just your own requirements. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11714069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1299388/']} | jdg_80891 |
stackexchange | llm_judgeable_groundtruth_similarity | 45562164 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I wrote a simple C++ function in order to check compiler optimization: bool f1(bool a, bool b) { return !a || (a && b);} After that I checked the equivalent in Rust: fn f1(a: bool, b: bool) -> bool { !a || (a && b)} I used godbolt to check the assembler output. The result of the C++ code (compiled by clang with -O3 flag) is following: f1(bool, bool): # @f1(bool, bool) xor dil, 1 or dil, sil mov eax, edi ret And the result of Rust equivalent is much longer: example::f1: push rbp mov rbp, rsp mov al, sil mov cl, dil mov dl, cl xor dl, -1 test dl, 1 mov byte ptr [rbp - 3], al mov byte ptr [rbp - 4], cl jne .LBB0_1 jmp .LBB0_3.LBB0_1: mov byte ptr [rbp - 2], 1 jmp .LBB0_4.LBB0_2: mov byte ptr [rbp - 2], 0 jmp .LBB0_4.LBB0_3: mov al, byte ptr [rbp - 4] test al, 1 jne .LBB0_7 jmp .LBB0_6.LBB0_4: mov al, byte ptr [rbp - 2] and al, 1 movzx eax, al pop rbp ret.LBB0_5: mov byte ptr [rbp - 1], 1 jmp .LBB0_8.LBB0_6: mov byte ptr [rbp - 1], 0 jmp .LBB0_8.LBB0_7: mov al, byte ptr [rbp - 3] test al, 1 jne .LBB0_5 jmp .LBB0_6.LBB0_8: test byte ptr [rbp - 1], 1 jne .LBB0_1 jmp .LBB0_2 I also tried with -O option but the output is empty (deleted unused function). I intentionally am NOT using any library in order to keep output clean. Please notice that both clang and rustc use LLVM as a backend. What explains this huge output difference? And if it is only disabled-optimize-switch problem, how can I see optimized output from rustc ?
Now provide the response and nothing else.
| Compiling with the compiler flag -O ( and with an added pub ), I get this output ( Link to Godbolt ): push rbpmov rbp, rspxor dil, 1or dil, silmov eax, edipop rbpret A few things: Why is it still longer than the C++ version? The Rust version is exactly three instructions longer: push rbpmov rbp, rsp[...]pop rbp These are instructions to manage the so called frame pointer or base pointer ( rbp ). This is mainly required to get nice stack traces. If you disable it for the C++ version via -fno-omit-frame-pointer , you get the same result . Note that this uses g++ instead of clang++ since I haven't found a comparable option for the clang compiler . Why doesn't Rust omit frame pointer? Actually, it does. But Godbolt adds an option to the compiler to preserve frame pointer. You can read more about why this is done here . If you compile your code locally with rustc -O --crate-type=lib foo.rs --emit asm -C "llvm-args=-x86-asm-syntax=intel" , you get this output: f1: xor dil, 1 or dil, sil mov eax, edi ret Which is exactly the output of your C++ version. You can "undo" what Godbolt does by passing -C debuginfo=0 to the compiler . Why -O instead of --release ? Godbolt uses rustc directly instead of cargo . The --release flag is a flag for cargo . To enable optimizations on rustc , you need to pass -O or -C opt-level=3 (or any other level between 0 and 3). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45562164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4131673/']} | jdg_80892 |
stackexchange | llm_judgeable_groundtruth_similarity | 51340603 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between the comparison operators == and === in Kotlin? class A { var foo = 1} var a1 = A()var a2 = A() println(a1 == a2) // output falseprintln(a1 === a2) // output false a1 = a2 println(a1 == a2) // output trueprintln(a1 === a2) // output true
Now provide the response and nothing else.
| In Kotlin, two types of equality are available. These are: Structural Equality & Referential Equality . class A { var foo = 1}var a1 = A()var a2 = A() Here a1 and a2 are two instances of class A . println(a1 == a2) It prints false because a1 and a2 are not structurally equal. println(a1 === a2) It prints false because a1 and a2 are not referencing the same object. But, if you execute this line: a1 = a2 then, a1 and a2 will be structurally equal and a1 is referencing to the a2 instance. That's why, println(a1 == a2)println(a1 === a2) both these lines returns true. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51340603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3157020/']} | jdg_80893 |
stackexchange | llm_judgeable_groundtruth_similarity | 21879824 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to access static resource in jsp that i am using in spring security...but it is not accessing those static resources need your ..valuable suggestions ..i am new in springs security .... my dispacher-servlet is... <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:property-placeholder location="classpath:resources/database.properties" /><context:component-scan base-package="com.nufame" /><tx:annotation-driven transaction-manager="hibernateTransactionManager" /><bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="WEB-INF/views/" /> <property name="suffix" value=".jsp" /></bean><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /></bean><bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop> </props> </property></bean> my security.xml is.. <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <!-- Non secure URLs --><security:http auto-config="true"> <security:intercept-url pattern="/index*" access="ROLE_USER" /> <security:form-login login-page="/login" default-target-url="/index" authentication-failure-url="/fail2login" /> <security:logout invalidate-session="true" logout-success-url="/logout" /> <security:access-denied-handler error-page="/403" /></security:http><security:http pattern="/css/**" security="none" /><security:authentication-manager> <security:authentication-provider> <!-- <security:user-service> <security:user name="dineshonjava" password="sweety" authorities="ROLE_USER" /> </security:user-service> --> <security:jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username, password, active from users where username=?" authorities-by-username-query="select us.username, ur.authority from users us, user_roles ur where us.user_id = ur.user_id and us.username =? " /> </security:authentication-provider></security:authentication-manager></beans> my web.xml is... <?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet><servlet-name>sdnext</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>sdnext</servlet-name><url-pattern>/</url-pattern></servlet-mapping><listener><listener-class> org.springframework.web.context.ContextLoaderListener </listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value> /WEB-INF/sdnext-*.xml, </param-value></context-param><welcome-file-list><welcome-file>index</welcome-file></welcome-file-list> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping><filter-name>springSecurityFilterChain</filter-name><url-pattern>/*</url-pattern> </filter-mapping><welcome-file-list> <welcome-file>login.jsp</welcome-file></welcome-file-list></web-app> please help i AM new in spring security .. thanks in advance....
Now provide the response and nothing else.
| You have 3 possibilities to solve this: Abstract factory : Instead of using a static method, use a concrete factory class: public abstract class AppleFactory { public Apple createInstance(final String str);}public class AppleFactoryImpl implements AppleFactory { public Apple createInstance(final String str) { // Implementation }} In your test class, mock the factory: @RunWith(MockitoJUnitRunner.class)public class MyClassTest { @Mock private AppleFactory appleFactoryMock; @Mock private Apple appleMock; @InjectMocks MyClass myClass; @Before public void setup() { when(appleFactoryMock.createInstance(Matchers.anyString()).thenReturn(appleMock); } @Test public void myMethod(){ ... ... ... }} PowerMock : Use PowerMock to create a mock of a static method. Look at my answer to a relevant question to see how it's done. Testable class : Make the Apple creation wrapped in a protected method and create a test class that overrides it: public class MyClass { private Apple apple; public void myMethod() { apple = createApple(); .... .... .... } protected Apple createApple() { return AppleFactory.createInstance(someStringVariable); }}@RunWith(MockitoJUnitRunner.class)public class MyClassTest { @Mock private Apple appleMock; @InjectMocks MyClass myClass; @Test public void myMethod(){ ... ... ... } private class TestableMyClass extends MyClass { @Override public void createApple() { return appleMock; } }} Of course, in your test class you should test TestableMyClass and not MyClass . I'll tell you my opinion on each of the methods: The abstract factory method is the best one - This is a clear design that hides the implementation details The testable class - Is the second option which requires minimum changes The PowerMock option is my least favorite - Instead of going for a better design, you ignore and hide your problem. But that's still a valid option. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21879824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3251824/']} | jdg_80894 |
stackexchange | llm_judgeable_groundtruth_similarity | 3010493 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So... I'm new to scheme r6rs, and am learning macros. Can somebody explain to me what is meant by 'hygiene'? Thanks in advance.
Now provide the response and nothing else.
| Hygiene is often used in the context of macros. A hygienic macro doesn't use variable names that can risk interfering with the code under expansion. Here is an example. Let's say we want to define the or special form with a macro. Intuitively, (or a b c ... d) would expand to something like (let ((tmp a)) (if tmp a (or b c ... d))) . (I am omitting the empty (or) case for simplicity.) Now, if the name tmp was actually added in the code like in the above sketched expansion, it would be not hygienic, and bad because it might interfere with another variable with the same name. Say, we wanted to evaluate (let ((tmp 1)) (or #f tmp)) Using our intuitive expansion, this would become (let ((tmp 1)) (let ((tmp #f)) (if tmp (or tmp))) The tmp from the macro shadows the outer-most tmp , and so the result is #f instead of 1 . Now, if the macro was hygienic (and in Scheme, it's automatically the case when using syntax-rules ), then instead of using the name tmp for the expansion, you would use a symbol that is guaranteed not to appear anywhere else in the code. You can use gensym in Common Lisp. Paul Graham's On Lisp has advanced material on macros. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3010493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2045611/']} | jdg_80895 |
stackexchange | llm_judgeable_groundtruth_similarity | 52894560 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this array: array:1 [βΌ 0 => array:3 [βΌ 0 => 10 2 => 5 3 => 6 ]] I want to convert it to this format of array [10,5,6]
Now provide the response and nothing else.
| Your problem is scoping. The this that you're trying to access inside the txt() function is pointing to its own this , and not the outer component this . There are several ways to fix this. here's a few: Use arrow functions You can transform txt into an arrow function to use the outer this : render() { const txt = (n) => { return this.state.bar[this.state.foo][n]; } return ( <View> ... </View> );} You can bind the function to use the outer this render() { function _txt(n){ return this.state.bar[this.state.foo][n]; } const txt = _txt.bind(this); return ( <View> ... </View> );} You can create an additional variable that points to the outer this render() { const self = this; function txt(n){ return self.state.bar[self.state.foo][n]; } return ( <View> ... </View> );} Other approaches You can move the txt function to outside of the render function and bind it to the component this . You can use an arrow function inside the component class block, which will seem like you've bound it to the component's this . You can pass the state as a parameter to the function ...and I'm sure that there are several other ways to fix this behaviour. You just need to know when you're using the component's this or some other this . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52894560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2158895/']} | jdg_80896 |
stackexchange | llm_judgeable_groundtruth_similarity | 3245644 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose $f\colon[0,\infty)\to(0,1)$ is a continuous function. Define the sequence $a_n$ : $$a_1 = 1, \quad a_{n+1}=\int_0^{a_n} f(x)\,\mathrm dx$$ Then find $$\lim_{n\to\infty} a_n.$$ I just know $a_n$ goes to zero when $n$ goes to $\infty$ intuitively. But how can I solve this more strict and in more detail?
Now provide the response and nothing else.
| Since $0<f(x)<1$ , note that $a_n$ is decreasing and bounded below by $0$ . So it's convergent. Say $\lim a_n=L$ . Taking the limit to your equality, you have $$L=\int _0^L f(x)\,\mathrm dx.$$ Now, $f(x)<1$ , convince yourself that if $L>0$ then $L=\int _0^L f(x)\,\mathrm dx<\int _0^L 1\,\mathrm dx=L$ . A contradiction. So $L=0$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3245644', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/672369/']} | jdg_80897 |
stackexchange | llm_judgeable_groundtruth_similarity | 353654 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Until now I have been using Ubuntu server. Ubuntu has separate downloads for desktop and server editions. I want to try a CentOS server, when I download a copy from a mirror through centos.org the ISO I get installs with a GUI. On every download mirror, there is no distinguishing label on the downloads. So is there only one version of CentOS or separate versions for Desktop and Server? I want a bare bones install with no GUI for a server, where can I download such a ISO?
Now provide the response and nothing else.
| No, there is no separate installations for desktop and server since you can select the packages you want during the install. By default the 'minimal' install doesn't have Gnome (Or pretty much anything for that matter) but even with the full DVD downloads you can deselect the packages (I believe it's called 'Graphical Desktop') ('GNOME Desktop Environment', you can install this from yum at a later time with yum groupinstall "GNOME Desktop Environment" ) Generally my preferred method of CentOS/RedHat install is to use the 'NetInstall' ISO and point it to one of the HTTP mirrors, then you only download the packages you need. You can always yum install some later | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/353654', 'https://serverfault.com', 'https://serverfault.com/users/108324/']} | jdg_80898 |
stackexchange | llm_judgeable_groundtruth_similarity | 628485 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following brace expansion (bash shell): echo -e {0..4..2}" "{0..2..2}"\n" I expected this to produce 0 00 22 02 24 04 2 but every line of the output except the first has a leading space and there is an extra blank line at the end that I didn't expect. Why is this. Is there a simple way to fix it? Obviously I can do something clunky like pipe to sed 's/^ //' , but is there a prettier way without piping to extra commands?
Now provide the response and nothing else.
| echo prints its arguments separated by spaces, even if they include (or generate) newline characters. Additionally it adds one newline character at the end of its output (unless it's echo -n ). Use printf : printf '%s\n' {0..4..2}" "{0..2..2} When echo does something unexpected, always consider printf . After you get familiar with printf it may even become your first choice. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/628485', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/120484/']} | jdg_80899 |
stackexchange | llm_judgeable_groundtruth_similarity | 22380131 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to F# and haven't seen anywhere how to do the following correctly let fun1 a b =match a b with| a + b > 0 -> fun2| a + b < 0 -> fun3 I have to do this with pattern matchingβfor homeworkβbut I don't know how to do it correctly. I thought I could be use tuples as follows: let fun1 (a,b) =match (a,b) with| (a,b) when a + b > 0 -> fun2| (a,b) when a + b < 0 -> fun3 But that doesn't work too. How do I proceed?
Now provide the response and nothing else.
| You have the right idea, you just forgot that indentation matters in F#. Adding spaces makes you solution work: let fun1 (a,b) = match (a,b) with | (a,b) when a + b > 0 -> fun2 | (a,b) when a + b < 0 -> fun3 This actually patterns matches twice, so we might want to rewrite it: let fun1 t = function | (a,b) when a + b > 0 -> fun2 | (a,b) when a + b < 0 -> fun3 The compiler/interpreter will let this go through, but with a warning: warning FS0025: Incomplete pattern matches on this expression. I'll leave getting rid of that as an exercise :-) PS. Good of you to be upfront about this being homework. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22380131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415546/']} | jdg_80900 |
stackexchange | llm_judgeable_groundtruth_similarity | 13534 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Albert Einstein quote Insanity: doing the same thing over and over again and expecting different results Often-times, Linux drives me mad because I'm doing the same thing over and over again and getting different results from box to box. (See my previous question ). For me, the biggest area of confusion is taking over a machine that someone else has installed (as is the case when signing up with a web hosting company). You just don't know what you're dealing with. Is there some kind of clever diff tool that I can run on an installation of Linux (Ubuntu) to give me a heads-up on how that machine has veered from the default installation? i.e. Something that can show me a list of the commands that are going to behave surprisingly thus avoiding a trial and error approach.
Now provide the response and nothing else.
| Whenever I have a good reference system and a misbehaving one, I try to compare them with vimdiff. What I compare varies with the problem, e.g. 1) When comparing servers at the package level, I create sorted lists of packages on each server, send the results to files and diff them, e.g. On server1: dpkg --get-selections|sort > server1_packages On server2: dpkg --get-selections|sort > server2_packages Copy both files to the same machine and diff (or vimdiff) them. 2) Make a list of running services as in example 1 sysv-rc-conf --list|sort > server1_servicessysv-rc-conf --list|sort > server2_services ...etc., and vimdiff those. 3) If you are troubleshooting inconsistent configurations with Apache for example, make copies of the config files, and vimdiff those, etc. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/13534', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/7638/']} | jdg_80901 |
stackexchange | llm_judgeable_groundtruth_similarity | 10436521 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create application that sends email I used classes like SKPSMTPMessage , NSStream+SKPSMTPExtensions, NSData+Base64Additions, HSK_CFUtilities, Base64Transcoder but it gives me the following errors Undefined symbols for architecture i386:"_OBJC_CLASS_$_SKPSMTPMessage", referenced from: objc-class-ref in MFViewController.o"_kSKPSMTPPartContentTransferEncodingKey", referenced from: -[MFViewController sendMail:] in MFViewController.o"_kSKPSMTPPartContentTypeKey", referenced from: -[MFViewController sendMail:] in MFViewController.o"_kSKPSMTPPartMessageKey", referenced from: -[MFViewController sendMail:] in MFViewController.o"_CFHostCreateWithName", referenced from: +[NSStream(SKPSMTPExtensions) getStreamsToHostNamed:port:inputStream:outputStream:] in NSStream+SKPSMTPExtensions.o +[NSStream(SKPSMTPExtensions) getStreamsToHostNamed:port:inputStream:outputStream:] in SKPSMTPMessage.o"_CFStreamCreatePairWithSocketToCFHost", referenced from: +[NSStream(SKPSMTPExtensions) getStreamsToHostNamed:port:inputStream:outputStream:] in NSStream+SKPSMTPExtensions.o +[NSStream(SKPSMTPExtensions) getStreamsToHostNamed:port:inputStream:outputStream:] in SKPSMTPMessage.o ld: symbol(s) not found for architecture i386clang: error: linker command failed with exit code 1 (use -v to see invocation) keep in mind that I'm using Xcode 4.3 , what shall I do to solve this?? After adding the CFNetwork framework and SystemConfiguration framework ,the number of errors decreased from 6 to 4 and it is now Undefined symbols for architecture i386:"_OBJC_CLASS_$_SKPSMTPMessage", referenced from: objc-class-ref in MFViewController.o"_kSKPSMTPPartContentTransferEncodingKey", referenced from: -[MFViewController sendMail:] in MFViewController.o"_kSKPSMTPPartContentTypeKey", referenced from: -[MFViewController sendMail:] in MFViewController.o"_kSKPSMTPPartMessageKey", referenced from: -[MFViewController sendMail:] in MFViewController.old: symbol(s) not found for architecture i386clang: error: linker command failed with exit code 1 (use -v to see invocation)
Now provide the response and nothing else.
| Answering my own question: Adding arbitrary entries to Class-Path is fine on its own. The problem arises when you enable JAR indexing using: <configuration> <archive> <index>true</index> </archive></configuration> Maven will omit your entries from META-INF/INDEX.LIST . When you use the JAR at runtime, Java will look at INDEX.LIST for finding classes, not MANIFEST.MF. Because your entries are missing from INDEX.LIST, they will not be found by the classloader, no matter what the manifest says. A simple workaround is to disable JAR indexing. I'm not sure how to inject an arbitrary Class-Path with indexing enabled. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10436521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1338832/']} | jdg_80902 |
stackexchange | llm_judgeable_groundtruth_similarity | 14527595 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given two sets of values, I have to find whether there is any common element among them or not i.e. whether their intersection is null or not. Which of the standard C# collection will suit best (in terms of performance) for this purpose? I know that linq has a Intersect extension method to find out the intersection of two list/arrays but my focus is on performance in terms of Big-O notation . And what if I have to find out the intersection of two sets as well?
Now provide the response and nothing else.
| Well, if you use LINQ's Intersect method it will build up a HashSet of the second sequence, and then check each element of the first sequence against it. So it's O(M+N)... and you can use foo.Intersect(bar).Any() to get an early-out. Of course, if you store one (either) set in a HashSet<T> to start with, you can just iterate over the other one checking for containment on each step. You'd still need to build the set to start with though. Fundamentally you've got an O(M+N) problem whatever you do - you're not going to get cheaper than that (there's always the possibility that you'll have to look at every element) and if your hash codes are reasonable, you should be able to achieve that complexity easily. Of course, some solutions may give better constant factors than others... but that's performance rather than complexity ;) EDIT: As noted in the comments, there's also ISet<T>.Overlaps - if you've already got either set with a static type of ISet<T> or a concrete implementation, calling Overlaps makes it clearer what you're doing. If both of your sets are statically typed as ISet<T> , use larger.Overlaps(smaller) (where larger and smaller are in terms of the size of the set) as I'd expect an implementation of Overlaps to iterate over the argument and check each element against contents of the set you call it on. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14527595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/370520/']} | jdg_80903 |
stackexchange | llm_judgeable_groundtruth_similarity | 3747739 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Will the right side of the expression get evaluated first or the left ? void main (){ int i = 0 , a[3] ; a[i] = i++; printf ("%d",a[i]) ;}
Now provide the response and nothing else.
| The order of evaluation of the operands of the assignment operator is unspecified: the operands may be evaluated in any order. However, this expression ( a[i] = i++ ) yields undefined behavior because you both modify i (using i++ ) and you separately read i (using a[i] ) without a sequence point in between those actions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3747739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_80904 |
stackexchange | llm_judgeable_groundtruth_similarity | 112144 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If voltage is equal across parallel resistors, then why can't one battery supply power to a infinite number of leds, if they are all in parallel?
Now provide the response and nothing else.
| Because a battery, like any real power source, has an output impedance. The more current you draw, the lower the voltage output. Granted, for a battery the output is not simply a fixed resistor, but the principle remains the same. As an example, let's pretend that a 12-volt battery has a 0.1 ohm output impedance. If you were to short the outputs of this notional battery, the current would be 12 v / 0.1 ohms, or 120 amps. By the same token, if a load were to draw 60 amps, the output of the battery would be 12 - (60 * 0.1), or 6 volts. Another way to put it is that the output impedance sets an upper limit on the amount of power a battery (or any power source) can provide. For DC, this upper limit is (V * V / R) /4.In the case of our notional battery, this upper limit is 360 watts. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/112144', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/43578/']} | jdg_80905 |
stackexchange | llm_judgeable_groundtruth_similarity | 213425 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible for the closure of a simply connected domain in the complex plane to not be simply connected? Intuitively it seems the closure is simply connected but I can't prove it. Is it enough to show that every point is homotopic to some point in the interior?
Now provide the response and nothing else.
| The set $X = \{re^{i\theta}\ | 1 < r < 2, -\pi < \theta < \pi\}$ (an open annulus without the negative real axis), is simply connected but $\overline{X} = \{re^{i\theta}\ | 1 \leq r \leq 2\}$ is not simply connected. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/213425', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/832/']} | jdg_80906 |
stackexchange | llm_judgeable_groundtruth_similarity | 9359 |
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've recently created a new repository in gitlab.com, started a new Ubuntu instance in digitalocean, installed docker and gitlab-runner in the ubuntu instance. Also, did gitlab-runner register and passed the correct host and token from gitlab.com ci/cd settings. Pushed a branch, and the expected pipeline job runs but fails, presenting the error: error during connect: Get http://docker:2375/v1.40/containers/json?all=1: dial tcp: lookup docker on 67.207.67.2:53: no such host Just followed the basic steps and expected it to work perfectly. By looking for the error when google search, there's no info. The config.toml file, which is created automatically on gitlab-runner register: concurrent = 1check_interval = 0[[runners]] name = "digital ocean runner" url = "https://gitlab.com/" token = "xxxxxxxxxxxxxxxxx" executor = "docker" [runners.docker] tls_verify = false image = "ruby:2.1" privileged = true disable_cache = false volumes = ["/cache"] shm_size = 0 [runners.cache] The gitlab ci file: image: docker:latestservices: - docker:dindstages: - testtest-build: stage: test script: - echo "Fine!" - docker info tags: - docker Steps to reproduce open a gitlab.com accountInstall Ubuntu latestInstall gitlab-runnerdo `register` and should have the config.toml above What causes this issue? The error log for one one of the tests, not for the job above: Running with gitlab-runner 12.3.0 (a8a019e0) on foobar laptop szWcjfZgUsing Docker executor with image foobar/docker-bash ...Starting service docker:dind ...Authenticating with credentials from /Users/foobar/.docker/config.jsonPulling docker image docker:dind ...Using docker image sha256:5768e15eefd175c1ba6969b616cfe827152556c5fe691b9258cb57d1a5c37e9d for docker:dind ...Waiting for services to be up and running...*** WARNING: Service runner-szWcjfZg-project-14670943-concurrent-0-docker-0 probably didn't start properly.Health check error:service "runner-szWcjfZg-project-14670943-concurrent-0-docker-0-wait-for-service" timeoutHealth check container logs:Service container logs:2019-10-05T23:18:52.128774700Z Generating RSA private key, 4196 bit long modulus (2 primes)2019-10-05T23:18:53.209639200Z .......................................................................................................................................................................................++++2019-10-05T23:18:53.694383300Z .......................................................................................++++2019-10-05T23:18:53.694784400Z e is 65537 (0x010001)2019-10-05T23:18:53.710661300Z Generating RSA private key, 4196 bit long modulus (2 primes)2019-10-05T23:18:53.789938500Z ............++++2019-10-05T23:18:54.926850200Z ..............................................................................................................................................................................................................++++2019-10-05T23:18:54.927064600Z e is 65537 (0x010001)2019-10-05T23:18:54.953296700Z Signature ok2019-10-05T23:18:54.953354500Z subject=CN = docker:dind server2019-10-05T23:18:54.953422500Z Getting CA Private Key2019-10-05T23:18:54.967240700Z /certs/server/cert.pem: OK2019-10-05T23:18:54.970126300Z Generating RSA private key, 4196 bit long modulus (2 primes)2019-10-05T23:18:55.244959900Z .................................................++++2019-10-05T23:18:55.317443900Z ...........++++2019-10-05T23:18:55.317858100Z e is 65537 (0x010001)2019-10-05T23:18:55.339564700Z Signature ok2019-10-05T23:18:55.339581700Z subject=CN = docker:dind client2019-10-05T23:18:55.339671300Z Getting CA Private Key2019-10-05T23:18:55.356469400Z /certs/client/cert.pem: OK2019-10-05T23:18:55.359632000Z mount: permission denied (are you root?)2019-10-05T23:18:55.359866500Z Could not mount /sys/kernel/security.2019-10-05T23:18:55.359910700Z AppArmor detection and --privileged mode might break.2019-10-05T23:18:55.361037300Z mount: permission denied (are you root?)*********Authenticating with credentials from /Users/foobar/.docker/config.jsonPulling docker image foobar/docker-bash ...Using docker image sha256:2ecf555077c9d0a7df0cc45188094a84fbbae4ce4c28cac37a652e9765bf3157 for foobar/docker-bash ...Authenticating with credentials from /Users/foobar/.docker/config.jsonRunning on runner-szWcjfZg-project-14670943-concurrent-0 via Foobar-MacBook-Pr.local...Authenticating with credentials from /Users/foobar/.docker/config.jsonFetching changes with git depth set to 50...Reinitialized existing Git repository in /builds/foobar/foobar-project/.git/Checking out 4f9789a7 as review-ci-test...Skipping Git submodules setupAuthenticating with credentials from /Users/foobar/.docker/config.jsonAuthenticating with credentials from /Users/foobar/.docker/config.jsonAuthenticating with credentials from /Users/foobar/.docker/config.json$ echo "INFO - Clear exited containers" # collapsed multi-line commandINFO - Clear exited containersINFO - List all services running...error during connect: Get http://docker:2375/v1.40/containers/json?all=1: dial tcp: lookup docker on 192.168.65.1:53: no such hostAuthenticating with credentials from /Users/foobar/.docker/config.jsonERROR: Job failed: exit code 1
Now provide the response and nothing else.
| I might have skipped the optional installation of docker in my Ubuntu instance, so if the gitlab runner is going to use Docker, remember to install it: curl -sSL https://get.docker.com/ | sh I got back to this issue and seem to have partially fixed it by checking it the gitlab runner is running gitlab-runner statussystemctl is-enabled gitlab-runnersystemctl is-enabled docker I do have a different issue to solve, but it doesn't seem to be related. That is: error during connect: Post http://docker:2375/v1.40/images/ [...] dial tcp: lookup docker on xx.xxx.xx.x:xx: no such host Then I found the solution, there's a problem in Gitlab CI that is reported here ( https://gitlab.com/gitlab-org/gitlab-runner/issues/4566#note_199261985 ); And there are a lot of ways to fix this but my solution follows: 1) Set the .gitlab-ci.yml services to use an older dind version: services: - docker:18.09.7-dind 2) Check the toml file /etc/gitlab-runner/config.toml , set the DOCKER_HOST just in case, to point to the right place, make sure it runs in privileged mode. My working version is: concurrent = 1check_interval = 0[session_server] session_timeout = 1800[[runners]] name = "xxxxxx xxxxxxxx" url = "https://gitlab.com/" token = "xxxxxxxxxx" executor = "docker" pre_build_script = "export DOCKER_HOST=tcp://docker:2375" [runners.custom_build_dir] [runners.docker] tls_cert_path = "" tls_verify = false image = "alpine:latest" privileged = true disable_entrypoint_overwrite = false oom_kill_disable = false disable_cache = false volumes = ["/cache"] shm_size = 0 [runners.cache] [runners.cache.s3] [runners.cache.gcs] Hope this helps someone else in the future! | {} | {'log_upvote_score': 4, 'links': ['https://devops.stackexchange.com/questions/9359', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/17458/']} | jdg_80907 |
stackexchange | llm_judgeable_groundtruth_similarity | 6834 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to melt diamonds into a liquid? I mean if you heat diamond at open air it will start to burn around 700 degrees Celsius, reacting with oxygen to produce carbon dioxide gas. In the absence of oxygen it will transform into graphite, a more stable form of carbon, long before turning into graphite. My question is, is it possible to melt diamonds into liquid? If so, then, how? If not, then why?
Now provide the response and nothing else.
| Liquid carbon does indeed exist, but perhaps surprisingly, relatively little is known about it. It only exists above around $4000\ \mathrm{K}$ and $100\ \mathrm{atm}$, which are not trivial conditions to sustain and probe. There certainly are many theoretical studies into the properties of liquid carbon, though. You can find a phase diagram for carbon here , though it is likely just a rough guide. The specific bonding properties of carbon atoms in the liquid phase still seems uncertain to some extent because carbon is very versatile and can create very dissimilar structures (easily seen comparing its two most common phases, graphite and diamond). This source suggests that bonding in the liquid varies continuously between linear acetylenic chains, graphite-like and diamond-like structures, depending on the exact conditions. Edit : Now I realize that obtaining liquid carbon and melting diamonds are two slightly different things. Liquid carbon is trivial to obtain compared to melting a diamond. As you mention, heating diamond at relatively low pressures will cause it to convert into graphite before it could melt. The only way to inhibit that would be to exploit the slight difference in density between graphite and diamond; as diamond is denser, the increased pressure will stabilize it slightly, decreasing the tendency for diamond to revert back to graphite. You'll need a lot of pressure though! Rigorously speaking, according to the phase diagram above, to obtain liquid carbon directly from melting a diamond would require a pressure of at least $10\ \mathrm{GPa}$, which is about $10^5\ \mathrm{atm}$. To put that into perspective, it's about $1/30$ of the pressure at the centre of the Earth. Amazingly, we actually can reach such absurd pressures in the lab by compressing two diamonds against each other . However, if the conditions required conditions for melting diamond (and sustaining it in molten form) are reached, it would probably compromise the integrity of the instrument and cause catastrophic (possibly explosive) failure, so I don't think anyone will be purposefully melting diamonds any time soon! Other techniques could be used ( laser inertial confinement , light-gas guns , etc), but I believe most would only transiently produce liquid diamond. | {} | {'log_upvote_score': 6, 'links': ['https://chemistry.stackexchange.com/questions/6834', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/2616/']} | jdg_80908 |
stackexchange | llm_judgeable_groundtruth_similarity | 1921421 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array: array( 4 => 'apple', 7 => 'orange', 13 => 'plum' ) I would like to get the first element of this array. Expected result: string apple One requirement: it cannot be done with passing by reference , so array_shift is not a good solution. How can I do this?
Now provide the response and nothing else.
| Original answer, but costly (O(n)): array_shift(array_values($array)); In O(1): array_pop(array_reverse($array)); Other use cases, etc... If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use: reset($array); This should be theoretically more efficient, if a array "copy" is needed: array_shift(array_slice($array, 0, 1)); With PHP 5.4+ (but might cause an index error if empty): array_values($array)[0]; | {} | {'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/1921421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223386/']} | jdg_80909 |
stackexchange | llm_judgeable_groundtruth_similarity | 10159236 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I found a similar question in the forum. But the answer in there does not answer my question. If I do feature detection (goodFeaturesToTrack) only once on the first image , and then use optical flow (calcOpticalFlowPyrLK) to track these features, the problem is: only the features detected on the first image can be tracked. When these features go beyond of the image, there would be no features to track. If I do feature detection for every new image , the feature tracking is not stable, because the feature detected last time may not be detected this time. I am using optical flow for 3D reconstruction. So I'm not interested in tracking what features, instead, I only care whether features in the field of view can be tracked stably. To summarize, my question is : how can I use optical flow to track old features, and in the meantime add new image features that come into the field of view and remove old features that go beyond the field of view?
Now provide the response and nothing else.
| Several approaches are possible. A good method goes like this: in Frame 1 detect N features, this is the Keyframe m=1 in Frame k track the features by optical flow in Frame k if the number of successfully tracked features drops under N/2: this frame is the keyframe m+1 compute the homography or the fundamental matrix describing the motion between the keyframes m and m+1 detect N features and discard the old ones k := k+1 go to 2 In this method basically you estimate the camera motion between the last two keyframes. Since you didn't mention what approach is used for 3D reconstruction I assumed either H or F are computed to estimated motion first. To estimate them accurately the baseline between the keyframes should be as wide as possible. In general, the best strategy is take into account the rough motion model of the camera. If the camera is held by hand a different strategy should be used compared to when the camera is fixed on the top of a car or a robot.I can provide a minimal working example in Python if that helps, let me know. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10159236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1334033/']} | jdg_80910 |
stackexchange | llm_judgeable_groundtruth_similarity | 282875 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having some capacitors blown up and I am not sure what's the cause of this. It is definitely NOT OVERVOLTAGE and NOT in WRONG POLARIZATION . Let me introduce the scenario: I have designed a double cascaded Boost converter using this scheme: Vout can be obtained from: \$\ Vout=Vin/(1-D_\max)^2\$ where \$D_ \max\$ is the maximum duty cycle. I want to step-up an input voltage of 12V into a 100V output voltage. My load is 100Ξ© , hence it would be dissipating 100W. If I consider no losses (I know I'm being TOO idealist, calm down), the input voltage source will deliver 8.33A We can split the circuit into two stages, the first stage's ouput is the second stage's input. Here comes my problem: C1 is blowing up when the voltage accross it reaches aproximately 30V. C1 is rated for 350V and it's a 22uF electrolytic capacitor (radial) 10x12.5mm. I am totally sure the polarization is right. The second stage's input current should (ideally) be around 3.33A (in order to keep the 100W with 30V for this stage). I know the current might be higher, but it's a good aproximation for this purpose. The switching frequency is 100Khz . For some reason the cap blows up and I don't really know why. Of course that when this happens the cap (dead) is hot. May it be an effect of the ESR? This cap has a 0.15 Dissipation Factor at 1kHz. \$|X_c|= 1/(2*pi*100Khz*22uF) =0.07234Ξ© \$ So \$ESR=0.15*0.07234= 0.01Ξ©\$ (DF would also increase for a higher frequency) for C1. Since L2 is pretty large, I would expect C1 to deliver a pretty constant current equal to the second stange's input current (3.33A) so the power dissipated in ESR is supposed to be around: \$3.33A^2 * 0.01Ξ© = 0.11W\$ Can this make it too hot and explode? I doubt it.... Additional information: L1 is about 1mHy L2 is about 2mHy D1 is a schottky 45V diode I tried two different capacitors: 160V 22uF that blown up, and then I tried the 350V 22uF which also blown up. Measuring the current in the cap would be difficult due to PCB layout Both the first and second MOSFET has a small snubber RC network. I don't think it could cause any problem in C1. I am waiting for your ideas! EDIT nΒ°1=L1 is pretty large, ripple is only 1% of the rated input current (let's say 100W/12V = 8.33A) so que can assume it's almost like a constant current at the input of stage 1. For stage 2 inductor current ripple is less than 5%, we can also think it's a constant current). When MOSFET 1 is turned ON, around 8.33A goes through it, but when it's turned off, that current (we said "practically constant") would go through D1. We can say current in the capacitor would be \$ I_{D1} - I_{L2} \$ . Then we finally find that the peak current in C1 must be in the order of \$ 8.33A - 3.33A = 5A\$. Pretty much current! and it would dissipate \$5A^2 *0.01Ξ© = 0.25W \$ ... but looks not so much power dissipated in the ESR. As someone said, I might also consider the internal inductance of the cap, but i think this wouldn't be a cause of power dissipation (we know inductors store energy but don't make it into heat) Anyways, despite of the calculation above was very simplified and it might be a little higher power dissipated, I still wonder if it's enough to make it boil and explode!
Now provide the response and nothing else.
| The peak ripple current for C1 is approximately I(out)/D where D= duty cycle. If the Duty cycle is say 50% at your 30 V output then the ripple for C1 is 3.3/0.5 = 6.6 A. As the duty cycle is reduced this gets worse. If the duty cycle was 10% = 0.1 then the current peak is 33 A. If you then use your ESR value the power dissipated is about 0.4 W, much higher than you previously calculated. If I look at 160 V capacitors on Mouser (I'm assuming you are using Al Electrolytics) then I see nothing generally available that could sustain the peak currents you need. I'd suggest you use TI's Webench to work through a design and then look at the selected components. You will notice on many of the designs they use very low ESR capacitors and often have two or even three in parallel. For example they use Panasonic polymer caps often in the designs and they have very high ripple current ratings at very high frequencies. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/282875', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/136811/']} | jdg_80911 |
stackexchange | llm_judgeable_groundtruth_similarity | 45505 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
What are the odds two uniformly chosen elements of S_n span the whole group (or just the alternating group)? Mathematica experements suggest those odds approach 1 - this might have been proven a long time ago. How likely is it to get the alternating group or something much smaller? Also, how can you efficiently find the size of the subgroup $\langle a,b\rangle$ in S_n ? My crude tests consists of randomly multiplying the two permutations and seeing how many different elements you get. Maybe there's a more efficient way to generate all the elements spanned by two permutation. You can generate the whole permutation group using a swap (12) and a shift (12...n). I wonder if all two element generating sets are conjugate to this.
Now provide the response and nothing else.
| The probability of generation of $A_n$ or $S_n$ by two random permutations is $1 - 1/n - O(1/n^2)$. The $1/n$ term comes from both permutations having the same fixed point. This is a classical result of L. Babai: The probability of generating the symmetric group, Journal of Combinatorial Theory, Series A, 1989. Warning: it uses the classification of finite simple groups. For asymptotics for general simple groups, see this paper by Liebeck and Shalev, and a recent short survey by Shalev. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/45505', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1358/']} | jdg_80912 |
stackexchange | llm_judgeable_groundtruth_similarity | 3076002 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $r_n$ be an enumeration of the rational numbers and let $a_n$ be a sequence of positive real numbers that converges to zero. Does there exist $x\in \mathbb{R}$ such that $|x-r_n|>a_n$ for all $n$ ? This problem was inspired by an easier version of the problem where we assume the stronger condition that $\displaystyle\sum_{n=1}^\infty a_n$ converges. I have a simple solution in this particular case but I will spoiler it in case anyone would like to try this too. Let $\Omega$ denote the set of $x\in \mathbb{R}$ that do not satisfy the given property; we claim that $\Omega \neq \mathbb{R}$ and so an $x\in \mathbb{R}$ with given property exists. Indeed, $\Omega=\{x\in\mathbb{R} \ | \ \exists \ n\in \mathbb{N} \ \mathrm{such \ that} \ |x-r_n| \leq a_n\}=\displaystyle\bigcup_{n=1}^\infty \ [r_n-a_n,r_n+a_n]$ whose Lebesgue measure $\lambda(\Omega)\leq \displaystyle\sum_{n=1}^\infty \lambda([r_n-a_n,r_n+a_n])=\displaystyle\sum_{n=1}^\infty 2a_n < \infty$ , so $\Omega \neq \mathbb{R}$ . Unfortunately it is very specific to this particular case so I doubt it helps with the general case, which I have no idea how to solve. I assume that, unless I'm missing something obvious, it uses some deeper theory (irrationality measure?) that I have not learned. Ideas for the general case or alternative (more elementary) solutions to the easier case would be appreciated.
Now provide the response and nothing else.
| No, this is not the case, and in fact is never the case: any enumeration of rationals whatsoever has an "unsatisfiable sequence" (that is, a sequence of reals tending to zero - indeed, strictly decreasing! - such that no real satisfies the corresponding requirement on distances from rationals) . (At the same time, given a sequence $(a_i)_{i\in\mathbb{N}}$ it's easy to construct an enumeration of the rationals with respect to which that sequence is satisfiable - just play "keep away from $\pi$ ," and make sure every rational gets tossed in eventually - so this is the strongest negative result we can hope for.) For simplicity, let's look at $[0,\infty)$ rather than $\mathbb{R}$ (this doesn't make a substantive difference). The key point is the following picture: we chop $[0,\infty)$ into blocks $B_i$ such that the size of block $B_i$ goes to zero as $i$ goes to $\infty$ . One way to do this is to define the $B_i$ s inductively by $B_0=[0,1)$ and $B_{i+1}=[\sum_{0<j\le i}{1\over j}, (\sum_{0<j\le i}{1\over j})+{1\over i+1})$ . Note that each $B_k$ has "diameter" ${1\over k+1}$ , and hence if $q\in B_k$ then the ball around $q$ with radius ${2\over k+1}$ covers $B_k$ . Now fix any enumeration of rationals $E=(r_i)_{i\in\mathbb{N}}$ , and pick a sequence $n_i$ ( $i\in\mathbb{N}$ ) of naturals such that: $n_i<n_{i+1}$ , and $r_{n_i}\in B_i$ . Such a sequence must exist since $B_i\cap\mathbb{Q}$ is always infinite. Finally, let $A=(a_i)_{i\in\mathbb{N}}$ be any strictly descending sequence of rationals such that $a_{n_i}={2\over i+1}$ for all $i$ . The set $$\{(r_{n_i}-a_i, r_{n_i}+a_i): i\in\mathbb{N}\}$$ covers $[0,\infty)$ since each $(r_{n_i}-a_i, r_{n_i}+a_i)$ covers the corresponding $B_i$ . So the sequence $A$ is unsatisfiable for the enumeration $E$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3076002', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/561496/']} | jdg_80913 |
stackexchange | llm_judgeable_groundtruth_similarity | 19327973 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Core Data is allowing me to save, but when I try to delete the object, I'm getting the following error: *** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0xa6b7e00 <x-coredata://8A687ECB-03F8-47C0-8470-087B9CF032B1-2801-00000A8C9A09CDB7/Notification/p2774005D-4B49-4378-A109-949F15D37032>' ' [self.managedObjectContext executeFetchRequest:allFetchRequest onSuccess:^(NSArray *results) { NSLog(@"Fetch for Objects with origial_id"); if (results.count>0) { NSLog(@"original_id = %@", dlPlanDate.original_id); NSLog(@"Results Recieved %i", results.count); for (PlanDate *pd in results) { PlanDateResolved *pdResolved = [NSEntityDescription insertNewObjectForEntityForName:@"PlanDateResolved" inManagedObjectContext:self.managedObjectContext]; NSArray *keys = [[[pd entity] attributesByName] allKeys]; NSDictionary *dict= [pd dictionaryWithValuesForKeys:keys]; [pdResolved setValuesForKeysWithDictionary:dict]; [pdResolved setValue:[pd plandate_id] forKey:[pdResolved primaryKeyField]]; pdResolved.senderUser = pd.senderUser; pdResolved.objectCreator = pd.objectCreator; pdResolved.users = pd.users; NSLog(@"pd.planDateID %@", pd.plandate_id); [self.managedObjectContext saveOnSuccess:^{ NSLog(@"Saving Each Object in the Array to PlanDateResolved with Original ID"); [self.managedObjectContext deleteObject:pd]; [self.managedObjectContext saveOnSuccess:^{ NSLog(@"Deleted the pd Object object!"); } onFailure:^(NSError *error) { NSLog(@"There was an error Deleting pd Object %@", error); }]; } onFailure:^(NSError *error) { }]; } } } onFailure:^(NSError *error) { NSLog(@"Error fetching: %@", error); }]; } Log: 2013-10-11 11:53:11.175 ST[2801:c07] Fetch for Objects with origial_id2013-10-11 11:53:11.175 ST[2801:c07] original_id = CFADD5A7-C9E8-48B3-91B2-56FDBC0F9BAB2013-10-11 11:53:11.175 ST[2801:c07] Results Recieved 32013-10-11 11:53:11.180 ST[2801:c07] pd.planDateID CFADD5A7-C9E8-48B3-91B2-56FDBC0F9BAB2013-10-11 11:53:11.182 ST[2801:c07] pd.planDateID 5917071A-8CFD-4C7C-A60F-A76FA48144292013-10-11 11:53:11.183 ST[2801:c07] pd.planDateID 1998BB90-D6FC-4226-977C-3414C4A570782013-10-11 11:53:11.913 ST[2801:c07] You updated the Accepted object!2013-10-11 11:53:11.913 ST[2801:c07] Saving Each Object in the Array to PlanDateResolved with Original ID2013-10-11 11:53:11.913 ST[2801:c07] Saving Each Object in the Array to PlanDateResolved with Original ID2013-10-11 11:53:12.155 ST[2801:c07] Saving Each Object in the Array to PlanDateResolved with Original ID2013-10-11 11:53:35.482 ST[2801:c07] *** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0xa6b7e00 <x-coredata://8A687ECB-03F8-47C0-8470-087B9CF032B1-2801-00000A8C9A09CDB7/Notification/p2774005D-4B49-4378-A109-949F15D37032>''*** First throw call stack:(0x24e7012 0x1cfae7e 0x1a20a48 0x1a515e8 0x1ac2879 0x1a59627 0x1a59271 0x1ace025 0x1a53cc1 0x1e7f014 0x1e6ed5f 0x1e6eaa3 0x1a53c8b 0x1a53aee 0x1a30eac 0x1ab0c1 0x1a5398f 0x1e7f014 0x1e6f7d5 0x248daf5 0x248cf44 0x248ce1b 0x24027e3 0x2402668 0x92effc 0x418d 0x25c5)libc++abi.dylib: terminate called throwing an exception
Now provide the response and nothing else.
| When a managed object is inaccessible it means that Core Data was not able to find that object in the persistent store file. There are a couple of reasons this can happen. I don't know where executeFetchRequest:onSuccess: and saveOnSuccess: come from, but assuming they do what their method names imply (and are not horribly buggy), there's no obvious reason in the code above why this would happen. So it's happening as a side-effect of work you're doing somewhere else. Most likely: You're also deleting these objects somewhere else, and this delete happens sometime after you perform the fetch but before the code crashes. As a result they're already gone when the code above tries to delete them. It appears that the mystery Core Data methods you're using run asynchronously (based on the fact that you get pd.planDateID printed multiple times before reaching the crash point), so this could be either on the same thread or on a different thread. [All of this assumes that your log statements actually came from the code you posted. That's somewhat in doubt, because the logs include a message reading "You updated the Accepted object!" , which does not appear in the code.] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19327973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1107173/']} | jdg_80914 |
stackexchange | llm_judgeable_groundtruth_similarity | 3006766 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was recently on an interview for a position where C/C++ is the primary language and during one question I was told that it's possible to use the vtable to determine which class in a hierarchy a base pointer actually stores. So if, for example you have class A { public: A() {} virtual ~A() {} virtual void method1() {} }; class B : public A { public: B() {} virtual ~B() {} virtual void method1() {} }; and you instantiate A * pFoo = new B() , is it indeed possible to use the vtable to determine whether pFoo contains a pointer to an instance of A or B?
Now provide the response and nothing else.
| This is obviously implementation dependent but, on most implementations, the in-memory representation of an object of class A or B will start with a pointer to the vtable. You can look at this vtable pointer, compare it to vtable pointers for objects that you know to be of class A or B , and determine the class of the object in that way. To illustrate (of course this is anything but good style): A *pFoo=new B(); // pointer to object of unknown class (either A or B)A a; // Object known to be of class AB b; // Object known to be of class Bvoid *vptrA=*((void **)&a); // Pointer to vtable of class Avoid *vptrB=*((void **)&b); // Pointer to vtable of class Bvoid *vptrFoo=*((void **)pFoo); // Pointer to vtable of unknown objectif(vptrFoo==vptrA) printf("Class A\n");else printf("Class B\n"); Important: This is only an illustration of how most implementations work; besides being implementation dependent, this technique breaks down in the presence of multiple inheritance. You should never do anything like this in production code; use RTTI instead. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3006766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363077/']} | jdg_80915 |
stackexchange | llm_judgeable_groundtruth_similarity | 13929972 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I find out the absolute position of an element on the current visible screen (viewport) using jQuery? I am having position:relative , so offset() will only give the offset within the parent. I have hierarchical divs, so $("#me").parent().offset() + $("#me").offset() doesn't help either. I need the position in the window, not the document, so when the document is scrolled, the value should change. I know I could add up all the parent offsets, but I want a cleaner solution. var top = $("#map").offset().top + $("#map").parent().offset().top + $("#map").parent().parent().offset().top + $("#map").parent().parent().parent().offset().top; Any ideas? Update: I need to get the exact gap in pixels between the top of my div and the top of the document, including padding/margins/offset? My code: HTML <div id="map_frame" class="frame" hidden="hidden"> <div id="map_wrapper"> <div id="map"></div> </div></div> CSS #map_frame{ border:1px solid #800008;}#map_wrapper { position:relative; left:2%; top:1%; width:95%; max-height:80%; display:block;}#map { position:relative; height:100%; width:100%; display:block; border:3px solid #fff;} jQuery to resize the map to fill the screen* var t = $("#map").offset().top + $("#map").parent().offset().top + $("#map").parent().parent().offset().top + $("#map").parent().parent().parent().offset().top;$("#map").height($(window).height() - t - ($(window).height() * 8 / 100)); Thanks...
Now provide the response and nothing else.
| See .offset() here in the jQuery doc . It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position. Here's an excerpt from the doc: The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful. To combine these: var offset = $("selector").offset();var posY = offset.top - $(window).scrollTop();var posX = offset.left - $(window).scrollLeft(); You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13929972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1729773/']} | jdg_80916 |
stackexchange | llm_judgeable_groundtruth_similarity | 26635684 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've googled calling __enter__ manually but with no luck. So let's imagine I have MySQL connector class that uses __enter__ and __exit__ functions (originally used with with statement) to connect/disconnect from a database. And let's have a class that uses 2 of these connections (for example for data sync). Note: this is not my real-life scenario, but it seems to be the simplest example . Easiest way to make it all work together is class like this: class DataSync(object): def __init__(self): self.master_connection = MySQLConnection(param_set_1) self.slave_connection = MySQLConnection(param_set_2) def __enter__(self): self.master_connection.__enter__() self.slave_connection.__enter__() return self def __exit__(self, exc_type, exc, traceback): self.master_connection.__exit__(exc_type, exc, traceback) self.slave_connection.__exit__(exc_type, exc, traceback) # Some real operation functions# Simple usage examplewith DataSync() as sync: records = sync.master_connection.fetch_records() sync.slave_connection.push_records(records) Q : Is it okay (is there anything wrong) to call __enter__ / __exit__ manually like this? Pylint 1.1.0 didn't issue any warnings on this, nor have I found any article about it (google link in the beggining). And what about calling: try: # Db queryexcept MySQL.ServerDisconnectedException: self.master_connection.__exit__(None, None, None) self.master_connection.__enter__() # Retry Is this a good/bad practice? Why?
Now provide the response and nothing else.
| Note: This answer doesn't properly account for possible failures when there are multiple calls to underlying __enter__ and __exit__ methods. See Eric's answer for one that does deal with that. No, there's nothing wrong with that. There are even places in the standard library that do it. Like the multiprocessing module : class SemLock(object): def __init__(self, kind, value, maxvalue, *, ctx): ... try: sl = self._semlock = _multiprocessing.SemLock( kind, value, maxvalue, self._make_name(), unlink_now) except FileExistsError: pass ... def __enter__(self): return self._semlock.__enter__() def __exit__(self, *args): return self._semlock.__exit__(*args) Or the tempfile module : class _TemporaryFileWrapper: def __init__(self, file, name, delete=True): self.file = file self.name = name self.delete = delete self._closer = _TemporaryFileCloser(file, name, delete) ... # The underlying __enter__ method returns the wrong object # (self.file) so override it to return the wrapper def __enter__(self): self.file.__enter__() return self # Need to trap __exit__ as well to ensure the file gets # deleted when used in a with statement def __exit__(self, exc, value, tb): result = self.file.__exit__(exc, value, tb) self.close() return result The standard library examples aren't calling __enter__ / __exit__ for two objects, but if you've got an object that's responsible for creating/destroying the context for multiple objects instead of just one, calling __enter__ / __exit__ for all of them is fine. The only potential gotcha is properly handling the return values of the __enter__ __exit__ calls for the objects you're managing. With __enter__ , you need to make sure you're returning whatever state is required for the user of your wrapper object to get back from the with ... as <state>: call. With __exit__ , you need to decide if you want to propagate any exception that occurred inside the context (by returning False ), or suppress it (by returning True ). Your managed objects could try to do it either way, you need to decide what makes sense for the wrapper object. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26635684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1149736/']} | jdg_80917 |
stackexchange | llm_judgeable_groundtruth_similarity | 5244472 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to add an image in email body.I don't want to attach an image to the email, but add an image in the email body. How to do this? I'm using this. "<img src=\"data:image/png;base64,"+convertFileTOByteEncrypt()+"\">" or "<img src=\"http://images.anandtech.com/doci/3982/HTCSurround-0134.jpg\">" Then image is displayed like this.
Now provide the response and nothing else.
| Unfortunately, it's not possible to do this with Intents. The reason why for example bold text is displayed in the EditText and not an Image is that StyleSplan is implementing Parcelable whereas ImageSpan does not. So when the Intent.EXTRA_TEXT is retrieved in the new Activity the ImageSpan will fail to unparcel and therefor not be part of the style appended to the EditText. Using other methods where you don't pass the data with the Intent is unfortunately not possible here as you're not in control of the receiving Activity. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5244472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/624069/']} | jdg_80918 |
stackexchange | llm_judgeable_groundtruth_similarity | 505054 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Since there is no Linq to DB2 yet (c'mon IBM!), and I want to deal with IQueryables or IEnumerables in my code, how would I convert a DataTable to an IQueryable? Or an IEnumerable? I have an interface and a class that matches the columns in the datatable... IQueryable<IMyData> GetAS400Data(..parameters..){ DataSet d = GetData(); ... //Some code to convert d to IQueryable<IMyData>} DataTable.Rows does not support .AsQueryable, since MSFT yanked it, so I'm not sure what to do here.
Now provide the response and nothing else.
| table.AsEnumerable()...table.AsEnumerable().AsQueryable()... However, you'd need to write your own translation ( Select ) to your type; and the IQueryable<T> would still be using LINQ-to-Objects; the only purpose (in this scenario) of using IQueryable<T> over IEnumerable<T> would be to use expressions for some other reason - perhaps for the dynamic LINQ library . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/505054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16426/']} | jdg_80919 |
stackexchange | llm_judgeable_groundtruth_similarity | 363856 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been able to prove this relation by using a certain method, but it uses the fact that $$\hat p=-i\hbar\frac\partial{\partial x},\tag{1}$$ which is a relation I have avoided so far, so I wish to prove it without using that ($\hat p$ has simply been defined as the generator of spatial translation). Is it possible to prove that $$[\hat p,F(\hat x)]=-i\hbar\frac{\partial F(\hat x)}{\partial x}.\tag{2}$$ without using this relation? I can't see how to get even the first step.
Now provide the response and nothing else.
| Write $F(\hat{x})$ as a power series with arbitrary coefficients. Use linearity to express $[\hat{p}, F(\hat{x})]$ as a linear combination of commutators of the form $[\hat{p}, \hat{x}^n]$. You can calculate the latter commutator using induction and the identities $[A, BC] = B [A, C] + [A, B]C$ and $[\hat{x}, \hat{p}] = i \hbar$. Then recombine the power series into a single expression. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/363856', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/154004/']} | jdg_80920 |
stackexchange | llm_judgeable_groundtruth_similarity | 2291653 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like a closed-form expression of the following series: $\left(\frac{x}{1!}+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\cdots\right)+\left(\frac{x}{3!}+\frac{x^2}{4!}+\frac{x^3}{5!}+\frac{x^4}{6!}+\cdots\right)+\left(\frac{x}{5!}+\frac{x^2}{6!}+\frac{x^3}{7!}+\frac{x^4}{8!}+\cdots\right)+\cdots$ Clearly the first bracket is $e^x-1$, the second bracket is $x^{-2}(e^x-1-x-\frac{x^2}{2!})$, the third bracket is $x^{-4}(e^x-1-x-\frac{x^2}{2!}-\frac{x^3}{3!}-\frac{x^4}{4!})$, and so on. Is there a way to combine these infinitely many terms into a closed form expression?
Now provide the response and nothing else.
| For any formal Laurent series in $t$, $f(t) = \sum\limits_{\ell=-\infty}^\infty \alpha_\ell t^\ell$, we will use the notation $[t^\ell] f(t)$ to denote the coefficient $\alpha_\ell$ in front of the monomial $t^\ell$. When $f(t)$ defines afunction holomorphic over an annular region $\mathcal{A} \subset \mathbb{C}$, $[t^\ell] f(t)$ can be reinterpreted as a contour integral over some suitably chosen circle $C_R = \{ t : |t| = R \}$ lying within $\mathcal{A}$.$$[t^\ell]f(t) \quad\longleftrightarrow\quad\frac{1}{2\pi i}\oint_{C_R} \frac{f(t)}{t^{\ell+1}} dt$$ The series at hand can be rewritten as $$\begin{align}\mathcal{S} \stackrel{def}{=}\sum_{\ell=0}^\infty \sum_{k=1}^\infty \frac{x^k}{(k+2\ell)!}&= \sum_{\ell=0}^\infty \sum_{k=1}^\infty \sum_{m=0}^\infty \delta_{m,k+2\ell} \frac{x^k}{m!}= \sum_{\ell=0}^\infty \sum_{k=1}^\infty \sum_{m=0}^\infty \delta_{m-k,2\ell} \frac{x^k}{m!}\\&= \sum_{\ell=0}^\infty \left\{ \sum_{k=1}^\infty \sum_{m=0}^\infty [t^{2\ell}]\left(\frac{x}{t}\right)^k \frac{t^m}{m!}\right\}\tag{*1}\end{align}$$Over the complex plane, the sum$\displaystyle\;\sum\limits_{k=1}^\infty \sum\limits_{m=0}^\infty \left(\frac{x}{t}\right)^k \frac{t^m}{m!}\;$converges absolutely for $|t| > |x|$. If we interpret the expression inside curly braces of $(*1)$ as contour integrals over circle $C_R$ with $R > |x|$, we can switch the order of summation and $[\ldots]$.We find $$\mathcal{S} = \sum_{\ell=0}^\infty [t^{2\ell}]\sum\limits_{k=1}^\infty \sum\limits_{m=0}^\infty \left(\frac{x}{t}\right)^k \frac{t^m}{m!}= \sum_{\ell=0}^\infty [t^{2\ell}] \frac{xe^t}{t-x}= \sum_{\ell=0}^\infty [t^0] t^{-2\ell} \frac{xe^t}{t-x}$$ Over the complex plane, the term $\sum\limits_{\ell=0}^\infty t^{-2\ell}$ converges absolutely when $|t| > 1$. If we choose $R > \max\{ |x|, 1 \}$,we can change the order of summation and $[\cdots]$ again and get $$\mathcal{S}= [t^0]\left[\left(\sum_{\ell=0}^\infty t^{-2\ell}\right)\frac{xe^t}{t-x}\right]= [t^0] \left(\frac{t^2}{t^2-1}\frac{xe^t}{t-x}\right)= \frac{1}{2\pi i}\oint_{C_R} \frac{tx e^t}{(t^2-1)(t-x)} dt$$Since $R > \max\{ |x|, 1 \}$, there are 3 poles $x, \pm 1$ inside $C_R$. If onesums over the contributions from these poles, one obtains $$\begin{align}\mathcal{S} &= \frac{x^2 e^x}{(x^2-1)} + \frac{xe}{2(1-x)} + \frac{-xe^{-1}}{(-2)(-1-x)}\\&= \frac{x}{2(x^2-1)}\left[ 2xe^x - e (x+1) - e^{-1}(x-1)\right]\\&= \frac{x}{2(x^2-1)}\left[ x(2e^x - (e+e^{-1})) - (e-e^{-1})\right]\end{align}$$Reproducing what Did mentioned in hir comment. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2291653', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90839/']} | jdg_80921 |
stackexchange | llm_judgeable_groundtruth_similarity | 197124 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am running an Ubuntu 12.04 desktop system. So far I have only installed some programs (I have sudo rights). When I check the list of users on the system, I see a long list, like more than 20 usersβwhen were these users created (e.g. daemon, sys, sync, games, pulse, etc.)? How are these related to new programs being installed? If I run a program on my system, it should run with my UID. But on doing a ps , I see many other programs running with different UID (like root, daemon, avahi, syslog, colord etc.) β how were these programs started with different UIDs?
Now provide the response and nothing else.
| User accounts are used not only for actual, human users, but also to run system services and sometimes as owners of system files. This is done because the separation between human users' resources (processes, files, etc.) and the separation between system services' resources requires the same mechanisms under the hood. The programs that you run normally run with your user ID. It's only system daemons that run under their own account. Either the configuration file that indicates when to run the daemon also indicates what user should run it, or the daemon switches to an unprivileged account after starting. Some daemons require full administrative privileges, so they run under the root account. Many daemons only need access to a specific hardware device or to specific files, so they run under a dedicated user account. This is done for security: that way, even if there's a bug or misconfiguration in one of these services, it can't lead to a full system attack, because the attacker will be limited to what this service can do and won't be able to overwrite files, spy on processes, etc. Under Ubuntu, user IDs in the range 0β99 are created at system installation. 0 is root; many of the ones in the range 1β99 exist only for historical reasons and are only kept for backward compatibility with some local installations that use them (a few extra entries don't hurt). User IDs in the range 100β999 are created and removed dynamically when services that need a dedicated user ID are installed or removed. The range from 1000 onwards is for human users or any other account created by the system administrator. The same goes for groups. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/197124', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/63934/']} | jdg_80922 |
stackexchange | llm_judgeable_groundtruth_similarity | 532248 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
EDIT: I just want to note that both David and Richard's answers (and comments) I think are needed to paint the full picture in response. To me I still haven't felt a real need to try out time-series frameworks from the given replies if all I can about is strong predictions and have a good sense of how to set up the regression formula, but I do take the points taken on interpretation of the coefficients and overall efficiency (and that, perhaps, I'm doing it the "hard" way). I'm a bit naive to time-series related models like ARIMA as I can't seem to find a justification for them compared to a well-setup regression model for forecasting. Numerous responses online point to the vulnerability of linear regression due to thinks like autocorrelated errors, seasonality, and extrapolation, but it seems to me I can accommodate much of this with good data prep: Seasonality - Model it. If there are periodic dips, I've had good luck catching them with various flag columns (month, quarter, even years, etc). Autocorrelation - Include lagged values. Taking deltas, rolling means, and various statistics against prior values seems to help nicely. Extrapolation - I don't see how time-series approaches navigate this any better since rare to no series is truly stationary into the future. I've found that keeping a running count from an initial reference point (i.e. months since start) seems to help general directional trends, and at some point you need to retrain anyways. Adding on to that, regression models allow for a standard means of including multiple other input features (for instance market data if predicting sales) that do help that extrapolation quandary, as well as the benefits of a typical "optimize it to heck" framework of machine learning... I've never found the justification for a true time-series route. Can someone help explain what I'm missing in practical use case terms? Or is it perhaps just that regression models do require that careful data modelling before use?
Now provide the response and nothing else.
| It is somewhat of a false dichotomy that one has choose between using a time series framework OR a regression framework. The main reason for wanting to use a time-series framework would be autocorrelated errors. With this in mind, one can incorporate autocorrelated errors into regression by using Regression with ARMA errors ( The ARIMAX model muddle - Hyndman ) and in a sense get the 'best of both worlds'. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/532248', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/260763/']} | jdg_80923 |
stackexchange | llm_judgeable_groundtruth_similarity | 750868 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
After reading the docs I found myself somewhat confused as to how best to manage productive application/service data. There seem to be 3 options: Simply map volume to host directory (i.e. -v argument for docker run ) Create a docker container image for data (i.e. separate container and --volumes-from ) Creating a docker volume (i.e. docker volume create ) Now, it seems that the accepted practice is option #2, but then I wonder what is the purpose of #3. Especially how do you correctly handle these scenarios with docker volume and is it better to use a data volume container or this for each situation? You need application data in a separate volume and/or storage tier in your server Backing up Restoring data
Now provide the response and nothing else.
| I think #2 and #3 are pretty much the same thing, the main difference is that there is no stopped container with #3 (it is literally, just a named volume). For example, you can create a named volume and do similarly what you would do with #2 with -v instead. Create a named volume: $ docker volume create --name test Mount and write some data to that volume from a container: $ docker run -v test:/opt/test alpine touch /opt/test/hello You can then mount that same test volume in another container and read the data: $ docker run -v test:/opt/test alpine ls -al /opt/test total 8drwxr-xr-x 2 root root 4096 Jan 23 22:28 .drwxr-xr-x 3 root root 4096 Jan 23 22:29 ..-rw-r--r-- 1 root root 0 Jan 23 22:28 hello The advantage here is that the volume won't accidentally disappear if you remove the data-only container. You now manage it with the docker volume sub-command. $ d volume lsDRIVER VOLUME NAMElocal test It also opens the possibilities for volume drivers down the road so you might be able to do shared volumes between hosts (ie. named volumes over NFS). Examples of this might be Flocker and Convoy . To your point specifically about moving or backing up data, Convoy has specific sub-commands for backing up data and allows for storage on NFS or EBS external to your host. For this reason, I think the more new-school way (Docker 1.9+) is to use a named volume rather than a data-only container. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/750868', 'https://serverfault.com', 'https://serverfault.com/users/66835/']} | jdg_80924 |
stackexchange | llm_judgeable_groundtruth_similarity | 10400751 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I parse data from /proc/[pid]/statm to get a clue about memory usage of a certain process. man proc states that resident set size (measured in 'pages') is the same as VmRSS (KB??) in /proc/[pid]/status . Since they have different values, I would like to understand the connection between these Values. Is there something like a factor I can read somewhere in /proc (I thought of VmPTE but its sth. else...)? Which one of both should I parse to get the size of the used Memory for a certain process? #ex 1782 = firefox~$ cat /proc/1782/statm 224621 46703 9317 11 0 98637 0# \--- resident set size~$ cat /proc/1782/status | grep Vm VmPeak: 935584 kB VmSize: 898484 kB VmLck: 0 kB VmHWM: 257608 kB VmRSS: 186812 kB VmData: 394328 kB VmStk: 220 kB VmExe: 44 kB VmLib: 61544 kB VmPTE: 1224 kB VmSwap: 0 kB
Now provide the response and nothing else.
| My understanding is that VM is the amount of virtual memory and RSS is how much of it is resident in memory. So, virtual memory = part in physical memory + part on disk The part in physical memory is RSS. So, VSS should be greater than RSS. If they are close to equal, that means your process is sitting comfortably in memory. If VSS is much larger, that means there isn't enough memory and parts of it have to be swapped out to disk (i.e., because of a competing process, etc.). On my system, I can do a "man proc" and it lists the following: * VmPeak: Peak virtual memory size. * VmSize: Virtual memory size. * VmLck: Locked memory size (see mlock(3)). * VmHWM: Peak resident set size ("high water mark"). * VmRSS: Resident set size. * VmData, VmStk, VmExe: Size of data, stack, and text segments. If you want to report the peak memory usage, then you probably want virtual memory, which looks like VmPeak. Hope this helps! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10400751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1167428/']} | jdg_80925 |
stackexchange | llm_judgeable_groundtruth_similarity | 47841783 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm porting code to C++17, trying to use the new features while possible. One thing I like is the idea to use std::optional to return or not a value in a function that may fail in some conditions. I was curious about the possible usages of this new feature, and I'm thinking in start to use it to replace optional arguments in functions, so: void compute_something(int a, int b, const Object& c = Object(whatever))Β { // ...} Becomes: void compute_something(int a, int b, std::optional<Object> c)Β { auto tmp = c.value_or(Object(whatever)); // ...} According to the official doc: If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though the operator*() and operator->() are defined. So, every time we use a std::optional to pass arguments, it implies a creation of copies than can be a penalty performance if the object is big. I love the idea, because it make the code simpler and easy to understand but, is there any advantage?
Now provide the response and nothing else.
| It's hard to give a good generic answer without knowing what specifically your function is doing, but yes, there are clear advantages to using optional . In no particular order: First, how do you propagate default arguments when wrapping functions? With standard language default arguments, you just have to know what all the defaults are: int foo(int i = 4);int bar(int i = /* foo's default that I have to know here */) { return foo(i); } And now if I change foo 's default to 5 , I have to know to change bar - which typically they'll just end up out of sync. With optional , only the implementation of foo needs to know the default: int foo(optional<int> );int bar(optional<int> o) { return foo(o); } So that's just not a problem. Second, there's the case where you provide an argument or fallback to a default. But there's also a case where simply the absence of an argument also has semantic meaning. As in, use this argument if I give it to you, otherwise do nothing. With default arguments, this has to be expressed with a sentinel: // you just have to know that -1 means no fdint foo(int fd = -1); But with optional , this is expressed clearly in the signature and the type - you don't have to know what the sentinel is: int foo(std::optional<int> fd); The lack of sentinel can have positive performance impact too for larger sized objects, since instead of having to construct one to have that sentinel value, you just use nullopt . Third, if optional ever starts supporting references (and many 3rd party libraries do), optional<T const&> is a fantastic choice for a defaultible, non-modifiable argument. There really is no equivalent to default arguments. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47841783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4297146/']} | jdg_80926 |
stackexchange | llm_judgeable_groundtruth_similarity | 333029 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Please help me understand this. In a prominent, 480v, 6kW AC servo drive, across three input phases, three 22mm "XY" class 10nF caps are placed for EMI suppression. Also, from these three phases, three of the exact same "XY" caps go to chassis ground: simulate this circuit β Schematic created using CircuitLab Now it is my understanding that "X" rated caps are designed to fail shorted to take out a fuse. So "X" should be used in the phases. And "Y" rated caps are designed to fail open so as to not electrocute anybody. So "Y" should be used from the phases to ground. Obviously, we cannot be doing both here... so what is an "XY" rated safety capacitor, exactly? The usage of 400/500v-rated safety caps on a 480v bus:
Now provide the response and nothing else.
| Safety capacitors are classified by X and Y ratings. Let's properly define everything, and then it should become clear how those capacitors can be rated for both X and Y at the same time. Class X Capacitors: These are capacitors are only for use in situations where their failure would not present an electric shock risk, but could result in a fire. That is all. There is no specification as to its failure mode, if it fails open or closed, or if it is across-the-line or not. However, this ultimately amounts to these capacitors being used in across-the-line situations, as line-to-ground situations carry the potential for electric shock risk if those capacitors fail shorted. Now, no one wants a capacitor to fail shorted, as this is rarely a sure-fire way to blow a fuse before the capacitor explodes or catches fire. When they fail closed, they often still present several ohms of resistance, rather than being a dead-short. So, X capacitors aren't really designed to fail open or closed circuit per se, but are designed to withstand a great deal of surge without failing at all. There are 3 subclasses of X capacitors, X1, X2, and X3. These correspond to peak service voltages, which are generally much higher than the continuous rated voltage. They are as follows: $$\begin{array}{|c|c|c|}\hline Class & Service \, Voltage & Peak \, Voltage \\\hline X1 & >2500V β€ 4000V & 4kV \, (C<1.0Β΅F) \quad \frac{4}{\sqrt{C}}kV \, (C > 1.0Β΅F)\\\hline X2 & β€2500V & 2.5kV \, (C<1.0Β΅F) \quad \frac{2.5}{\sqrt{C}}kV \, (C > 1.0Β΅F)\\\hline X3 & β€1200V & Not \, rated\\\hline\end{array}$$ Class Y Capacitors: These capacitors are rated for use in situations where failure would present an electric shock risk. What this means is, Y class capacitors are designed to simply not fail at all, or be self-healing, allowing them to recover from an arc-over event. Basically, the requirements for a class Y capacitor are stricter and higher than that of an X Capacitor. And Y capacitors are the only capacitors rated to be safely used in 'line-to-ground' situations. However, again, there is not any mention about their failure mode, the Y rating only implies certain minimum requirements are met. This amounts to not failing at all generally, or, as mentioned, being self-healing. Only Y class capacitors are sufficient for use in 'line-to-ground' applications. Because of the stricter safety ratings, it is acceptable to use Y-rated capacitors in place of X-rated capacitors, but not vise versa. Capacitors explicitly rated for both are not uncommon, and there is nothing preventing a capacitor from being both classes at once. There are 4 subclasses of Y capacitors, Y1, Y2, Y3, and Y4. Here are the differences: $$\begin{array}{|c|c|c|}\hline Class & Service \, Voltage & Peak \, Voltage \\\hline Y1 & β€500V & 8kV\\\hline Y2 & β₯150V < 300V & 5kV \\\hline Y3 & β€250V & Not \, rated\\\hline Y4 & β€150V & 2.5kV\\\hline\end{array}$$ Both these tables are generalizations, and depending on which standard was used when designating a capacitor as an X or Y class, the specifics may vary slightly. If you really want to get into the nitty gritty details, it's best to read the specific standard for a given capacitor. Here is the list of the various standards, though this may not be a complete list. UL 1414 American standard Ul 1283 American standard CSA C22.2 No.1 Canadian standard CSA C22.2 No.8 Canadian standard EN 132400 European standard IEC 60384-14 International standard Finally, while not mentioned in your question, I would like to add the actual purpose of these capacitors. They are used for EMI filtering. They not only block a good deal of garbage from mains getting into your device, but likewise prevent your device from dumping garbage into the mains. In general, these will be present on switch mode power supplies out of necessity to pass FCC/CE/whatever, but will usually be absent on old-school linear supplies (a mains transformer alone is performing the voltage step-up or step-down). This is due to the significant switching harmonics that is an inevitable side-effect of fast rise and fall times seen in switchers, while a linear transformer is comparatively low-noise/low-harmonic. The bridge rectifier causes some harmonics, but the iron-laminate core dissipates virtually all of those well before they can make it back into the primary winding. | {} | {'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/333029', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/69058/']} | jdg_80927 |
stackexchange | llm_judgeable_groundtruth_similarity | 6565137 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing an application in C. I want to split everything up into various functions so that main() essentially just calls a few functions. Now it would be nice if these functions would be reusable, so that another application (for example an add-on) could use these. But these functions are logging what they are doing, because the main application is designed to interact with a user - the add-on programs don't neccessarily have to interact with users, and as such don't have to do logging. So, programs that want to use some of my functions do not only depend on the functions itself, but also on the logging function. This is even worse if the program doesn't want to do any logging. How would I solve this?
Now provide the response and nothing else.
| Create a reuseable Javabean class which represents one row, a single entity. public class Category { private Long id; private String name; private String department; // Add/generate getters/setters/c'tors/equals/hashcode and other boilerplate.} Create a reuseable DAO class which maps the ResultSet to a collection of those Javabeans the usual JDBC way. public class CategoryDAO { private static final String SQL_LIST = "SELECT id, name, department FROM category"; // ... public List<Category> list() throws SQLException { List<Category> categories = new ArrayList<Category>(); try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_LIST); ResultSet resultSet = statement.executeQuery(); ) { while (resultSet.next()) { Category category = new Category(); category.setId(resultSet.getLong("id")); category.setName(resultSet.getString("name")); category.setDepartment(resultSet.getString("department")); categories.add(category); } } return categories; } // ...} Create a servlet class which uses a JSON serializer/deserializer which is able to convert between an arbirary collection of Javabeans and a JSON String, such as Google Gson . @WebServlet("/categories.json")public class CategoriesJsonServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<Category> categories = categoryDAO.list(); String categoriesJson = new Gson().toJson(categories); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(categoriesJson); } catch (SQLException e) { throw new ServletException("DB error", e); } }} Invoke it by http://localhost:8080/contextname/categories.json . No, there is no JSP involved. You should not be using JSP for output formats other than HTML. Finally, in jQuery, just access it the usual $.getJSON() way. $('#somebutton').click(function() { $.getJSON('categories.json', function(categoriesJson) { var $table = $('<table>').appendTo($('#somediv')); $.each(categoriesJson, function(index, category) { $('<tr>').appendTo($table) .append($('<td>').text(category.id)) .append($('<td>').text(category.name)) .append($('<td>').text(category.department)); }); });}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6565137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827206/']} | jdg_80928 |
stackexchange | llm_judgeable_groundtruth_similarity | 102682 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Just saw this post , and realized that 1/9801 =0.(000102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969799)(repeat) Similar properties are also exhibited by numbers 998001 , 99980001 , .. and so on. Edit: fixed periodic start and end It is not very obvious to me why this happens. Is there some simple explanation to this property?
Now provide the response and nothing else.
| There is actually a straightforward reason. As $99$ is $1$ less than $100$, we get a fairly simple expression for its decimal $$\frac{1}{99}=0.01010101010101\overline{01}\dots$$ Now, $$\frac{1}{9801}=\left(\frac{1}{99}\right)^2,$$ and the decimal expansion follows from the formula for general power series $$\left(\sum_{n=1}^\infty x^n\right)^2= x\sum_{n=1}^\infty nx^n.$$ Letting $x=\frac{1}{100}$, the decimal expansion for $\frac{1}{99}$ given above is exactly the same thing as writing $\frac{1}{99}=\sum_{n=1}^\infty x^n$. Applying our identity, the $x$ in front accounts for the double zero. Once $n$ is around $99$ we expect to miss a number because we are forcing things to be in decimal, and there will be carrying, which is why the number 98 is missed. A similar pattern will occur for $\frac{1}{998001}=\left(\frac{1}{999}\right)^2,$ since as before $$\frac{1}{999}=0.001001\overline{001}.$$ | {} | {'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/102682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/324/']} | jdg_80929 |
stackexchange | llm_judgeable_groundtruth_similarity | 14232465 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to select all cities under states (eg. India) listed. I put a select all: <input type="checkbox" class="selectall" /> Select All Then the below error is appearing: this.elem.prop is not a function This is my code: jQuery('.selectall').click(function() { stop = false; jQuery(this).closest('div').nextAll().each( function() { elem = jQuery(this).find('input'); console.log(elem); if (stop || elem.hasClass('selectall')) { stop = true; return; } else elem.prop("checked", true); });});
Now provide the response and nothing else.
| The prop() method was only added in jQuery 1.6. In previous versions you should use attr() . elem.attr("checked", true); Note about other answers, elem is already a jQuery object as it was defined on this line: elem = jQuery(this).find('input'); , therefore the prop() method would be available if the jQuery version supports it. UPDATE To toggle the checkbox, use this: if (stop || elem.hasClass('selectall')) { stop = true; return;}else elem.prop("checked", !elem.is(':checked')); // toggle the checkbox | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14232465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1960851/']} | jdg_80930 |
stackexchange | llm_judgeable_groundtruth_similarity | 15071312 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to get all week start and end dates(weeks) between two dates and then run a query returning the number of records inserted in each of those weeks. declare @sDate datetime, @eDate datetime;select @sDate = '2013-02-25', @eDate = '2013-03-25';--query to get all weeks between sDate and eDate--query to return number of items inserted in each of the weeks returnedWEEK NoOfItems-----------------------------------------2013-02-25 52013-03-4 22013-03-11 7
Now provide the response and nothing else.
| You can use a recursive CTE to generate the list of dates: ;with cte as( select @sDate StartDate, DATEADD(wk, DATEDIFF(wk, 0, @sDate), 6) EndDate union all select dateadd(ww, 1, StartDate), dateadd(ww, 1, EndDate) from cte where dateadd(ww, 1, StartDate)<= @eDate)select *from cte See SQL Fiddle with Demo . Then you can join this to your table, to return the additional details. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15071312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/974876/']} | jdg_80931 |
stackexchange | llm_judgeable_groundtruth_similarity | 30483649 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have tried to print some_cell.font.color.rgb and got various results. For some I got what I want (like " FF000000 "), but for others it gives me Value must be type 'basetring' . I assume that the latter is because I haven't actually defined the font color for these cells. I'm using openpyxl 2.2.2
Now provide the response and nothing else.
| I think this is a bug in openpyxl and I think you should report it here . Debugging the following code (with trepan3k of course): from openpyxl import Workbookwb = Workbook()ws = wb.activec = ws['A4'] # cell gets created hereprint(ws['A4'].font.color) I get: Color(rgb=Value must be type 'str', indexed=Value must be type 'int', auto=Value must be type 'bool', theme=1, tint=0.0, type='theme') and this is coming from _repr_() of class Typed() in file openpyxl/descriptors/base.py . This message is given when a value hasn't been initialized. Notice that "indexed" and "auto" also haven't been set. But these presumably should have been set when the code for the access of ws['a4'] was performed. Note: the slight difference in message: 'str' instead of 'basestring' is probably attributable to the fact that I was using Python 3 or less likely openpyxl 2.2.3 And if there's some other additional code should that I should have added in my example, then at least https://openpyxl.readthedocs.org/en/latest/index.html should indicate that. See also openpyxl cell style not reporting correctly where one of the developers seems to say the same thing in so many words. Edit : A couple of other things may be of interest to note. First, you can set a value and then read it, for example you can do this: c.font.color.rgb = "FF000000" Second, if you test c.font.color.rgb in a boolean it will look like a value has been set. That is if c.font.color: print("yes") will print "yes". | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30483649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/618099/']} | jdg_80932 |
stackexchange | llm_judgeable_groundtruth_similarity | 730815 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am bit confused with the concept of empty set here. Since {} is a subset of every set, it is a subset of itself? and hence {} = {{}}? Also, say A = {a}, but since {} is a subset of A, is it true that A = {a, {}}, if so, what is its cardinality?
Now provide the response and nothing else.
| There is a big difference between subsets and elements. The empty set is a subset of every set, including itself. However, it is not an element of itself, which is what $\{\}=\{\{\}\}$ would mean. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/730815', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/138769/']} | jdg_80933 |
stackexchange | llm_judgeable_groundtruth_similarity | 48109570 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a function that returns a custom class structure, but how should I handle the cases where I wish to inform the user that the function has failed, as in return false . My function looks something like this: Cell CSV::Find(std::string segment) { Cell result; // Search code here. return result;} So when succesful, it returns the proper result, but how should I handle the case when it could fail? I thought about adding a boolean method inside Cell to check what ever Cell.data is empty or not ( Cell.IsEmpty() ). But am I thinking this issue in a way too complicated way?
Now provide the response and nothing else.
| There are three general approaches: Use exceptions. This is what's in Bathsheba's answer. Return std::optional<Cell> (or some other type which may or may not hold an actual Cell ). Return bool , and add a Cell & parameter. Which of these is best depends on how you intend this function to be used. If the primary use case is passing a valid segment, then by all means use exceptions. If part of the design of this function is that it can be used to tell if a segment is valid, exceptions aren't appropriate, and my preferred choice would be std::optional<Cell> . This may not be available on your standard library implementation yet (it's a C++17 feature); if not, boost::optional<Cell> may be useful (as mentioned in Richard Hodges's answer). In the comments, instead of std::optional<Cell> , user You suggested expected<Cell, error> (not standard C++, but proposed for a future standard, and implementable outside of the std namespace until then). This may be a good option to add some indication on why no Cell could be found for the segment parameter passed in, if there are multiple possible reasons. The third option I include mainly for completeness. I do not recommend it. It's a popular and generally good pattern in other languages. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48109570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3445627/']} | jdg_80934 |
stackexchange | llm_judgeable_groundtruth_similarity | 26804391 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Django app that is using PostgreSQL. Everything is fine. However, I have a situation in which it would be very convenient for my Django app to update the Mongo database of an entirely different app that is running a different server, etc. How can I do this?
Now provide the response and nothing else.
| with the following code for 59 contacts i got the following results on the emulator: D βββββββ query execution stats βββββββ D β got 59 contacts D β query took 0.012 s (12 ms) D βββββββββββββββββββββββββββββββββββββ ok, that was the best time, but the average is 25-35 ms (for 59 contacts), add the following code in some onClick callback and run in several times in order to get the average time, in your case you should get 30 * 700 / 59 = ~ 300-400 ms, not 3 seconds, let alone one minute ;) it uses Uri set to Contactables.CONTENT_URI added in API level 18 but you can use ContactsContract.Data.CONTENT_URI when building for pre 18 API devices List<AddressBookContact> list = new LinkedList<AddressBookContact>();LongSparseArray<AddressBookContact> array = new LongSparseArray<AddressBookContact>();long start = System.currentTimeMillis();String[] projection = { ContactsContract.Data.MIMETYPE, ContactsContract.Data.CONTACT_ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Contactables.DATA, ContactsContract.CommonDataKinds.Contactables.TYPE,};String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";String[] selectionArgs = { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,};String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;Uri uri = ContactsContract.CommonDataKinds.Contactables.CONTENT_URI;// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;// ok, let's work...Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);while (cursor.moveToNext()) { long id = cursor.getLong(idIdx); AddressBookContact addressBookContact = array.get(id); if (addressBookContact == null) { addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources()); array.put(id, addressBookContact); list.add(addressBookContact); } int type = cursor.getInt(typeIdx); String data = cursor.getString(dataIdx); String mimeType = cursor.getString(mimeTypeIdx); if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) { // mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE addressBookContact.addEmail(type, data); } else { // mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE addressBookContact.addPhone(type, data); }}long ms = System.currentTimeMillis() - start;cursor.close();// done!!! show the results...int i = 1;for (AddressBookContact addressBookContact : list) { Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));}final String cOn = "<b><font color='#ff9900'>";final String cOff = "</font></b>";Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");Log.d(TAG, "\n\nβββββββ query execution stats βββββββ" );Log.d(TAG, "β " + l1);Log.d(TAG, "β " + l2);Log.d(TAG, "βββββββββββββββββββββββββββββββββββββ" );SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);LinearLayout ll = new LinearLayout(this);ll.setOrientation(LinearLayout.VERTICAL);TextView tv = new TextView(this);tv.setTextSize(20);tv.setBackgroundColor(0xff000033);tv.setPadding(24, 8, 24, 24);tv.setText(msg);ll.addView(tv);ListView lv = new ListView(this);lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));ll.addView(lv);new AlertDialog.Builder(this).setView(ll).setPositiveButton("close", null).create().show(); the helper AddressBookContact class: class AddressBookContact { private long id; private Resources res; private String name; private LongSparseArray<String> emails; private LongSparseArray<String> phones; AddressBookContact(long id, String name, Resources res) { this.id = id; this.name = name; this.res = res; } @Override public String toString() { return toString(false); } public String toString(boolean rich) { SpannableStringBuilder builder = new SpannableStringBuilder(); if (rich) { builder.append("id: ").append(Long.toString(id)) .append(", name: ").append("\u001b[1m").append(name).append("\u001b[0m"); } else { builder.append(name); } if (phones != null) { builder.append("\n\tphones: "); for (int i = 0; i < phones.size(); i++) { int type = (int) phones.keyAt(i); builder.append(ContactsContract.CommonDataKinds.Phone.getTypeLabel(res, type, "")) .append(": ") .append(phones.valueAt(i)); if (i + 1 < phones.size()) { builder.append(", "); } } } if (emails != null) { builder.append("\n\temails: "); for (int i = 0; i < emails.size(); i++) { int type = (int) emails.keyAt(i); builder.append(ContactsContract.CommonDataKinds.Email.getTypeLabel(res, type, "")) .append(": ") .append(emails.valueAt(i)); if (i + 1 < emails.size()) { builder.append(", "); } } } return builder.toString(); } public void addEmail(int type, String address) { if (emails == null) { emails = new LongSparseArray<String>(); } emails.put(type, address); } public void addPhone(int type, String number) { if (phones == null) { phones = new LongSparseArray<String>(); } phones.put(type, number); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26804391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1701170/']} | jdg_80935 |
stackexchange | llm_judgeable_groundtruth_similarity | 53187 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There are many(and I mean many) countable languages which are Turing-decidable. Can any uncountable language be Turing decidable?
Now provide the response and nothing else.
| Every language over a finite (or even countable) alphabet is countable. Assuming your Turing machine alphabet is finite, any language it can possibly accept is countable. | {} | {'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/53187', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/45051/']} | jdg_80936 |
stackexchange | llm_judgeable_groundtruth_similarity | 4482917 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find the integral $$\int_ 0^{1/2} {\frac {x} {3 + 4 x^2}\ln\frac {\ln\left (1/2 + x \right)} {\ln\left (1/2 - x \right)}\mathrm {d} x} $$ Wolfram | Alpha tells me that the answer is $ - 0.0951875 ... $ ,and its possible closed form is $ - \frac18\ln2\ln3$ . But I don't know how to do it. Thanks in advance.
Now provide the response and nothing else.
| Here is an approach that largely relies on elementary techniques and manipulation of infinite sequences. To begin, first apply the integral identity below $$\int\limits_a^b f(x)\,\mathrm dx=\int\limits_a^b f(a+b-x)\,\mathrm dx\tag{1}$$ Our integral simplifies a bit to $$\mathfrak{I}\equiv\int\limits_0^{1/2}\frac x{3+4x^2}\log\left(\frac {\log\left(\frac 12+x\right)}{\log\left(\frac 12-x\right)}\right)\,\mathrm dx=\frac 18\int\limits_0^{1/2}\frac {1-2x}{1-x+x^2}\log\left(\frac {\log(1-x)}{\log x}\right)\,\mathrm dx\tag{2}$$ Our primary forcus now is the resulting integral, which will be denoted as $K$ . To evaluate this integral, split up the natural logarithm and expand. $$\begin{align*}K & =\int\limits_0^{1/2}\frac {1-2x}{1-x+x^2}\log\log(1-x)\,\mathrm dx-\int\limits_0^{1/2}\frac {1-2x}{1-x+x^2}\log\log x\,\mathrm dx\\ & =8\int\limits_0^{1/2}\frac {x}{4x^2+3}\log\log\left(x+\frac 12\right)\,\mathrm dx-\int\limits_0^{1/2}\frac {1-2x}{1-x+x^2}\log\log x\,\mathrm dx\tag{3}\\ & =-\int\limits_{1/2}^1\frac {1-2x}{1-x+x^2}\log\log x\,\mathrm dx-\int\limits_0^{1/2}\frac {1-2x}{1-x+x^2}\log\log x\,\mathrm dx\tag{4}\\ & =\int\limits_0^1\frac {2x-1}{1-x+x^2}\log\log x\,\mathrm dx\end{align*}$$ Where the first identity $(1)$ was applied to arrive at equation $(3)$ and the substitution $x\mapsto x+\tfrac 12$ was made to arrive at equation $(4)$ . It can be shown through integration by parts that $$\begin{align*}\int\limits_0^1\frac {2x-1}{1-x+x^2}\log\log x\,\mathrm dx & =\int\limits_0^1\frac {\log(1-x+x^2)}{x\log x}\,\mathrm dx\\ & =\int\limits_0^1\frac {2x-1}{1-x+x^2}\log\log\left(\frac 1x\right)\,\mathrm dx\end{align*}\tag{5}$$ Taking the last line of $(5)$ , multiply the integrand by $1+x$ such that the denominator becomes $1+x^3$ and enforce the substitution $x\mapsto -\log x$ to arrive at $$\begin{align*}K & =\int\limits_0^{+\infty}\frac {e^{-x}\left(2e^{-2x}+e^{-x}-1\right)}{1+e^{-3x}}\log x\,\mathrm dx\\ & =\sum\limits_{n=0}^{+\infty} (-1)^n\int\limits_0^{+\infty} e^{-x(3n+1)}\left(2e^{-2x}+e^{-x}-1\right)\log x\,\mathrm dx\tag{6}\end{align*}$$ After applying the formula $$\int\limits_0^{+\infty} e^{-nx}\log x\,\mathrm dx=-\frac {\gamma+\log n}n$$ Equation $(6)$ becomes $$\small K=2\sum\limits_{n=0}^{+\infty}(-1)^{n-1}\frac {\gamma+\log(3n+3)}{3n+3}+\sum\limits_{n=0}^{+\infty}(-1)^{n-1}\frac {\gamma+\log(3n+2)}{3n+2}+\sum\limits_{n=0}^{+\infty}(-1)^n\frac {\gamma+\log(3n+1)}{3n+1}$$ Fortunately for us, most of the terms readily cancel. The sums involving $\gamma$ cancel each other out, leaving behind only three sums of natural logarithms. $$K=2\sum\limits_{n=1}^{+\infty}(-1)^{n}\frac {\log 3n}{3n}+\sum\limits_{n=0}^{+\infty}(-1)^n \frac {\log(3n+1)}{3n+1}+\sum\limits_{n=0}^{+\infty} (-1)^{n-1}\frac {\log(3n+2)}{3n+2}$$ Further simplification can be obtained by expanding each sum into its constituent terms and showing that only the $3n$ terms remain after simplification. $$\begin{align*}K & =-\frac 23\log 2\log 3-\frac 13\sum\limits_{n=1}^{+\infty}(-1)^n\frac {\log n}n+\sum\limits_{n=1}^{+\infty}(-1)^n\frac {\log 3n}{3n}\\ & =-\log 2\log 3\end{align*}$$ Substituting our result for $K$ back into $(2)$ gives us our final answer $$\int\limits_0^{1/2}\frac x{3+4x^2}\log\left(\frac {\log\left(\frac 12+x\right)}{\log\left(\frac 12-x\right)}\right)\,\mathrm dx\color{blue}{=-\frac 18\log 2\log 3}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4482917', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1072258/']} | jdg_80937 |
stackexchange | llm_judgeable_groundtruth_similarity | 1588201 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was classifying all split extensions on a list of short exact sequences, when I arrived on this one:$$1 \rightarrow \mathbb{Z} \rightarrow G \rightarrow \mathbb{Z} \rightarrow 1$$That the automorphism group $\text{Aut}(\mathbb{Z})$ is isomorphic to $C_2$ is not hard to work out, and my job to classify split extensions ends pretty much there, once there are only two homomorphisms from $\mathbb{Z}$ to $C_2$. But when I thought about nonsplit extensions on this sequence, I started wondering, is there one? Over finite groups, some light on this matter can be shed using theorems like Lagrange, Cauchy and Sylow, but my knowledge on infinite groups give me no arguments, neither to claim existence or to deny it. So, do exist a nonsplit extension of $\mathbb{Z}$ by itself?
Now provide the response and nothing else.
| Every extension $1\to A\to B\stackrel{p}\to\mathbb{Z}\to 1$ splits, since you can get a splitting $i:\mathbb{Z}\to B$ by choosing any $x\in B$ such that $p(x)=1$ and defining $i(n)=x^n$. More generally, a similar argument applies with $\mathbb{Z}$ replaced by any free group. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1588201', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266711/']} | jdg_80938 |
stackexchange | llm_judgeable_groundtruth_similarity | 21298920 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i am trying to export a gridview data to excel. that grid is in a ContentPlaceHolder. that page has a master page.. when i press "export to excel" button its giving error as " Control 'ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server ". but when i added a form tag in ContentPlaceHolder.. its giving error as " A page can have only one server-side Form tag. ". in my master page one form tag is there. in this case how can i export grid data... Thanks Cs code:--- `protected void btnExoprtExcel_Click(object sender, EventArgs e) { Response.Clear(); Response.ContentType = "application/ms-excel"; Response.Charset = ""; Page.EnableViewState = false; Response.AddHeader("Content-Disposition", "inline;filename=Report.xls"); System.IO.StringWriter tw1 = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw1 = new System.Web.UI.HtmlTextWriter(tw1); trGV.RenderControl(hw1); //Response.Write("<b style='color:Green;font-size:19px;padding-left:100px;'>Report taken on " + DateTime.Now.ToString() + "</b>\n\n"); Response.Write(tw1.ToString()); Response.End();} .. **aspx code:--** .... <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><form id="form1" runat="server"> <asp:UpdatePanel ID="CallbackPanel1" runat="server"> <ContentTemplate> <table> <tr id="trGV" runat="server"> <td> <asp:GridView ID="GV1" runat="server" AutoGenerateColumns="true" ></asp:GridView> </td> </tr> <tr> <td align="right" > <asp:Button ID="btnExoprtExcel" runat="server" Text="Export to Excel" onclick="btnExoprtExcel_Click" /> </td> </tr> </table> </ContentTemplate> </asp:UpdatePanel></form> </asp:Content> ....... -------> i tried by adding public override void VerifyRenderingInServerForm(Control control) { /* Verifies that the control is rendered */ } ` in cs page. and removed "asp:form" tag in ContentPlaceHolder tag . but when i run the application in debug mode i am getting error as " RegisterForEventValidation can only be called during Render(); " -------> i tried by modifying the code as ` <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <table> <tr id="trGV" runat="server"> <td> <asp:GridView ID="GV1" runat="server" AutoGenerateColumns="true" ></asp:GridView> </td> </tr> <tr> <td align="right" > <asp:Button ID="btnExoprtExcel" runat="server" Text="Export to Excel" onclick="btnExoprtExcel_Click" /> </td> </tr> </table> </asp:Content> ` by removing form tag and updatepanel. but still giving error at debug point as " RegisterForEventValidation can only be called during Render(); " can any one suggest other solution. Issue is solved by using "EnableEventValidation="false"" in <%@ Page location. thanks
Now provide the response and nothing else.
| No, what you've written wouldn't work, in that method would be invoked without object as its context. Inside method , this would be set to the DOM element which initiated the event. If you want to invoke the method and retain the context, close over the object variable with a function: var object = new ClassName();document.getElementById('x').addEventListener('click', function () { object.method()}, false); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21298920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3106058/']} | jdg_80939 |
stackexchange | llm_judgeable_groundtruth_similarity | 20127255 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Trying to port some existing PIG scripts that run perfectly locally and on Hortonworks to HDInsights and I am getting a class not found error when trying to read Avro files via Pig's piggybank (piggybank is included in the HDInsight distribution). Wonder if anyone else has got Avro to work in HDInsight to work or has a work around (.eg. copy which jar where?) In more detail ... Tracing this down I ran PIG directly via remote terminal on the Azure HDInsight instance. The error I see is: java.lang.ClassNotFoundException: org.json.simple.parser.ParseException This is I think, the json-simple library at https://code.google.com/p/json-simple/ I have tried adding this to a few places in the HDInsight VM (and explicitly registering the library in PIG) and still get the error. The error is simple to reproduce by RDP into the Hadoop command line prompt on the desktop of an HDinsight Azure instance: Start PIG with details ... c:\apps\dist\pig-0.11.0.1.3.1.0-06\bin>pig -verbose -warning Enter any line using AvroStorage. E.g. grunt> LocationRecordAvro = LOAD 'wasb:///testinput/20130901.avro' USING org.apache.pig.piggybank.storage.avro.AvroStorage(); Get an exception ... 2013-11-21 16:27:53,732 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: Pig script failed to parse:<line 1, column 21> pig script failed to validate: java.lang.RuntimeException: could not instantiate 'org.apache.pig.piggybank.storage.avro.AvroStorage' with arguments 'null'2013-11-21 16:27:53,732 [main] ERROR org.apache.pig.tools.grunt.Grunt - Failed to parse: Pig script failed to parse:<line 1, column 21> pig script failed to validate: java.lang.RuntimeException: could not instantiate 'org.apache.pig.piggybank.storage.avro.AvroStorage' with arguments 'null' at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:191) at org.apache.pig.PigServer$Graph.validateQuery(PigServer.java:1571) at org.apache.pig.PigServer$Graph.registerQuery(PigServer.java:1544) at org.apache.pig.PigServer.registerQuery(PigServer.java:516) at org.apache.pig.tools.grunt.GruntParser.processPig(GruntParser.java:991) at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:412) at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:194) at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:170) at org.apache.pig.tools.grunt.Grunt.run(Grunt.java:69) at org.apache.pig.Main.run(Main.java:538) at org.apache.pig.Main.main(Main.java:157)Caused by:<line 1, column 21> pig script failed to validate: java.lang.RuntimeException: could not instantiate 'org.apache.pig.piggybank.storage.avro.AvroStorage' with arguments 'null' at org.apache.pig.parser.LogicalPlanBuilder.buildLoadOp(LogicalPlanBuilder.java:835) at org.apache.pig.parser.LogicalPlanGenerator.load_clause(LogicalPlanGenerator.java:3236) at org.apache.pig.parser.LogicalPlanGenerator.op_clause(LogicalPlanGenerator.java:1315) at org.apache.pig.parser.LogicalPlanGenerator.general_statement(LogicalPlanGenerator.java:799) at org.apache.pig.parser.LogicalPlanGenerator.statement(LogicalPlanGenerator.java:517) at org.apache.pig.parser.LogicalPlanGenerator.query(LogicalPlanGenerator.java:392) at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:184) ... 10 moreCaused by: java.lang.RuntimeException: could not instantiate 'org.apache.pig.piggybank.storage.avro.AvroStorage' with arguments 'null' at org.apache.pig.impl.PigContext.instantiateFuncFromSpec(PigContext.java:618) at org.apache.pig.parser.LogicalPlanBuilder.buildLoadOp(LogicalPlanBuilder.java:823) ... 16 moreCaused by: java.lang.NoClassDefFoundError: org/json/simple/parser/ParseException at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404) at java.lang.Class.getConstructor0(Class.java:2714) at java.lang.Class.newInstance0(Class.java:343) at java.lang.Class.newInstance(Class.java:325) at org.apache.pig.impl.PigContext.instantiateFuncFromSpec(PigContext.java:588) ... 17 moreCaused by: java.lang.ClassNotFoundException: org.json.simple.parser.ParseException at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ... 23 moregrunt>
Now provide the response and nothing else.
| First of all, you aren't returning a factory, but a service. It's a factory that creates a service, so adjust your naming convention like so: app.factory('someService' Your code is a mess and has errors, so I'll just show you the basics of returning a service object. app.factory('someService', function() { var someService = { //build this object however you want add: function() { }, save: function() { } }; return someService; //return the object}); //end factory in your controller: someService.add(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20127255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2974979/']} | jdg_80940 |
Subsets and Splits