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
4487007
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: Problem: Evaluate $$\underset{z=0}{\text{Res}} \; \frac{(z^6-1)^2}{z^5(2z^4 -5z^2 + 2)}.$$ My question: This is a question from a previous complex analysis qualifying exam that I am trying to work through. I know that the straightforward formula for calculating this residue would be $$\frac{1}{4!} \lim_{z\to 0} \frac{d^4}{dz^4} \left(z^5 \cdot \frac{(z^6-1)^2}{z^5(2z^4 -5z^2 + 2)} \right)$$ However, I'm guessing there is a better method in this case than taking four derivatives or trying to turn this into a Laurent series. Can someone point me in the right direction here? Now provide the response and nothing else.
Let $$f(z) = \frac{(z^6-1)^2}{z^5(2z^4 - 5z^2 + 2)}, \quad g(z) = \frac{(z^3-1)^2}{2z^2 - 5z + 2},$$ so that we have $f(z) = g(z^2)/z^5$ . So by computing the series expansion of $g$ about $0$ , we can obtain the Laruent expansion of $f$ , since $g$ has no singularity at $0$ . To this end, observe $$2z^2 - 5z + 2 = (2z-1)(z-2) = 2(1-2z)(1-z/2),$$ hence $$\begin{align}g(z) &= \frac{1}{6}(z^3 - 1)^2 \left( \frac{4}{1-2z} - \frac{1}{1-z/2} \right) \\&= \frac{1}{6} (z^3 - 1)^2 \sum_{k=0}^\infty 4(2z)^k - (z/2)^k \\&= \frac{1}{6} (z^6 - 2z^3 + 1) \sum_{k=0}^\infty (2^{k+2} - 2^{-k}) z^k.\end{align}$$ We specifically need the coefficient of $z^2$ in this expansion, since this yields the coefficient of $z^4$ in $g(z^2)$ , which in turn is the coefficient of $1/z$ in the Laurent expansion of $f$ . This corresponds to the choice $k = 2$ : $$g(z) = \cdots + \frac{1}{6}(2^4 - 2^{-2}) z^2 + \cdots.$$ Thus the required coefficient is $21/8$ , which is also the desired residue of $f$ at $0$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4487007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/700742/']}
jdg_372541
stackexchange
llm_judgeable_groundtruth_similarity
8017829
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 Play MP3 and getting unexpected errors. I have tested my app before 3 days which was working perfect on my device but now even that same jar file is giving me following error. javax.microedition.midlet.MediaException:Sounds not allowed error is coming when it executes this line player.prefetch() I am testing this app on Nokia 5200 and Nokia 5130 what could be problem? Please guide me. Following is my code. public class PlayAudioMidlet extends MIDlet {private Display display;AudioPlayer ap;public void startApp() {display = Display.getDisplay(this);ap = new AudioPlayer(this, display);display.setCurrent(ap); // display a subclass of Form named as AudioPlayer}public void pauseApp() {}public void destroyApp(boolean unconditional) {notifyDestroyed();}}class AudioPlayer extends Formimplements CommandListener, PlayerListener {PlayAudioMidlet midlet;private Display display;private Command play, stop, exit, forward, backward;private Player player;public AudioPlayer(PlayAudioMidlet midlet, Display display) {super("");this.midlet = midlet;this.display = Display.getDisplay(midlet);play = new Command("Play", Command.OK, 0);stop = new Command("Stop", Command.STOP, 0);exit = new Command("Exit", Command.EXIT, 0);addCommand(play);addCommand(stop);addCommand(forward);addCommand(backward);addCommand(exit);setCommandListener(this);}public void commandAction(Command c, Displayable d) {if (c == play) {try {//System.out.println(System.currentTimeMillis());playAudio();} catch (Exception e) {e.printStackTrace();}} else if (c == stop) {player.close();}}public void playerUpdate(Player player, String event, Object eventData) {}public void playAudio() {int i = 0;try {**//Even this commented line doesn't work//player = Manager.createPlayer(getClass().getResourceAsStream("/res/alert.mp3"), "audio/mpeg");player = Manager.createPlayer("file:///E:/Sound/alert1.mp3");**player.addPlayerListener(this);// player.setLoopCount(-1);player.prefetch();player.realize();player.start();} catch (Exception e) {Alert a = new Alert("");a.setString("Error "+e.toString());a.setTimeout(Alert.FOREVER);display.setCurrent(a);}}} Now provide the response and nothing else.
Implement NSToolbarItemValidation Protocol in your window, view or document controller. The documentation gives the following sample code: -(BOOL)validateToolbarItem:(NSToolbarItem *)toolbarItem { BOOL enable = NO; if ([[toolbarItem itemIdentifier] isEqual:SaveDocToolbarItemIdentifier]) { // We will return YES (enable the save item) // only when the document is dirty and needs saving enable = [self isDocumentEdited]; } else if ([[toolbarItem itemIdentifier] isEqual:NSToolbarPrintItemIdentifier]) { // always enable print for this window enable = YES; } return enable;} You can also use action or tag to determine what toolbar item is being validated. Items are validated frequently, whenever your app is activated or events are dispatched, so they will always be in a valid state.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8017829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/491978/']}
jdg_372542
stackexchange
llm_judgeable_groundtruth_similarity
284
Below is a question asked on the forum computergraphics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we already have UV coordinates assigned for mesh vertices,how is texture baking implemented? I guess it will be something like this: for each coordinate (u, v) in parameter space: (x, y, z) = inverse(u, v) # Get the geometric space coordinate. f = faces(x, y, z) # Get the corresponding face. We may need face's normal for rendering. pixels[u, v] = render(x, y, z, f) What is the inverse function? Is it a projective transformation, or a bilinear transformation? And how to get the corresponding face of one coordinate (u, v) efficiently? Now provide the response and nothing else.
Texture baking can be accomplished by simply rendering the mesh in texture space. In other words, you set up a render target matching the size of your texture, and draw the mesh with a vertex shader that sets the output position to the vertex's UV coordinate (appropriately remapped from [0, 1] UV space to [−1, 1] post-projective space). The vertex shader can still calculate the world-space position, normals, and whatever else it needs and send those down to the pixel shader. Then the pixel shader can do its thing without even being aware that it's rendering into texture space instead of the usual screen space. Lighting and shading calculations will work as usual as long as the pixel shader inputs are hooked up correctly. You don't have to do any complicated inversion operation; you just take advantage of the GPU rasterization hardware, which is happy to draw your triangles at any coordinates you choose. Naturally, this requires that your mesh already has a non-overlapping UV mapping that fits within the unit square, but texture baking doesn't really make sense without that.
{}
{'log_upvote_score': 4, 'links': ['https://computergraphics.stackexchange.com/questions/284', 'https://computergraphics.stackexchange.com', 'https://computergraphics.stackexchange.com/users/120/']}
jdg_372543
stackexchange
llm_judgeable_groundtruth_similarity
51707
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 had a test today which involved solving the following limit: $$\lim\limits_{x \to 0^+} \frac{\ln[\cos(x)]}{x}$$ I didn't figure out how to solve. After the test, I asked a couple of classmates and they told me that it was supposed to be solved by first transporting the multiplication by $\frac{1}{x}$ inside the logarithm as an exponent and then replacing $\cos(x)$ with $\sqrt{1-\sin^2(x)}$, giving the following expression: $$\lim\limits_{x \to 0^+} \ln[(1-\sin^2(x))^\frac{1}{2x}]$$ However, I don't know how to proceed from here. It's not like it matters a lot at this point, but I'd still like to know how I'm supposed to solve this. I'm not sure if it's applicable here, but we haven't learned L'Hôpital's rule. Now provide the response and nothing else.
Note that $\ln(\cos(0))=0$. So we can write our limit as$$\lim_{x\to 0^+} \frac{\ln(\cos(x))-\ln(\cos(0))}{(x-0)}.$$ Note that the above expression is almost the usual expression for the derivative of $\ln(\cos(x))$ at $x=0$. (If necessary, go back and look up the definition of the derivative of $f(x)$ at $x=a$). The only difference is the use of a one-sided limit. But what about if the two-sided limit existed? If we are very lucky and the derivative of $\ln(\cos(x))$ at $0$ exists, the value of that derivative at $x=0$ will be our answer. So differentiate $\ln(\cos(x))$ in the usual way. Everything works out nicely, the derivative is $0$. Added : I expect there is no issue in finding the derivative, but here are the details. Using the Chain Rule, we get $$-(\sin(x))\frac{1}{\cos(x)}.$$At $x=0$ this is $0$. So the $0^+$ turns out to be unnecessary, plain old $0$ will do. The manipulations suggested by classmates are not needed, everything follows from the definition of derivative, if we know a couple of differentiation rules. Comment : This is not really how I would do it, if I needed to know the answer. The "natural" approach is to use the power series expansions of $\cos(x)$ and $\ln(1+u)$. But since you mentioned that you had not yet done L'Hospital's Rule, I assumed that you would not yet have been exposed to power series. But the power series approach is very much worth knowing. The power series expansion of $\cos x$ is$$1-\frac{x^2}{2!}+\frac{x^4}{4!}-\frac{x^6}{6!} +\cdots.$$ So very informally, if $x$ is near $0$, $\cos x$ is about $1-x^2/2$. The power series expansion of $\ln(1+u)$ is$$u-\frac{u^2}{2}+\frac{u^3}{3} -\frac{u^4}{4}+\cdots.$$(This expansion is only valid when $-1 \lt u \le 1$.) So when $x$ is near $0$, $\ln(\cos(x))$ is about $-x^2/2$. Divide by $x$. We get $-x/2$, which approaches $0$ as $x$ approaches $0$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/51707', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2757/']}
jdg_372544
stackexchange
llm_judgeable_groundtruth_similarity
2740874
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 wrap my head around shaders in GLSL, and I've found some useful resources and tutorials, but I keep running into a wall for something that ought to be fundamental and trivial: how does my fragment shader retrieve the color of the current fragment? You set the final color by saying gl_FragColor = whatever , but apparently that's an output-only value. How do you get the original color of the input so you can perform calculations on it? That's got to be in a variable somewhere, but if anyone out there knows its name, they don't seem to have recorded it in any tutorial or documentation that I've run across so far, and it's driving me up the wall. Now provide the response and nothing else.
The fragment shader receives gl_Color and gl_SecondaryColor as vertex attributes. It also gets four varying variables: gl_FrontColor , gl_FrontSecondaryColor , gl_BackColor , and gl_BackSecondaryColor that it can write values to. If you want to pass the original colors straight through, you'd do something like: gl_FrontColor = gl_Color;gl_FrontSecondaryColor = gl_SecondaryColor;gl_BackColor = gl_Color;gl_BackSecondaryColor = gl_SecondaryColor; Fixed functionality in the pipeline following the vertex shader will then clamp these to the range [0..1], and figure out whether the vertex is front-facing or back-facing. It will then interpolate the chosen (front or back) color like usual. The fragment shader will then receive the chosen, clamped, interpolated colors as gl_Color and gl_SecondaryColor . For example, if you drew the standard "death triangle" like: glBegin(GL_TRIANGLES); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(-1.0f, 0.0f, -1.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(1.0f, 0.0f, -1.0f); glColor3f(1.0f, 0.0f, 0.0f); glVertex3d(0.0, -1.0, -1.0);glEnd(); Then a vertex shader like this: void main(void) { gl_Position = ftransform(); gl_FrontColor = gl_Color;} with a fragment shader like this: void main() { gl_FragColor = gl_Color;} will transmit the colors through, just like if you were using the fixed-functionality pipeline.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2740874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32914/']}
jdg_372545
stackexchange
llm_judgeable_groundtruth_similarity
17116814
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 working with a large csv file and the next to last column has a string of text that I want to split by a specific delimiter. I was wondering if there is a simple way to do this using pandas or python? CustNum CustomerName ItemQty Item Seatblocks ItemExt32363 McCartney, Paul 3 F04 2:218:10:4,6 6031316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 300 I want to split by the space (' ') and then the colon (':') in the Seatblocks column, but each cell would result in a different number of columns. I have a function to rearrange the columns so the Seatblocks column is at the end of the sheet, but I'm not sure what to do from there. I can do it in excel with the built in text-to-columns function and a quick macro, but my dataset has too many records for excel to handle. Ultimately, I want to take records such John Lennon's and create multiple lines, with the info from each set of seats on a separate line. Now provide the response and nothing else.
This splits the Seatblocks by space and gives each its own row. In [43]: dfOut[43]: CustNum CustomerName ItemQty Item Seatblocks ItemExt0 32363 McCartney, Paul 3 F04 2:218:10:4,6 601 31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 300In [44]: s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()In [45]: s.index = s.index.droplevel(-1) # to line up with df's indexIn [46]: s.name = 'Seatblocks' # needs a name to joinIn [47]: sOut[47]: 0 2:218:10:4,61 1:13:36:1,121 1:13:37:1,13Name: Seatblocks, dtype: objectIn [48]: del df['Seatblocks']In [49]: df.join(s)Out[49]: CustNum CustomerName ItemQty Item ItemExt Seatblocks0 32363 McCartney, Paul 3 F04 60 2:218:10:4,61 31316 Lennon, John 25 F01 300 1:13:36:1,121 31316 Lennon, John 25 F01 300 1:13:37:1,13 Or, to give each colon-separated string in its own column: In [50]: df.join(s.apply(lambda x: Series(x.split(':'))))Out[50]: CustNum CustomerName ItemQty Item ItemExt 0 1 2 30 32363 McCartney, Paul 3 F04 60 2 218 10 4,61 31316 Lennon, John 25 F01 300 1 13 36 1,121 31316 Lennon, John 25 F01 300 1 13 37 1,13 This is a little ugly, but maybe someone will chime in with a prettier solution.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/17116814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1955794/']}
jdg_372546
stackexchange
llm_judgeable_groundtruth_similarity
3600777
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 way to make a read-only property of an object in PHP? I have an object with a couple arrays in it. I want to access them as I normally would an array echo $objObject->arrArray[0]; But I don't want to be able to write to those arrays after they're constructed. It feels like a PITA to construct a local variable: $arrArray = $objObject->getArray1();echo $arrArray[0]; And anyways, while it keeps the array in the object pristine, it doesn't prevent me from re-writing the local array variable. Now provide the response and nothing else.
Well, the question is where do you want to prevent writing from? The first step is making the array protected or private to prevent writing from outside of the object scope: protected $arrArray = array(); If from "outside" of the array, a GETTER will do you fine. Either: public function getArray() { return $this->arrArray; } And accessing it like $array = $obj->getArray(); or public function __get($name) { return isset($this->$name) ? $this->$name : null;} And accessing it like: $array = $obj->arrArray; Notice that they don't return references. So you cannot change the original array from outside the scope of the object. You can change the array itself... If you really need a fully immutable array, you could use a Object using ArrayAccess ... Or, you could simply extend ArrayObject and overwrite all of the writing methods: class ImmutableArrayObject extends ArrayObject { public function append($value) { throw new LogicException('Attempting to write to an immutable array'); } public function exchangeArray($input) { throw new LogicException('Attempting to write to an immutable array'); } public function offsetSet($index, $newval) { throw new LogicException('Attempting to write to an immutable array'); } public function offsetUnset($index) { throw new LogicException('Attempting to write to an immutable array'); }} Then, simply make $this->arrArray an instance of the object: public function __construct(array $input) { $this->arrArray = new ImmutableArrayObject($input);} It still supports most array like usages: count($this->arrArray);echo $this->arrArray[0];foreach ($this->arrArray as $key => $value) {} But if you try to write to it, you'll get a LogicException ... Oh, but realize that if you need to write to it, all you need to do (within the object) is do: $newArray = $this->arrArray->getArrayCopy();//Edit array here$this->arrArray = new ImmutableArrayObject($newArray);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3600777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151841/']}
jdg_372547
stackexchange
llm_judgeable_groundtruth_similarity
15829768
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here are my requirements: 1. Create links to a single app in the app store 2. Access the links either from inside an app, on the device generally (e.g. mail link) or from a PC (e.g. via facebook share link) 3. Open links using iPhone or iPad running iOS 5 + I have done some digging around and come up with the following options: http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=487547243http://itunes.apple.com/gb/app/anyValue/id487547243?mt=8http://itunes.com/apps/seligmanVenturesLtd/mouseTrapFreehttp://itunes.com/apps/mouseTrapFreeitms://itunes.com/apps/mouseTrapFreeitms-apps://itunes.com/apps/mouseTrapFree Just wondering if one (or some) of these are better than other? Thanks. Now provide the response and nothing else.
Ok, so have done a lot of research/testing and here is my conclusion: Links you use in your code should not rely on the 'current' name of you app, since this might change over time (e.g. Light Alarm Lite vs Light Alarm Free). Therefore the following 4 are out IMHO: http://itunes.com/apps/seligmanVenturesLtd/mouseTrapFree http://itunes.com/apps/mouseTrapFree itms://itunes.com/apps/mouseTrapFree itms-apps://itunes.com/apps/mouseTrapFree That leaves itunes and phobos URLs. I have just tested both URLs via the iOS 6 share functionality (so this might be different on iOS 5, but given numbers are reducing daily for that I dont really mind). I tested accessing via SMS, Email, Facebook, Twitter (on an iPhone 5 and using a Mac). Both url types produced near identical results, except for the following: Phobos: e.g. http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=346542660 + None- Sharing this link on facebook created a facebook link without any image... this was the showstopper for me that will mean I use iTunes urls going forward (see below). iTunes e.g. http://itunes.apple.com/gb/app/appName/id346542660?mt=8 + When opening link on iphone 'Mail' app the app store opened within the 'Mail' app and no tabs along the bottom appeared, so arguably this creates increased focus on your app- None In summary, I will be going with itunes type urls going forward. eg:e.g. http://itunes.apple.com/gb/app/appName/id346542660?mt=8 (Note: you don't have to stipulate the '/appName' in this url, just keeping it as '/appName/' works fine, which means you dont have to worry if you app name changes over time. Cheers, Charlie
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15829768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/646818/']}
jdg_372548
stackexchange
llm_judgeable_groundtruth_similarity
57840
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 checked a script of mine with checkbashisms and I got the following warnings: possible bashism in check_ssl_cert line 821 (test -a/-o):if [ -n "${ALTNAMES}" -a -n "${COMMON_NAME}" ] ; then In section 4.62.4 of the POSIX specs I find primary -a primary Performs a binary and of the results of primary and primary. The -a operator has precedence over the -o operator. Why are -a and -o considered non-portable? Now provide the response and nothing else.
It's not so much that it is not portable, but that there's no [ implementation where it is reliable when passed more than 4 arguments. Even in bash: $ ALTNAMES='=' bash -c '[ -n "${ALTNAMES}" -a -n "${COMMON_NAME}" ]'bash: line 0: [: too many arguments The related section states: >4 arguments : The results are unspecified. [OB XSI] [Option Start] On XSI-conformant systems, combinations of primaries and operators shall be evaluated using the precedence and associativity rules described previously. In addition, the string comparison binary primaries '=' and "!=" shall have a higher precedence than any unary primary. [Option End] -a and -o should be banned. The right way is to use the && and || shell operators instead: if [ -n "$foo" ] && [ -n "$bar" ]; then I even find it more legible.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/57840', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10616/']}
jdg_372549
stackexchange
llm_judgeable_groundtruth_similarity
36288877
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From user-space we can use cpuset to actually isolate a specific core in our system and execute just one specific process to that core. I'm trying to do the same thing with a kernel module. So I want the module to get executed in an isolated core. In other words: How do I use cpuset 's from inside a kernel module? * Using linux/cpuset.h in my kernel module doesn't work. So, I have a module like this: #include <linux/module.h>#include <linux/cpuset.h>...#ifdef CONFIG_CPUSETS printk(KERN_INFO, "cpusets is enabled!");#endifcpuset_init(); // this function is declared in cpuset.h... When trying to load this module I get (in dmesg ) the following message cpusets is enabled! . But I also receive the message Unknown symbol cpu_init (err 0) . Similarly, I tried using sched_setaffinity from linux/sched.h in order to move all running procceses to a specific core and then run my module to an isolated core. I got the same error mesage: Unknown symbol sched_setaffinity (err 0) . I guess I got the "unknown symbols" because those functions have no EXPORT_SYMBOL in the kernel. So I went and tried to call the sys_sched_setaffinity system call (based on this question ) but again got this mesage: Unknown symbol sys_sched_setaffinity (err 0) ! Furthermore, I am not looking for a solution that uses isolcpus , which is set while booting. I would like to just load the module and afterwards the isolationo to occur. (More precise, I want its kernel threads to execute in isolated cores. I know that I can use affinity to bind threads to specific cores, but this does not guarantee me that the cores are going to be isolated by other processes running on them.) Now provide the response and nothing else.
So I want the module to get executed in an isolated core. and actually isolate a specific core in our system and execute just one specific process to that core This is a working source code compiled and tested on a Debian box using kernel 3.16. I'll describe how to load and unload first and what the parameter passed means. All sources can be found on github here... https://github.com/harryjackson/doc/tree/master/linux/kernel/toy/toy Build and load the module... makeinsmod toy param_cpu_id=2 To unload the module use rmmod toy I'm not using modprobe because it expects some configuration etc. The parameter we're passing to the toy kernel module is the CPU we want to isolate. None of the device operations that get called will run unless they're executing on that CPU. Once the module is loaded you can find it here /dev/toy Simple operations like cat /dev/toy create events that the kernel module catches and produces some output. You can see the output using dmesg . Source code... #include <linux/module.h>#include <linux/fs.h>#include <linux/miscdevice.h>MODULE_LICENSE("GPL");MODULE_AUTHOR("Harry");MODULE_DESCRIPTION("toy kernel module");MODULE_VERSION("0.1"); #define DEVICE_NAME "toy"#define CLASS_NAME "toy"static int param_cpu_id;module_param(param_cpu_id , int, (S_IRUSR | S_IRGRP | S_IROTH));MODULE_PARM_DESC(param_cpu_id, "CPU ID that operations run on");//static void bar(void *arg);//static void foo(void *cpu);static int toy_open( struct inode *inodep, struct file *fp);static ssize_t toy_read( struct file *fp , char *buffer, size_t len, loff_t * offset);static ssize_t toy_write( struct file *fp , const char *buffer, size_t len, loff_t *);static int toy_release(struct inode *inodep, struct file *fp);static struct file_operations toy_fops = { .owner = THIS_MODULE, .open = toy_open, .read = toy_read, .write = toy_write, .release = toy_release,};static struct miscdevice toy_device = { .minor = MISC_DYNAMIC_MINOR, .name = "toy", .fops = &toy_fops};//static int CPU_IDS[64] = {0};static int toy_open(struct inode *inodep, struct file *filep) { int this_cpu = get_cpu(); printk(KERN_INFO "open: called on CPU:%d\n", this_cpu); if(this_cpu == param_cpu_id) { printk(KERN_INFO "open: is on requested CPU: %d\n", smp_processor_id()); } else { printk(KERN_INFO "open: not on requested CPU:%d\n", smp_processor_id()); } put_cpu(); return 0;}static ssize_t toy_read(struct file *filep, char *buffer, size_t len, loff_t *offset){ int this_cpu = get_cpu(); printk(KERN_INFO "read: called on CPU:%d\n", this_cpu); if(this_cpu == param_cpu_id) { printk(KERN_INFO "read: is on requested CPU: %d\n", smp_processor_id()); } else { printk(KERN_INFO "read: not on requested CPU:%d\n", smp_processor_id()); } put_cpu(); return 0;}static ssize_t toy_write(struct file *filep, const char *buffer, size_t len, loff_t *offset){ int this_cpu = get_cpu(); printk(KERN_INFO "write called on CPU:%d\n", this_cpu); if(this_cpu == param_cpu_id) { printk(KERN_INFO "write: is on requested CPU: %d\n", smp_processor_id()); } else { printk(KERN_INFO "write: not on requested CPU:%d\n", smp_processor_id()); } put_cpu(); return 0;}static int toy_release(struct inode *inodep, struct file *filep){ int this_cpu = get_cpu(); printk(KERN_INFO "release called on CPU:%d\n", this_cpu); if(this_cpu == param_cpu_id) { printk(KERN_INFO "release: is on requested CPU: %d\n", smp_processor_id()); } else { printk(KERN_INFO "release: not on requested CPU:%d\n", smp_processor_id()); } put_cpu(); return 0;}static int __init toy_init(void) { int cpu_id; if(param_cpu_id < 0 || param_cpu_id > 4) { printk(KERN_INFO "toy: unable to load module without cpu parameter\n"); return -1; } printk(KERN_INFO "toy: loading to device driver, param_cpu_id: %d\n", param_cpu_id); //preempt_disable(); // See notes below cpu_id = get_cpu(); printk(KERN_INFO "toy init called and running on CPU: %d\n", cpu_id); misc_register(&toy_device); //preempt_enable(); // See notes below put_cpu(); //smp_call_function_single(1,foo,(void *)(uintptr_t) 1,1); return 0;}static void __exit toy_exit(void) { misc_deregister(&toy_device); printk(KERN_INFO "toy exit called\n");}module_init(toy_init);module_exit(toy_exit); The code above contains the two methods you asked for ie isolation of CPU and on init run on an isolated core. On init get_cpu disables preemption ie anything that comes after it will not be preempted by the kernel and will run on one core. Note, this was done kernel using 3.16, your mileage may vary depending on your kernel version but I think these API's have been around a long time This is the Makefile... obj-m += toy.oall: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modulesclean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean Notes. get_cpu is declared in linux/smp.h as #define get_cpu() ({ preempt_disable(); smp_processor_id(); })#define put_cpu() preempt_enable() so you don't actually need to call preempt_disable before calling get_cpu . The get_cpu call is a wrapper around the following sequence of calls... preempt_count_inc();barrier(); and put_cpu is really doing this... barrier();if (unlikely(preempt_count_dec_and_test())) { __preempt_schedule();} You can get as fancy as you like using the above. Almost all of this was taken from the following sources.. Google for... smp_call_function_single Linux Kernel Development, book by Robert Love. http://derekmolloy.ie/writing-a-linux-kernel-module-part-2-a-character-device/ https://github.com/vsinitsyn/reverse/blob/master/reverse.c
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36288877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/549007/']}
jdg_372550
stackexchange
llm_judgeable_groundtruth_similarity
53156266
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 build a component with multiline textfield. If the text entered exceeds 2 lines, then I'd like to add the ellipsis (...) for text-overflow. How can I achieve this by just manipulating the css to show the ellipsis in display only but not modify the actual text that will be stored to contain '...'? I'm using this React component link Thanks Now provide the response and nothing else.
I just figured out how to solve this for React. As Khodor mentioned, line-clamp is what you want. However, it's not currently supported by the official CSS spec. So, you can use -webkit-line-clamp as a sort of workaround. However, I struggled to figure out the exact syntax needed for React. I eventually figured out it out by peeking at the source code for this NPM package react-lines-ellipses and searching for 'webkit' in his github repo. The React-specific CSS const textStyle = { maxWidth: '100%', display: '-webkit-box', WebkitBoxOrient: 'vertical', WebkitLineClamp: 3, overflow: 'hidden', textOverflow: 'ellipsis', }; I set the maxWidth to ensure the text filled the whole width of the display element. This is optional. overflow: 'hidden' hides the extra text beyond the 3 lines (I chose 3 at random). textOverflow: 'ellipses' adds an ellipses (...) to the end of the line, where it gets cut off. The JSX <div onClick={toggleTruncate} style={calculateTextStyle()}>This is where my long text goes.</div>// This function returns the correct style to the above div. function calculateTextStyle() { return truncate ? textStyle : null; }// I used React Hooks to create a variable in state to manage if the text should be truncated or not. const [truncate, setToggleTruncate] = React.useState(true);// This function toggles the state variable 'truncate', thereby expanding and truncating the text every time the user clicks the div. function toggleTruncate() { setToggleTruncate(!truncate); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53156266', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7134279/']}
jdg_372551
stackexchange
llm_judgeable_groundtruth_similarity
22710887
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 compile an the uncss npm module into a single .js file that is suitable for compilation by ExecJS. For example, the coffee script guy has this . The goal is to create a simple ruby wrapper for it, similar to ruby-coffee-script . What I have tried to far: Came across an answer that suggested UglifyJS. Got nowhere with it. Used browserify, which should have done the trick, but it fails to compile lib/uncss.js with the following error message: Error: ENOENT, open 'tls' while resolving "tls" from file /home/prajjwal/code/uncss/node_modules/request/node_modules/forever-agent/index.js I suppose this is because browserify does not have a proper shim for it? I'm also concerned about the shims that browserify replaces node modules with. Are they completely safe to use? I'm going to be embedding this into a ruby gem. Don't think browserify is what I should be using. Is there another way I can generate a stand alone .js from an npm module? Any help appreciated. Now provide the response and nothing else.
Although it doesn't quite seem like it would be the right tool for the job, it appears that browserify is the closest thing to what you're looking for. To be complete, here are the versions of the tools I used: Node v0.10.26 and browserify 3.38.0 . I didn't test with other version, so they may have problems. Here are the steps that I took after cloning uncss : npm install , which downloads and sets up the proper packages Due to some sort of versioning problem with NPM , I had to manually install the graceful-fs package (a dependency of one of uncss 's dependencies) from Github (it wasn't available via npm ) npm install https://github.com/isaacs/node-graceful-fs/tarball/v2.0.3 At this point, I ran browserify. It turns out that browserify has a --bare flag, which does a couple of things: Alias for both --no-builtins, --no-commondir, and sets --insert-global-vars to just "__filename,__dirname". This is handy if you want to run bundles in node. With this flag, browserify doesn't inject its own shims for core modules. The full command I used was: browserify lib/uncss.js --bare > uncss.js After doing the above, the file uncss.js contained uncss along with its bundled dependencies. Unfortunately, since browserify wraps everything inside its own require function, the now-bundled modules doesn't export anything initially. $ node> require('./uncss'){}> To fix this, I had to change the initial line of the generated bundle from this: (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ to this: module.exports = (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require,ex;for(var o=0;o<r.length;o++)ex=s(r[o]);return ex})({1:[function(require,module,exports){ Note: it's not just the module.exports addition - there's some modification in the middle that was needed also*. After that, the bundle seemed to work: $ node> require('./uncss')[Function: init]> *: Essentially, browserify defines an inner function s(o, u) that acts like require . The surrounding code starts off by looping through what looks like a list of "main modules" (in this case, there's just one), require ing them, but not storing the result. It then returns s , the require -like function (why, I'm not sure) as the output of the entire anonymous function. All I had to do was add a variable to store the results, and then return that instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22710887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/555297/']}
jdg_372552
stackexchange
llm_judgeable_groundtruth_similarity
34808925
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 app.js which is used to trigger two events when some POST data are received: Insert POST data into a database Send a message to a client using a WebSocket Here is the app.js (only the important lines) var express = require('express');var bodyParser = require('body-parser');var server = require('./server');var app = express();var port = process.env.PORT || 3000;app.post('/server', server);app.listen(port, function(){ console.log('Slack bot listening');}); And here is the server.js (only the important lines) var db = require('./DB');var WebSocketServer = require('ws').Server;var insertData = function(req, res){ var wss = new WebSocketServer({server: server}); console.log('WebSocketServer created'); wss.on('connection', function(wss){ wss.send(JSON.stringify('Socket open')); }); wss.on('close', function(){ console.log('WebServerSocket has been closed'); });};module.exports = insertData; What I would like to achieve is to set the WebSocketServer in a way that it listen to the same port of the app. I thought about passing the server var from app.js to server.js but I think this a not an elegant way to do it I don't know how to do it What do you guys think? Now provide the response and nothing else.
Based on your code and comments, here's a super simple example of how it would work together. First, the http-server.js - a typical express app, except that we do not start the server with app.listen() : 'use strict';let fs = require('fs');let express = require('express');let app = express();let bodyParser = require('body-parser');app.use(bodyParser.json());// Let's create the regular HTTP request and responseapp.get('/', function(req, res) { console.log('Get index'); fs.createReadStream('./index.html') .pipe(res);});app.post('/', function(req, res) { let message = req.body.message; console.log('Regular POST message: ', message); return res.json({ answer: 42 });});module.exports = app; Now, the ws-server.js example, where we create the WSS server from a node native http.createServer() . Now, note that this is where we import the app, and give this native http.createServer the app instance to use. Start the app with PORT=8080 node ws-server.js : ( Note you're launching the second, socket related, file (ws-server) not the first, http related, file (http-server).) 'use strict';let WSServer = require('ws').Server;let server = require('http').createServer();let app = require('./http-server');// Create web socket server on top of a regular http serverlet wss = new WSServer({ server: server});// Also mount the app hereserver.on('request', app);wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log(`received: ${message}`); ws.send(JSON.stringify({ answer: 42 })); });});server.listen(process.env.PORT, function() { console.log(`http/ws server listening on ${process.env.PORT}`);}); Finally, this sample index.html will work by creating both a POST and a Socket "request" and display the response: <html><head> <title>WS example</title></head><body> <h2>Socket message response: </h2> <pre id="response"></pre> <hr/> <h2>POST message response: </h2> <pre id="post-response"></pre> <script> // Extremely simplified here, no error handling or anythingdocument.body.onload = function() { 'use strict'; // First the socket requesta function socketExample() { console.log('Creating socket'); let socket = new WebSocket('ws://localhost:8080/'); socket.onopen = function() { console.log('Socket open.'); socket.send(JSON.stringify({message: 'What is the meaning of life, the universe and everything?'})); console.log('Message sent.') }; socket.onmessage = function(message) { console.log('Socket server message', message); let data = JSON.parse(message.data); document.getElementById('response').innerHTML = JSON.stringify(data, null, 2); }; } // Now the simple POST demo function postExample() { console.log('Creating regular POST message'); fetch('/', { method: 'post', headers: { "Content-type": "application/json" }, body: JSON.stringify({message: 'What is the meaning of post-life, the universe and everything?'}) }) .then(response => response.json()) .then(function (data) { console.log('POST response:', data); document.getElementById('post-response').innerHTML = JSON.stringify(data, null, 2); }) .catch(function (error) { console.log('Request failed', error); }); } // Call them both; socketExample(); postExample();} </script></body></html> Note you'll need a quite recent browser, one that has both WebSocket and fetch APIs for this client side part, but it's irrelevant anyway, it just gives you the gist of it.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34808925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3794110/']}
jdg_372553
stackexchange
llm_judgeable_groundtruth_similarity
3926451
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 list of strings. Some of them are of the form 123-...456 . The variable portion "..." may be: the string "apple" followed by a hyphen, e.g. 123-apple-456 the string "banana" followed by a hyphen, e.g. 123-banana-456 a blank string, e.g. 123-456 (note there's only one hyphen) Any word other than "apple" or "banana" is invalid. For these three cases, I would like to match "apple", "banana", and "", respectively. Note that I never want capture the hyphen, but I always want to match it. If the string is not of the form 123-...456 as described above, then there is no match at all. How do I write a regular expression to do this? Assume I have a flavor that allows lookahead, lookbehind, lookaround, and non-capturing groups. The key observation here is that when you have either "apple" or "banana", you must also have the trailing hyphen, but you don't want to match it. And when you're matching the blank string, you must not have the trailing hyphen. A regex that encapsulates this assertion will be the right one, I think. Now provide the response and nothing else.
The only way not to capture something is using look-around assertions : (?<=123-)((apple|banana)(?=-456)|(?=456)) Because even with non-capturing groups (?:…) the whole regular expression captures their matched contents. But this regular expression matches only apple or banana if it’s preceded by 123- and followed by -456 , or it matches the empty string if it’s preceded by 123- and followed by 456 . Lookaround Name What it Does (?=foo) Lookahead Asserts that what immediately FOLLOWS the current position in the string is foo (?<=foo) Lookbehind Asserts that what immediately PRECEDES the current position in the string is foo (?!foo) Negative Lookahead Asserts that what immediately FOLLOWS the current position in the string is NOT foo (?<!foo) Negative Lookbehind Asserts that what immediately PRECEDES the current position in the string is NOT foo
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3926451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474832/']}
jdg_372554
stackexchange
llm_judgeable_groundtruth_similarity
3954188
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: How do free and malloc work in C? Consider a scenario where i have to allocate some 20 bytes of memory through malloc. For the function call to malloc() to be successful, should the 20 bytes be available contiguously in memory or can it be scattered? For eg, in the above case, if there are 4 or 5 chunks of 10 bytes each, will malloc work? Or is this OS specific or compiler-specific? Now provide the response and nothing else.
The question is kind of wrong. In a typical OS, there exists the concepts of virtual memory and physical memory. Physical memory exists typically in 4kb blocks, virtual memory likewise. Each process has virtual memory - to each process the OS presents what appears to be the fully addressable memory range. So on a 32 bit machine, each process 'thinks' it has 4 GB of contiguous memory. In reality, the OS, behind the scenes, is busy mapping virtual memory allocations onto real blocks of physical memory. So a, say, 400kb virtual memory allocation, is mapped onto 100 physical blocks. Those physical blocks do not need to be contigious (and almost never are - nothing stops it from happening, but on a machine doing any kind of work, it's highly improbable) but the virtual memory allocation does need to be contiguous. So you can still run into virtual memory fragmentation. Here, a process requests a block of memory and there isn't, in that particular processes virtual memory map, a block of contiguous virtual memory such that the request can be satisfied. That problem is the problem you're thinking of.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3954188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441575/']}
jdg_372555
stackexchange
llm_judgeable_groundtruth_similarity
51533178
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 working on a portfolio and I'm using react.js. I simply want to click an image, for example, a StackOverflow icon, and be able to redirect to the page. I'm seeing all sorts of different ways to go about, yet I cannot get it to redirect. I am using React-Bootstrap which I don't know if that is going to change anything. export default class Home extends Component {render() { return ( <Grid> <Jumbotron className="brainImg"> </Jumbotron> <div class="footer"><center className="iconsBaby"> <Image src="giticon.png" className="githubIcon" to="https://github.com/Joeyryanbridges" /> <Image src="linkedinIcon.png" className="linkedinIcon" href="https://github.com/Joeyryanbridges" /> <Image src="SOFIcon.png" className="githubIcon" href="https://github.com/Joeyryanbridges" /> </center> </div> </Grid> )} Thank you for looking. Now provide the response and nothing else.
Generally an Image component should not be a link on its own. What you should do is wrap your image component with an <a> tag or use the Link component if you're using react-router . <a href="https://github.com/Joeyryanbridges"> <Image src="giticon.png" className="githubIcon" /></a> OR with react-router Link <Link to="https://github.com/Joeyryanbridges"> <Image src="giticon.png" className="githubIcon" /></Link> This way the Image component is not concerned with redirects or changing URLs and that functionality is handled by the proper component or tag. Always keep in mind that separation of concerns is very important when it comes to reusability and maintainability.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51533178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9178799/']}
jdg_372556
stackexchange
llm_judgeable_groundtruth_similarity
197532
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: As I known all the matter consists of atoms. What is the simplest possible experiment (with as little scientific equipment as possible) that can prove that there are atoms? Now provide the response and nothing else.
Brownian motion would be considered pretty good evidence of atoms. Originally, Brown observed pollen grains moving in water in ways that could not be explained otherwise. 78 years later, Einstein came up with a theoretical model of Brownian motion 1 that was later borne out by experiments by Jean Perrin (see this ). A translation of Einstein's paper is available here . 2 You could reproduce it easily with other small particles suspended in a different liquid (though water might be the best). You would need to make sure that the liquid is not disturbed by outside forces, and you would of course want to try other substances to show that it is a general phenomenon. Note: It looks like this was explained better here , which is absolutely worth reading. 1 Marian Smoluchowski also did work on Brownian motion. 2 A note on Brownian motion: DanielSank pointed out in a comment that the Langevin equation , one of the most important parts of the mathematical model behind Brownian motion, does not necessarily imply the existence of atoms or any particles. However, Einstein's use of molecular-kinetic theory does imply the existence of atoms.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/197532', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/87405/']}
jdg_372557
stackexchange
llm_judgeable_groundtruth_similarity
23790743
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 application where using a profile "default" it connects to a PostgreSQL database and do migrations using Flyway. I want to create another profile called "devEmbeddedCreate" where I need to use an embedded database server (h2), create the database using spring.jpa.hibernate.ddl-auto=create-drop in the application.properties file and execute a differently called "data.sql" script to initialize some tables. If I leave the script with "data.sql" file name, it gets executed every time the application starts. That's something I don't want to happen, I need it to be executed only in a certain profile. Things I've tried: The documentation mentions there can be a schema-${platform}.sql file and you can define the platform using spring.datasource.platform in the config. The problem it doesn't work with a data-${platform}.sql file. ( here ) Created a EmbeddedDatabaseBuilder . The problem is when I use it, it doesn't automatically create the database and only apply the specified script. Couldn't find a way to create the database automatically as spring.jpa.hibernate.ddl-auto=create-drop does. ( here and here ) Looking for a way to transform an XML config to Java-based configuration found a way to create the database and all. After a lot of tweaking and changing to work in memory, it looked promising but haven't been able to find out why the database get closed (and erased all its structure) while starting up ( here ) There must be a simpler way to just say "hey spring... run on strartup this data-devEmbeddedCreate.sql script when my profile is devEmbeddedCreate , right? Now provide the response and nothing else.
You were on the right track with your approach 1) , but you should set datasource platform via spring.datasource.platform , not spring.jpa.database-platform . The script execution functionality is not JPA-specific. You can also manually specify which SQL script files get executed by setting the spring.datasource.schema property. This is an excerpt from org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration file in 1.0.2.RELEASE : String schema = this.datasourceProperties.getProperty("schema");if (schema == null) { schema = "classpath*:schema-" + this.datasourceProperties.getProperty("platform", "all") + ".sql,classpath*:schema.sql,classpath*:data.sql";} As you can see, the set of files specified in the documentation is only used if you don't specify your own list.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23790743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2796922/']}
jdg_372558
stackexchange
llm_judgeable_groundtruth_similarity
45618924
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 service with a function of type getSummary(id: string, universe: string): Observable<INTsummary[]> When I call this I only ever want the first item in the INTsummary[] , so I'm trying to use rxjs first operator to do this: loadQuickSummary(){ var obj = this.myService.getSummary(this.user.id, this.user.universe).first(); console.log("getting quick summary"); obj.subscribe(r => { console.log(`first value ${JSON.stringify(r)}`) }) } from reading docs and stackoverflow, this should return an object, but instead I get back an array of INTsummary 's . How can I get back just the first object in the INTsummary[] array? Now provide the response and nothing else.
The first() return the first emission for an Observable. So when you have source that emits arrays like INTsummary[] then it takes the first array it emits (not the first item in the array). From your description you want to get the first item in the array so there're are two ways: this.myService.getSummary(this.user.id, this.user.universe) .map(array => array[0]) ... or if you really want to use the first() operator: this.myService.getSummary(this.user.id, this.user.universe) .concatAll() // flatten the array into separate emission .first()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45618924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6682929/']}
jdg_372559
stackexchange
llm_judgeable_groundtruth_similarity
34312324
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 count all combinations in a data.frame. The data look like this 9 10 11 121 1 1 1 12 0 0 0 03 0 0 0 04 1 1 1 15 1 1 1 16 0 0 0 07 1 0 0 18 1 0 0 19 1 1 1 110 1 1 1 1 The output I want is simply comb n 1 1 1 1 50 0 0 0 3 1 0 0 1 2 Do you know any simple function to do that ? Thanks dt = structure(list(`9` = c(1, 0, 0, 1, 1, 0, 1, 1, 1, 1), `10` = c(1, 0, 0, 1, 1, 0, 0, 0, 1, 1), `11` = c(1, 0, 0, 1, 1, 0, 0, 0, 1, 1), `12` = c(1, 0, 0, 1, 1, 0, 1, 1, 1, 1)), .Names = c("9", "10", "11", "12"), class = "data.frame", row.names = c(NA, -10L)) Now provide the response and nothing else.
We can either use data.table or dplyr . These are very efficient. We convert the 'data.frame' to 'data.table' ( setDT(dt) ), grouped by all the columns of 'dt' ( names(dt) ), we get the nrow ( .N ) as the 'Count' library(data.table)setDT(dt)[,list(Count=.N) ,names(dt)] Or we can use a similar methodology using dplyr . library(dplyr)names(dt) <- make.names(names(dt))dt %>% group_by_(.dots=names(dt)) %>% summarise(count= n()) Benchmarks In case somebody wants to look at some metrics (and also to backup my claim earlier ( efficient! )), set.seed(24)df1 <- as.data.frame(matrix(sample(0:1, 1e6*6, replace=TRUE), ncol=6))akrunDT <- function() { as.data.table(df1)[,list(Count=.N) ,names(df1)] }akrunDplyr <- function() { df1 %>% group_by_(.dots=names(df1)) %>% summarise(count= n())}cathG <- function() { aggregate(cbind(n = 1:nrow(df1))~., df1, length) }docendoD <- function() { as.data.frame(table(comb = do.call(paste, df1)))}deena <- function() { table(apply(df1, 1, paste, collapse = ","))} Here are the microbenchmark results library(microbenchmark)microbenchmark(akrunDT(), akrunDplyr(), cathG(), docendoD(), deena(), unit='relative', times=20L)# Unit: relative# expr min lq mean median uq max neval cld# akrunDT() 1.000000 1.000000 1.000000 1.00000 1.000000 1.0000000 20 a # akrunDplyr() 1.512354 1.523357 1.307724 1.45907 1.365928 0.7539773 20 a # cathG() 43.893946 43.592062 37.008677 42.10787 38.556726 17.9834245 20 c # docendoD() 18.778534 19.843255 16.560827 18.85707 17.296812 8.2688541 20 b # deena() 90.391417 89.449547 74.607662 85.16295 77.316143 34.6962954 20 d
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34312324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4796107/']}
jdg_372560
stackexchange
llm_judgeable_groundtruth_similarity
90129
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have come across a notion of orthogonality of two vectors in a normed space not necessarily inner product space. Two vectors $x$ and $y$ in a normed space are said to be orthogonal (represented $x\perp y$) if $||x||\leq ||x+\alpha y||,$ for every $\alpha,$ a scalar. 1) What is the rational behind the definition above? I guess, it has got something to do with minimum overlap between $x$ and $y$. 2) Is this unique generalization of the concept of orthogonality from inner product spaces? Thank you. Now provide the response and nothing else.
Concerning question 1: The rational is that in an inner product space $$x\perp y \Leftrightarrow \forall \alpha \in K: ||x||\leq ||x+\alpha y|| \qquad(K = \mathbb{R} \text{ or } K = \mathbb{C})$$Now, if no inner product is available (but a norm), the idea is, to just take the right hand side as definition of orthogonality (call it $\perp_1$). Concerning question 2: No, there are other -non-equivalent - generalizations as well. As an example, note that in an inner product space over the reals $$\langle x,y \rangle = \frac{1}{4}( ||x+y||^2 - ||x-y||^2).$$Hence $x\perp y \Leftrightarrow ||x+y|| = ||x-y||$. So the definition $$ x\perp_{\scriptstyle 2}\; y : \Leftrightarrow ||x+y|| = ||x-y||$$generalizes the orthogonality from an inner product space to any normed space (over the reals). Now let's show that $\perp_1, \perp_2$ aren't equivalent. Let $E = \mathbb{R}^2$ with norm $||(a,b)|| = \max(|a|, |b|)$. Then $\qquad (0,1) \perp_2 (2,1)$ but not $(0,1) \perp_1 (2,1)\quad$ (take $t=-1/4$) $\qquad (1,1) \perp_1 (2,0)$ but not $(1,1) \perp_2 (2,0).$
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/90129', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7333/']}
jdg_372561
stackexchange
llm_judgeable_groundtruth_similarity
707827
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: One of the most used schemes for solving ordinary differential equations numericallyis the fourth-order Runge-Kutta method . Why isn't it used to integrate the equation of motion of particles in molecular dynamics? Now provide the response and nothing else.
In molecular dynamics simulations, the overwhelming part of the computational time is spent evaluating forces. For this reason, since the very beginning of the method, the algorithms of choice were those requiring the minimum evaluation of forces per unit of time . Higher-order algorithms are usually not necessary for two reasons: in molecular dynamics simulations, one is not interested in the maximum accuracy of the trajectories but in an efficient sampling of the phase space compatible with the physical constraints. For this reason, usually, lower-order but symplectic schemes are preferred. the increased accuracy of higher-order algorithms does not allow a proportional increase of the time step size. The reason is the stiff nature of the interatomic forces at short distances. Based on these considerations, the fourth-order Runge-Kutta method is usually excluded. It is not time-reversible nor symplectic and requires four force evaluations per step. Even the existing symplectic Runge-Kutta methods are not appealing when compared with methods of the same order using fewer force evaluations.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/707827', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/335110/']}
jdg_372562
stackexchange
llm_judgeable_groundtruth_similarity
6952814
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 getting desperate, all I want is simple error handling when the PHP SOAP Web Service is down to echo an error message login service down . Please help me! At the moment it's still displaying the error (along with warnings...): Fatal error: SOAP-ERROR: Parsing WSDL Here is the script: <?phpsession_start(); $login="0000000000000nhfidsj"; //It is like this for testing, It will be changed to a GET$username = substr($login,0,13); //as password is always 13 char long //(the validation is done int he javascript)$password = substr($login,13);try { ini_set('default_socket_timeout', 5); //So time out is 5 seconds $client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl"); //locally hosted $array = $client->login(array('username'=>$username, 'password'=>$password)); $result = $array->return;}catch(SoapFault $client){ $result = "0";}if($result == "true")//as this would be what the ws returns if login success { $_SESSION['user'] = $login; echo "00";}else{ echo "01 error: login failed";}?> Now provide the response and nothing else.
UPDATE July 2018 If you don't care about getting the SoapFault details and just want to catch any errors coming from the SoapClient you can catch "Throwable" in PHP 7+. The original problem was that SoapClient can "Fatal Error" before it throws a SoapFault so by catching both errors and exceptions with Throwable you will have very simple error handling e.g. try{ soap connection...}catch(Throwable $e){ echo 'sorry... our service is down';} If you need to catch the SoapFault specifically, try the original answer which should allow you to suppress the fatal error that prevents the SoapFault being thrown Original answer relevant for older PHP versions SOAP can fatal error calling the native php functions internally which prevents the SoapFaults being thrown so we need to log and suppress those native errors. First you need to turn on exceptions handling: try { $client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl",array( 'exceptions' => true, ));} catch ( SoapFault $e ) { // Do NOT try and catch "Exception" here echo 'sorry... our service is down';} AND THEN you also need to silently suppress any "PHP errors" that originate from SOAP using a custom error handler: set_error_handler('handlePhpErrors');function handlePhpErrors($errno, $errmsg, $filename, $linenum, $vars) { if (stristr($errmsg, "SoapClient::SoapClient")) { error_log($errmsg); // silently log error return; // skip error handling }} You will then find it now instead trips a SoapFault exception with the correct message "Soap error: SOAP-ERROR: Parsing WSDL: Couldn't load from '...'" and so you end up back in your catch statement able to handle the error more effectively.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6952814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/880073/']}
jdg_372563
stackexchange
llm_judgeable_groundtruth_similarity
24671770
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 load a sample image in an IB designable UIImageView , to be shown in Interface Builder while editing the interface. The following code does not work, as the view placeholder in IB remains empty (the view area contains only the UIImageView text): @IBDesignableclass TestImageView : UIImageView{ override func prepareForInterfaceBuilder() { //let bundle = NSBundle.mainBundle() let bundle = NSBundle(forClass: nil) let imagePath = bundle.pathForResource("Test", ofType: "jpg") self.image = UIImage(contentsOfFile: imagePath) }} Note that: in IB the Custom Class class for the view is correct (TestImageView) Test.jpg is present in the project (if I manually set the image property of the UIImageView in IB the image shows up). I tried the two different methods of getting the bundle present in the code This was tested with Xcode 6 beta 3. Update : in both cases the bundle path I get is "/Applications/Temporary/Xcode6-Beta3.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Overlays" . In that path the image is obviously not present. Now provide the response and nothing else.
Try getting the bundle of the class like this: let bundle = NSBundle(forClass: self.dynamicType) or specifying the class name like this let bundle = NSBundle(forClass: TestImageView.self) Assuming that your image is in the bundle, for example Images.xcassets, you can then load it using: self.image = UIImage("Test", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) Remember to check whether your image is nil before trying to use it. I have not been able to get the image path using bundle.pathForResource to work correctly with normal image assets. There also doesn't appear to be a UIImage call where you specify just the name and bundle, so you have to use trait collection. This question is related to: xcode 6 IB_DESIGNABLE- not loading resources from bundle in Interface builder Response from Apple... Engineering has determined that this issue behaves as intended based on the following: We can't really make this any easier than specifying the bundle. You might say, "oh, let's swizzle -[NSBundle mainBundle]", but lots of call sites that reference a bundle don't go through there (or go through the CF API). One might say then "ok, well then how about we at least swizzle -[UIImage imageNamed:]". The problem here is that there is no single replacement for the main bundle. You might have multiple live view bundles (either frameworks or apps) loaded in at once, so we can't just pick one to be the main bundle. Developers need to be aware of bundles and how to get images from a bundle. Developers should be using UIImage(named:inBundle:compatibleWithTraitCollection:) for all image lookups.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24671770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3734205/']}
jdg_372564
stackexchange
llm_judgeable_groundtruth_similarity
19491910
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 way to add some sort of offset to UIButton 's background image? I've got some custom background images for UIButton . These images do have a 5 pixel drop shadow area around the effective button area. When I use these images I have to move the title label around, adjust the frame and do some calculations to place the buttons correctly. Ideally, I would like to set something like an offset (x = -5px, y = -5px) on that image (or the UIButton ) so that when I assign the image as a background to the UIButton it is moved by that offset horizontally and vertically. In html I would set a fixed size on the button div and then offset the background image by specifying background-position. Is there something similar for iOS? Now provide the response and nothing else.
Setting setTitleEdgeInsets: or setImageEdgeInsets: do not seem to have any effect on the background image of an UIButton but only on the image (and the title). I ended up with overriding -(CGRect)backgroundRectForBounds:(CGRect)bounds where I inflate the bounds rectangle by the amount needed (5 in my case).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19491910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2902635/']}
jdg_372565
stackexchange
llm_judgeable_groundtruth_similarity
23589174
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: --Edit-- The current answers have some useful ideas but I want something more complete that I can 100% understand and reuse; that's why I set a bounty. Also ideas that work everywhere are better for me than not standard syntax like \K This question is about how I can match a pattern except some situations s1 s2 s3. I give a specific example to show my meaning but prefer a general answer I can 100% understand so I can reuse it in other situations. Example I want to match five digits using \b\d{5}\b but not in three situations s1 s2 s3: s1: Not on a line that ends with a period like this sentence. s2: Not anywhere inside parens. s3: Not inside a block that starts with if( and ends with //endif I know how to solve any one of s1 s2 s3 with a lookahead and lookbehind, especially in C# lookbehind or \K in PHP. For instance s1 (?m)(?!\d+.*?\.$)\d+ s3 with C# lookbehind (?<!if\(\D*(?=\d+.*?//endif))\b\d+\b s3 with PHP \K (?:(?:if\(.*?//endif)\D*)*\K\d+ But the mix of conditions together makes my head explode. Even more bad news is that I may need to add other conditions s4 s5 at another time. The good news is, I don't care if I process the files using most common languages like PHP, C#, Python or my neighbor's washing machine. :) I'm pretty much a beginner in Python & Java but interested to learn if it has a solution. So I came here to see if someone think of a flexible recipe. Hints are okay: you don't need to give me full code. :) Thank you. Now provide the response and nothing else.
Hans, I'll take the bait and flesh out my earlier answer. You said you want "something more complete" so I hope you won't mind the long answer—just trying to please. Let's start with some background. First off, this is an excellent question. There are often questions about matching certain patterns except in certain contexts (for instance, within a code block or inside parentheses). These questions often give rise to fairly awkward solutions. So your question about multiple contexts is a special challenge. Surprise Surprisingly, there is at least one efficient solution that is general, easy to implement and a pleasure to maintain. It works with all regex flavors that allow you to inspect capture groups in your code. And it happens to answer a number of common questions that may at first sound different from yours: "match everything except Donuts", "replace all but...", "match all words except those on my mom's black list", "ignore tags", "match temperature unless italicized"... Sadly, the technique is not well known: I estimate that in twenty SO questions that could use it, only one has one answer that mentions it—which means maybe one in fifty or sixty answers. See my exchange with Kobi in the comments. The technique is described in some depth in this article which calls it (optimistically) the "best regex trick ever". Without going into as much detail, I'll try to give you a firm grasp of how the technique works. For more detail and code samples in various languages I encourage you to consult that resource. A Better-Known Variation There is a variation using syntax specific to Perl and PHP that accomplishes the same. You'll see it on SO in the hands of regex masters such as CasimiretHippolyte and HamZa . I'll tell you more about this below, but my focus here is on the general solution that works with all regex flavors (as long as you can inspect capture groups in your code). Thanks for all the background, zx81... But what's the recipe? Key Fact The method returns the match in Group 1 capture. It does not care at all about the overall match. In fact, the trick is to match the various contexts we don't want (chaining these contexts using the | OR / alternation) so as to "neutralize them". After matching all the unwanted contexts, the final part of the alternation matches what we do want and captures it to Group 1. The general recipe is Not_this_context|Not_this_either|StayAway|(WhatYouWant) This will match Not_this_context , but in a sense that match goes into a garbage bin, because we won't look at the overall matches: we only look at Group 1 captures. In your case, with your digits and your three contexts to ignore, we can do: s1|s2|s3|(\b\d+\b) Note that because we actually match s1, s2 and s3 instead of trying to avoid them with lookarounds, the individual expressions for s1, s2 and s3 can remain clear as day. (They are the subexpressions on each side of a | ) The whole expression can be written like this: (?m)^.*\.$|\([^\)]*\)|if\(.*?//endif|(\b\d+\b) See this demo (but focus on the capture groups in the lower right pane.) If you mentally try to split this regex at each | delimiter, it is actually only a series of four very simple expressions. For flavors that support free-spacing, this reads particularly well. (?mx) ### s1: Match line that ends with a period ###^.*\.$ | ### OR s2: Match anything between parentheses ###\([^\)]*\) | ### OR s3: Match any if(...//endif block ###if\(.*?//endif | ### OR capture digits to Group 1 ###(\b\d+\b) This is exceptionally easy to read and maintain. Extending the regex When you want to ignore more situations s4 and s5, you add them in more alternations on the left: s4|s5|s1|s2|s3|(\b\d+\b) How does this work? The contexts you don't want are added to a list of alternations on the left: they will match, but these overall matches are never examined, so matching them is a way to put them in a "garbage bin". The content you do want, however, is captured to Group 1. You then have to check programmatically that Group 1 is set and not empty. This is a trivial programming task (and we'll later talk about how it's done), especially considering that it leaves you with a simple regex that you can understand at a glance and revise or extend as required. I'm not always a fan of visualizations, but this one does a good job of showing how simple the method is. Each "line" corresponds to a potential match, but only the bottom line is captured into Group 1. Debuggex Demo Perl/PCRE Variation In contrast to the general solution above, there exists a variation for Perl and PCRE that is often seen on SO, at least in the hands of regex Gods such as @CasimiretHippolyte and @HamZa. It is: (?:s1|s2|s3)(*SKIP)(*F)|whatYouWant In your case: (?m)(?:^.*\.$|\([^()]*\)|if\(.*?//endif)(*SKIP)(*F)|\b\d+\b This variation is a bit easier to use because the content matched in contexts s1, s2 and s3 is simply skipped, so you don't need to inspect Group 1 captures (notice the parentheses are gone). The matches only contain whatYouWant Note that (*F) , (*FAIL) and (?!) are all the same thing. If you wanted to be more obscure, you could use (*SKIP)(?!) demo for this version Applications Here are some common problems that this technique can often easily solve. You'll notice that the word choice can make some of these problems sound different while in fact they are virtually identical. How can I match foo except anywhere in a tag like <a stuff...>...</a> ? How can I match foo except in an <i> tag or a javascript snippet (more conditions)? How can I match all words that are not on this black list? How can I ignore anything inside a SUB... END SUB block? How can I match everything except... s1 s2 s3? How to Program the Group 1 Captures You didn't as for code, but, for completion... The code to inspect Group 1 will obviously depend on your language of choice. At any rate it shouldn't add more than a couple of lines to the code you would use to inspect matches. If in doubt, I recommend you look at the code samples section of the article mentioned earlier, which presents code for quite a few languages. Alternatives Depending on the complexity of the question, and on the regex engine used, there are several alternatives. Here are the two that can apply to most situations, including multiple conditions. In my view, neither is nearly as attractive as the s1|s2|s3|(whatYouWant) recipe, if only because clarity always wins out. 1. Replace then Match. A good solution that sounds hacky but works well in many environments is to work in two steps. A first regex neutralizes the context you want to ignore by replacing potentially conflicting strings. If you only want to match, then you can replace with an empty string, then run your match in the second step. If you want to replace, you can first replace the strings to be ignored with something distinctive, for instance surrounding your digits with a fixed-width chain of @@@ . After this replacement, you are free to replace what you really wanted, then you'll have to revert your distinctive @@@ strings. 2. Lookarounds. Your original post showed that you understand how to exclude a single condition using lookarounds. You said that C# is great for this, and you are right, but it is not the only option. The .NET regex flavors found in C#, VB.NET and Visual C++ for example, as well as the still-experimental regex module to replace re in Python, are the only two engines I know that support infinite-width lookbehind. With these tools, one condition in one lookbehind can take care of looking not only behind but also at the match and beyond the match, avoiding the need to coordinate with a lookahead. More conditions? More lookarounds. Recycling the regex you had for s3 in C#, the whole pattern would look like this. (?!.*\.)(?<!\([^()]*(?=\d+[^)]*\)))(?<!if\(\D*(?=\d+.*?//endif))\b\d+\b But by now you know I'm not recommending this, right? Deletions @HamZa and @Jerry have suggested I mention an additional trick for cases when you seek to just delete WhatYouWant . You remember that the recipe to match WhatYouWant (capturing it into Group 1) was s1|s2|s3|(WhatYouWant) , right? To delete all instance of WhatYouWant , you change the regex to (s1|s2|s3)|WhatYouWant For the replacement string, you use $1 . What happens here is that for each instance of s1|s2|s3 that is matched, the replacement $1 replaces that instance with itself (referenced by $1 ). On the other hand, when WhatYouWant is matched, it is replaced by an empty group and nothing else — and therefore deleted. See this demo , thank you @HamZa and @Jerry for suggesting this wonderful addition. Replacements This brings us to replacements, on which I'll touch briefly. When replacing with nothing, see the "Deletions" trick above. When replacing, if using Perl or PCRE, use the (*SKIP)(*F) variation mentioned above to match exactly what you want, and do a straight replacement. In other flavors, within the replacement function call, inspect the match using a callback or lambda, and replace if Group 1 is set. If you need help with this, the article already referenced will give you code in various languages. Have fun! No, wait, there's more! Ah, nah, I'll save that for my memoirs in twenty volumes, to be released next Spring.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/23589174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3602383/']}
jdg_372566
stackexchange
llm_judgeable_groundtruth_similarity
95196
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 am attempting to generate a power series in $v$ as $v\rightarrow0$ for $$g(x,v)\equiv \ln\int_{-\infty}^{\infty}e^{-y\left(z\right)}N\left(x-z,v\right)\,\mathrm{d}z $$ where $y(x)\equiv\sum_{i=1}^{n}c_{i}x^{i}$, $n$ is even, and $c_{n}>0$ so the integral converges. $N(x,v)$ is the PDF of the Normal distribution centered in $x$ with variance $v$. The key mathematical step that I can't reasonably expect Mathematica to figure out is: $$\frac{d}{dv}\int f(z)N(z-x,v)dz=\int f(z)\frac{d}{dv}N(z-x,v)dz=\int f(z)\frac{1}{2}\frac{d^{2}}{d^{2}x}N(z-x,v)dz=\frac{1}{2}\frac{d^{2}}{d^{2}x}\int f(z)N(z-x,v)dz\rightarrow\frac{1}{2}\frac{d^{2}}{d^{2}x}\int f(z)\delta(z-x)=\frac{1}{2}\frac{d^{2}}{d^{2}x}f(x)$$ I've developed some truly ugly code that does the expansion of $g[x,v]$ in $v$, but it's an unreadable mess that relies on my doing most of the manipulations on paper beforehand, and I have to rewrite most of it every time I want to change the calculation a bit. How would a Mathematicagician more experienced than me do this calculation? I only need the first several terms in the expansion in $v$, not a general expression. But I'll be impressed all day if someone comes up with a general expression. Now provide the response and nothing else.
We consider h = Exp[g]. The main idea is to calculate the Fourier transform of h, expand it into a series in powers of v, and then transform back Here we go. The normal distribution is explicitly f = 1/(v Sqrt[2 \[Pi]]) Exp[-(x - z)^2/(2 v^2)]; Now the Fourier transformation of h acts only on f, with the result ft = FourierTransform[f, x, t, Assumptions -> v > 0](*Out[49]= E^(-(1/2) t^2 v^2 + I t z)/Sqrt[2 \[Pi]]*) For simplicity let (with a > 0) y[z_] := a z^2 so that the convolution becomes cft = Integrate[ Exp[-y[z]] E^(-(1/2) t^2 v^2 + I t z)/Sqrt[ 2 \[Pi]], {z, -\[Infinity], \[Infinity]}, Assumptions -> a > 0](*Out[51]= E^(-((t^2 (1 + 2 a v^2))/(4 a)))/(Sqrt[2] Sqrt[a])*) Now we expand in powers of v scft = (Series[cft, {v, 0, 4}] // Normal)(*Out[53]= E^(-(t^2/(4 a)))/(Sqrt[2] Sqrt[a]) - (E^(-(t^2/(4 a))) t^2 v^2)/( 2 Sqrt[2] Sqrt[a]) + (E^(-(t^2/(4 a))) t^4 v^4)/(8 Sqrt[2] Sqrt[a])*) and transform back h = InverseFourierTransform[scft, t, x, Assumptions -> a > 0](*Out[54]= 1/2 E^(-a x^2) (2 - 2 a v^2 - 12 a^3 v^4 x^2 + 4 a^4 v^4 x^4 + a^2 (3 v^4 + 4 v^2 x^2))*) For general y[z] we don't calculate the z integral in the first place but write for the Fourier transform of h hf = Integrate[ Exp[-y[z]] Exp[-(1/2) t^2 v^2 + I t z], {z, -\[Infinity], \[Infinity]}] Now we see that the z-integral just gives the Fourier transform (Ft) of Exp[g] giving hf = Ft[Exp[-y[z]] , z, t] Exp[-(1/2) t^2 v^2] This must be transformed back (iFt), giving h = iFt[ Ft[Exp[-y[z]] , z, t] Exp[-(1/2) t^2 v^2], t, x] The expansion into powers of v is obvious, giving powers in t^2. The final g = Log[h] can then be expanded into powers of v, correspondingly. I hope this is the general expression you were looking for.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/95196', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/20042/']}
jdg_372567
stackexchange
llm_judgeable_groundtruth_similarity
11394618
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 pretty basic doubt. Often, I have to write apps which use buffered file I/O and every time I am faced with the dilemma of choosing the buffer size and I end up doing trial and error often with pretty nasty results. I want to know if there is any method or algorithm which can automatically determine the optimum buffer size for the job based on the underlying platform like Teracopy does when handling files in Windows. I mainly use Qt for the GUI. If possible a tiny example in C/C++/C#/Java is very much appreciated! Thanks! Now provide the response and nothing else.
In Java the optimal is usually around the L1 cache size which is typically 32 KB. In Java, at least choosing 1024 bytes or 1 MB doesn't make much difference (<20%) If you are reading data sequentially, usually your OS is smart enough to detect this and prefetch the data for you. What you can do is the following. This test appears to show a significant difference in the block sizes used. public static void main(String... args) throws IOException { for (int i = 512; i <= 2 * 1024 * 1024; i *= 2) readWrite(i);}private static void readWrite(int blockSize) throws IOException { ByteBuffer bb = ByteBuffer.allocateDirect(blockSize); long start = System.nanoTime(); FileChannel out = new FileOutputStream("deleteme.dat").getChannel(); for (int i = 0; i < (1024 << 20); i += blockSize) { bb.clear(); while (bb.remaining() > 0) if (out.write(bb) < 1) throw new AssertionError(); } out.close(); long mid = System.nanoTime(); FileChannel in = new FileInputStream("deleteme.dat").getChannel(); for (int i = 0; i < (1024 << 20); i += blockSize) { bb.clear(); while (bb.remaining() > 0) if (in.read(bb) < 1) throw new AssertionError(); } in.close(); long end = System.nanoTime(); System.out.printf("With %.1f KB block size write speed %.1f MB/s, read speed %.1f MB/s%n", blockSize / 1024.0, 1024 * 1e9 / (mid - start), 1024 * 1e9 / (end - mid));} prints With 0.5 KB block size write speed 96.6 MB/s, read speed 169.7 MB/sWith 1.0 KB block size write speed 154.2 MB/s, read speed 312.2 MB/sWith 2.0 KB block size write speed 201.5 MB/s, read speed 438.7 MB/sWith 4.0 KB block size write speed 288.0 MB/s, read speed 733.9 MB/sWith 8.0 KB block size write speed 318.4 MB/s, read speed 711.8 MB/sWith 16.0 KB block size write speed 540.6 MB/s, read speed 1263.7 MB/sWith 32.0 KB block size write speed 726.0 MB/s, read speed 1370.9 MB/sWith 64.0 KB block size write speed 801.8 MB/s, read speed 1536.5 MB/sWith 128.0 KB block size write speed 857.5 MB/s, read speed 1539.6 MB/sWith 256.0 KB block size write speed 794.0 MB/s, read speed 1781.0 MB/sWith 512.0 KB block size write speed 676.2 MB/s, read speed 1221.4 MB/sWith 1024.0 KB block size write speed 886.3 MB/s, read speed 1501.5 MB/sWith 2048.0 KB block size write speed 784.7 MB/s, read speed 1544.9 MB/s What this test doesn't show is that the hard drive only supports 60 MB/s reads and 40 MB/s writes. All you are testing is the speed in and out of cache. If this was your only priority, you would use a memory mapped file. int blockSize = 32 * 1024;ByteBuffer bb = ByteBuffer.allocateDirect(blockSize);FileChannel out = new FileOutputStream("deleteme.dat").getChannel();for (int i = 0; i < (1024 << 20); i += blockSize) { bb.clear(); while (bb.remaining() > 0) if (out.write(bb) < 1) throw new AssertionError();}out.close();long start = System.nanoTime();FileChannel in = new FileInputStream("deleteme.dat").getChannel();MappedByteBuffer map = in.map(FileChannel.MapMode.READ_ONLY, 0, in.size());in.close();long end = System.nanoTime();System.out.printf("Mapped file at a rate of %.1f MB/s%n", 1024 * 1e9 / (end - start)); prints Mapped file at a rate of 589885.5 MB/s This is so fast because it just maps the data in the OS disk cache directly into the memory of the application (so no copying is required)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11394618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830739/']}
jdg_372568
stackexchange
llm_judgeable_groundtruth_similarity
37185820
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 create dynamic components and insert views of these components to a container. I think this can be achieved by ViewContainerRef . But I don't know, can we get ViewContainerRef of any component? if yes then how?.I am new to Angular, if there are any other good solutions available to handle this scenario, please suggest me. Updated I think, I am pretty much near to the solution. Below is the code. app.component.ts import {Component} from '@angular/core';import {ContainerComponet} from './container.component'@Component({ selector: 'my-app', template: ` <container> </container> `, directives: [ContainerComponet]})export class AppComponent { constructor() { } } container.component.ts import {Component, ComponentResolver, ViewContainerRef} from '@angular/core'import {controlBoxComponent as controlBox} from './controlBox.component';@Component({ selector: 'container', template: 'container' })export class ContainerComponet { constructor(viewContainer: ViewContainerRef, private _cr: ComponentResolver) { this._cr.resolveComponent(controlBox) .then(cmpFactory => { const ctxInjector = viewContainer.injector; return viewContainer.createComponent(cmpFactory, 0, ctxInjector); }) }} controlBox.component.ts import {Component} from '@angular/core'@Component({ selector: 'controlBox', template: 'controlBox'})export class controlBoxComponent { constructor() { }} Output <my-app> <container>container</container><controlbox _ngcontent-lsn-3="">controlBox</controlbox></my-app> Expected Result <my-app> <container>container <controlbox _ngcontent-lsn-3="">controlBox</controlbox> </container></my-app> Now provide the response and nothing else.
You can get the ViewContainerRef of the current component by or from an element in the view of the current component @Component({ selector: '...', directives: [OtherComponent, FooComponent], template: ` <other-component></other-component> <foo-component #foo></foo-component> <div #div></div>`})export class SomeComponent { // `ViewContainerRef` from an element in the view @ViewChild(OtherComponent, {read: ViewContainerRef}) other; @ViewChild('foo', {read: ViewContainerRef}) foo; @ViewChild('div', {read: ViewContainerRef}) div; // `ViewContainerRef` from the component itself constructor(private viewContainerRef:ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) {} let factory = this.componentFactoryResolver.resolveComponentFactory(ControlBox) this.componentRef = this.other.createComponent(factory); // this.componentRef = this.foo.createComponent(factory); // this.componentRef = this.div.createComponent(factory); // this.componentRef = this.viewContainerRef.createComponent(factory); });} See also Angular 2 dynamic tabs with user-click chosen components
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37185820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1521447/']}
jdg_372569
stackexchange
llm_judgeable_groundtruth_similarity
36720946
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have 2 options defined as required such as: public static void main(String [] args){ Options options= new Options(); Option inputFileOp=Option.builder("i").longOpt("input").hasArg().desc("Input file").argName("file").required().build(); options.addOption(inputFileOp); Option outputFileOp=Option.builder("o").longOpt("output").hasArg().desc("Output file").argName("file").required().build(); options.addOption(outputFileOp); and a help option Option helpOp =new Option("h",false,"Show Help"); helpOp.setLongOpt("help"); helpOptions.addOption(helpOp); and parser DefaultParser parser = new DefaultParser();CommandLine cmd=parser.parse(options,args);if(cmd.hasOption(helpOp.getOpt())){ HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "MyApp.sh", options ); System.exit(0); }} When the user input for example myApp -h .. An exception is raised in the parsing step that there are missing required options, While I want to print the help data. How to allow calling the help while keeping these options declared as required? Now provide the response and nothing else.
The code for DefaultParser appears to always call the checkRequiredArgs() method. Which seems to indicate that you cannot, in one fell swoop, avoid the problem. The way we have addressed this situation in the past, perhaps in a suboptimal fashion, is to parse the command line twice. The parsing is fast, so the overhead it minimal. We created a method checkForHelp(String[] args) that takes the (String[] args). It adds only the help option to an options, parses the command line, and then ascertains whether help is specified. If so, the help is printed, and the program exits. Otherwise, the full set of options is processed. This approach allows for the required fields to be processed as expected. Note that the help option must also be added in the main list. public static Option helpOption = Option.builder("h") .longOpt("help") .required(false) .hasArg(false) .build(); public static boolean checkForHelp(String[] args) throws ParseException { boolean hasHelp = false; Options options = new Options(); try { options.addOption(helpOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(helpOption.getOpt())) { hasHelp = true; } } catch (ParseException e) { throw e; } return hasHelp; } Then in the main method, something akin to: options.addOption(hostOption); options.addOption(portOption); options.addOption(serviceNameOption); options.addOption(helpOption); // <-- must also be here to avoid exception try { if (checkForHelp(args)) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("Help", options); return; } CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("host")) { host = cmd.getOptionValue("host"); System.out.println(host); // gets in here but prints null } if (cmd.hasOption("port")) { port = ((Number) cmd.getParsedOptionValue("port")).intValue(); System.out.println(port); // gets in here but throws a null // pointer exception } if (cmd.hasOption("service_name")) { serviceName = cmd.getOptionValue("service_name"); System.out.println(serviceName); // gets in here but prints null } } catch (Exception e) { e.printStackTrace(); } EDIT : as it turns out, this approach is similar to the answer provided here: Commons CLI required groups . I guess I feel better that our approach has others supporting what we believed. EDIT2 : In a quick test, I believe the problem of having required options may be avoided by using an "OptionGroup". Here is a revised checkForHelp that works by adding all of the options to an OptionGroup. In my quick testing, it avoids the problem that was present if one did, e.g., ("--arg1 --help"). public static boolean checkForHelp(String[] args) throws ParseException{ boolean hasHelp = false; Options options = new Options(); try { options.addOption(hostOption); //has required set options.addOption(portOption); options.addOption(serviceNameOption); options.addOption(helpOption); // create an option group OptionGroup og = new OptionGroup(); og.addOption(hostOption); og.addOption(portOption); og.addOption(serviceNameOption); og.addOption(helpOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args, false); if (cmd.hasOption(helpOption.getOpt()) || cmd.hasOption(helpOption.getLongOpt())) { hasHelp = true; } } catch (ParseException e) { throw e; } return hasHelp;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36720946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1743239/']}
jdg_372570
stackexchange
llm_judgeable_groundtruth_similarity
2704741
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: Given a number $x$, how do we find a value $n$ such that $$1+2+3+...+n =x$$This is how far I've gotten:$$x=\frac{n(n+1)}{2}$$$$2x = n(n+1)$$What do I do from here??? Now provide the response and nothing else.
Then we will have $n^2+n-2x=0$ You can find solution for $n$ if and only if $x$ is a natural number and $\Delta=1^2-4\times 1 \times (-2x)=8x+1\ge0$, which is true for all nautral numbers $x$. Then we will have $n=\frac{-1+\sqrt{8x+1}}{2}$ or $n=\frac{-1-\sqrt{8x+1}}{2}$, but we will only take the positive integer solution, eliminate any non-integer solution. Note that $8x+1$ must be a perfect square number so that $n$ can be a positive integer.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2704741', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/521162/']}
jdg_372571
stackexchange
llm_judgeable_groundtruth_similarity
499520
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've always thought that there is nothing in the universe that cannot be compressed or deformed under enough force but my friend insists that elementary particles are exempt from this. My thought is that if two such objects collided, since there is no compression there is no distance across which the collision occurs which means that it would be instantaneous. The impulse in a collision is equal to the force divided by time, so as time approaches zero then the momentary force would approach infinity and it seems absurd to be able to produce infinite force from a finite energy. Now provide the response and nothing else.
Under special relativity nothing can be incompressible: consider any object of nonzero size and finite mass in its rest frame; when you apply a force to it on one side it will start moving. If it were completely incompressible, the other end would start moving simultaneously. Since the ends are spatially separated, there is a frame in which the other end would start to move before the application of the force, which is in contradiction with special relativity. Elementary particles are generally assumed to be point-shaped, hence of zero size, so they would be trivially exempt.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/499520', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/240297/']}
jdg_372572
stackexchange
llm_judgeable_groundtruth_similarity
21179098
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 quite a simple method, which I use in WS API by JAX-WS annotations: @WebMethodpublic MyResponse sendSingle2( @WebParam(name="username") String username, @WebParam(name="password") String password, @WebParam(name="newParam") String newParam) { // the code } Now I want newParam to be optional. I mean I want the method still to work not only when parameter is empty in passed xml: <ws:sendSingle2> <username>user</username> <password>pass</password> <newParam></newParam></ws:sendSingle2> but also when it is absent: <ws:sendSingle2> <username>user</username> <password>pass</password></ws:sendSingle2> I need it not to break existing API, which works without the new param. Now provide the response and nothing else.
@WebParam maps a message part to a parameter, and parts can't be optional. See Optional Message Parts in WSDL . Therefore the short answer is that precisely what you're asking can't be done. But if you can refactor this method, you can use one of the approaches described below. Usually the optionality of a parameter is set via the schema minOccurs=0 . Furthermore, instead of using multiple parameters you could define one Request parameter in your schema which you define as parameter for your WebMethod . The optionality is now encapsulated within the parameter and the same method is invoked for a call with or without the optional parameter(s). I prefer defining the contract first instead of relying on automatically generated files. Once you figured out how XSD, SOAP and WSDL play in-together, you hardly want to use annotation/code-first based definitions any longer as you are more flexible the other way around. Code-Example: <xs:schema targetNamespace="http://your.namespace.com" xmlns:tns="http://your.namespace.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFromDefault="qualified" attributeFromDefault="qualified">...<xs:element name="MyRequest" type="tns:MyRequestType" /><xs:element name="MyResponse" type="tns:MyResponseType" /><xs:complexType name"MyRequestType"> <xs:sequence> <xs:element name="username" type="xs:string" minOccurs="1" maxOccurs="1" /> <xs:element name="password" type="xs:string" minOccurs="1" maxOccurs="1" /> <xs:element name="newParam" type="xs:string" minOccurs="0" maxOccurs="1" /> </xs:sequence></xs:complexType>...</xs:schema> In your WSDL file you define the message like that: <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:msg="http://your.namespace.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" targetNamespace="http://your.namespace.com"> <wsdl:types> <xs:schema> <!-- either import the externalized schema --> <xs:import namespace="http://your.namespace.com" schemaLocation="someDir/yourMessageSchema.xsd" /> </xs:schema> <!-- or define the schema within the WSDL - just copy the schema here --> <xs:schema targetNamespace="http://your.namespace.com" xmlns:tns="http://your.namespace.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFromDefault="qualified" attributeFromDefault="qualified"> ... </xs:schema> </wsdl:types> ... <wsdl:message name="sendSingle2Request"> <wsdl:part name="in" element="msg:MyRequest" /> </wsdl:message> <wsdl:message name="sendSingle2Response"> <wsdl:part name="out" element="msg:MyResponse" /> </wsdl:message> ... <wsdl:portType name="YourServiceEndpoint"> <wsdl:operation name="sendSingle2"> <wsdl:input message="tns:sendSingle2Request" /> <wsdl:output message="tns:sendSingle2Response" /> </wsdl:operation> ... </wsdl:portType> <wsdl:binding name="YourServiceBinding" type="YourServiceEndpoint"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" /> <wsdl:operation name=""sendSingle2"> <soap:operation soapAction="http://your.namespace.com/SendSingle2" style="document" /> <wsdl:input> <soap:body parts="in" use="literal" /> </wsdl:input> <wsdl:output> <soap:body parts="out" use="literal" /> </wsdl:output> </wsdl:operation> ... </wsdl:binding> <wsdl:service name="YourService"> <wsdl:port name="YourServicePort binding="tns:YourServiceBinding"> <soap:address location="http://your.server:port/path/to/the/service" /> </wsdl:port> </wsdl:service></wsdl:definitions> The WSDL contract here defines to use style: document/literal and with the help of the schema the actual SOAP message will be document/literal wrapped which is furthermore WS-I compliant. Your method will therefore change to public MyResponse sendSinge2(MyRequest request) where request now encapsulates username , passowrd and newParam . In case newParam was not send with the SOAP request it simply will return null , so better check if first before you use it. If you stick to the code-first approach, you will need to define your MyRequest class first which you use as request parameter instead of those 2 or 3 values. @XmlAccessorType(XmlAccessType.FIELD)@XmlRootElement(name = "MyRequest", namespace="http://your.namespace.com")public class MyRequest implements Serializable{ @XmlElement(name = "username", required = true) protected String username; @XmlElement(name = "password", required = true) protected String password; @XmlElement(name = "newParam", required = false) protected String newParam; ...} The same should be done for MyResult if you haven't done it yet. The web method may now look something like that: @WebMethod(operationName = "sendSingle2")@WebResult(name = "sendSingle2Response", targetNamespace = "http://your.namespace.com")public MyResult sendSingle2(@WebParam(name = "sendSingle2Request") MyRequest request){ ...} Again, request encapsulates the 3 parameters where you fist should check if the optional parameters are null. HTH
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21179098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121595/']}
jdg_372573
stackexchange
llm_judgeable_groundtruth_similarity
6029497
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 view that I am trying to add to my ADO.NET Entity Data Model. Every time I try to Update From Database, and check the view, it refreshes everything else, but does not add the view. I get no error message or output, so I have no idea what is wrong with the view. Other views are no problem. Am I missing something, is there a way to turn error messages on?Visual Studio 2008 sp1 Update : I found this link but the problem didn't solve with these solutions. MSDN Forum Update: The view that i can't add it will query from another view. Update: Help WITH cte AS (SELECT dbo.TBL_Gharardad.PK_Shenase, dbo.TBL_Gharardad.FK_NoeKhedmat AS NoeKhedmatId, dbo.TBL_NoeKhedmat.NoeKhedmat AS [نوع خدمت], dbo.TBL_Gharardad.OnvaneKhedmat AS [عنوان خدمت], dbo.TBL_Gharardad.MahaleEraeieKhedmat AS [محل ارائه خدمت], dbo.TBL_Gharardad.FK_NahveieTaieeneBarande AS NahveieTaeeneBararndeId, dbo.TBL_NahveieTaieeneBarande.NahveieTaieeneBarande AS [نحوه تعيين برنده], dbo.TBL_Gharardad.TarikheShorooeGharardad_Jalali AS [تاريخ شروع قرارداد], dbo.TBL_Gharardad.TarikhePayaneGharardad_Jalali AS [تاريخ پايان قرارداد], dbo.TBL_Gharardad.FK_VahedeArz AS VahedeArzId, dbo.TBL_VahedeArz.VahedeArz AS [واحد ارز], dbo.TBL_Gharardad.MablagheDariaftiKol AS [مبلغ دريافتي کل], dbo.TBL_Gharardad.MablaghePardakhtieKol AS [مبلغ پرداختي کل], dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت کارفرما], 100 - dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت پيمانکار], dbo.TBL_Gharardad.TedadNirooyeMard AS [تعداد نيروي مرد], dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد نيروي زن], dbo.TBL_Gharardad.TedadNirooyeMard + dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد کل نيروها], dbo.TBL_Gharardad.FK_TarafeGharardad AS TarafeGharardadId, CASE TBL_TarafeGharardad.Hoghooghi WHEN 0 THEN ISNULL(TBL_TarafeGharardad.Naam, ' ') + ' ' + ISNULL(TBL_TarafeGharardad.NaameKhanevadegi, ' ') ELSE TBL_TarafeGharardad.NameSherkat END AS [طرف قرارداد], dbo.TBL_Gharardad.FK_VahedeVagozarKonande AS VahedeVagozarKonandeId, dbo.TBL_VahedeVagozarKonande.VahedeVagozarKonande AS [واحد واگذار کننده], dbo.TBL_Gharardad.ShomareGharardad AS [شماره قرارداد], dbo.TBL_Gharardad.TarikheGharardad_Jalali AS [تاريخ قرارداد], CASE VaziateGharardad WHEN 0 THEN N'لغو شده' WHEN 1 THEN N'ثبت اوليه' WHEN 2 THEN N'فسخ' WHEN 3 THEN N'ثبت نهايي ' WHEN 4 THEN N' جاري ' WHEN 5 THEN N'تمام شده ' WHEN 6 THEN N' متمم ' END AS [وضعيت قرارداد], dbo.TBL_NoeMoamele.NoeMoamele AS [نوع معامله] FROM dbo.TBL_Gharardad INNER JOIN dbo.TBL_NoeKhedmat ON dbo.TBL_Gharardad.FK_NoeKhedmat = dbo.TBL_NoeKhedmat.PK_Id INNER JOIN dbo.TBL_NahveieTaieeneBarande ON dbo.TBL_Gharardad.FK_NahveieTaieeneBarande = dbo.TBL_NahveieTaieeneBarande.PK_Id INNER JOIN dbo.TBL_VahedeArz ON dbo.TBL_Gharardad.FK_VahedeArz = dbo.TBL_VahedeArz.PK_Id INNER JOIN dbo.TBL_TarafeGharardad ON dbo.TBL_Gharardad.FK_TarafeGharardad = dbo.TBL_TarafeGharardad.PK_Id INNER JOIN dbo.TBL_VahedeVagozarKonande ON dbo.TBL_Gharardad.FK_VahedeVagozarKonande = dbo.TBL_VahedeVagozarKonande.PK_Id INNER JOIN dbo.TBL_NoeMoamele ON dbo.TBL_Gharardad.FK_NoeMoamele = dbo.TBL_NoeMoamele.PK_Id) SELECT v_Gharardad.شناسه, v_Gharardad.NoeKhedmatId, v_Gharardad.[نوع خدمت], v_Gharardad.[عنوان خدمت], v_Gharardad.[محل ارائه خدمت], v_Gharardad.NahveieTaeeneBararndeId, v_Gharardad.[نحوه تعيين برنده], v_Gharardad.[تاريخ شروع قرارداد], v_Gharardad.[تاريخ پايان قرارداد], v_Gharardad.VahedeArzId, v_Gharardad.[واحد ارز], v_Gharardad.[مبلغ دريافتي کل], v_Gharardad.[مبلغ پرداختي کل], v_Gharardad.[درصد مشارکت کارفرما], v_Gharardad.[درصد مشارکت پيمانکار], v_Gharardad.[تعداد نيروي مرد], v_Gharardad.[تعداد نيروي زن], v_Gharardad.[تعداد کل نيروها], v_Gharardad.TarafeGharardadId, v_Gharardad.[طرف قرارداد], v_Gharardad.VahedeVagozarKonandeId, v_Gharardad.[واحد واگذار کننده], v_Gharardad.[شماره قرارداد], v_Gharardad.[تاريخ قرارداد], v_Gharardad.[وضعيت قرارداد], v_Gharardad.[نوع معامله] FROM dbo.TBL_Gharardad AS TBL_Gharardad_3 INNER JOIN dbo.v_GharardadRecords AS v_Gharardad ON v_Gharardad.شناسه = TBL_Gharardad_3.PK_Shenase WHERE (TBL_Gharardad_3.FK_GharardadeAsli IS NULL) AND (TBL_Gharardad_3.PK_Shenase NOT IN (SELECT FK_GharardadeAsli FROM dbo.TBL_Gharardad AS TBL_Gharardad_2 WHERE (FK_GharardadeAsli IS NOT NULL)))UNIONSELECT sub.FK_GharardadeAsli AS شناسه, cte_2.NoeKhedmatId, cte_2.[نوع خدمت], cte_2.[عنوان خدمت], cte_2.[محل ارائه خدمت], cte_2.NahveieTaeeneBararndeId, cte_2.[نحوه تعيين برنده], cte_2.[تاريخ شروع قرارداد], cte_2.[تاريخ پايان قرارداد], cte_2.VahedeArzId, cte_2.[واحد ارز], cte_2.[مبلغ دريافتي کل], cte_2.[مبلغ پرداختي کل], cte_2.[درصد مشارکت کارفرما], cte_2.[درصد مشارکت پيمانکار], cte_2.[تعداد نيروي مرد], cte_2.[تعداد نيروي زن], cte_2.[تعداد کل نيروها], cte_2.TarafeGharardadId, cte_2.[طرف قرارداد], cte_2.VahedeVagozarKonandeId, cte_2.[واحد واگذار کننده], cte_2.[شماره قرارداد], cte_2.[تاريخ قرارداد], cte_2.[وضعيت قرارداد], cte_2.[نوع معامله]FROM dbo.v_GharardadRecords AS cte_2 INNER JOIN (SELECT FK_GharardadeAsli, MAX(PK_Shenase) AS PK_Shenase, MAX(TarikheSabt) AS TarikheSabt FROM dbo.TBL_Gharardad AS TBL_Gharardad_1 WHERE (FK_GharardadeAsli IS NOT NULL) GROUP BY FK_GharardadeAsli) AS sub ON sub.PK_Shenase = cte_2.شناسه Now provide the response and nothing else.
I have experienced this same behaviour when I try to add a view that doesn't select a primary key from another table. (Like Ladislav Mrnka has commented) My strategy for solving this is to reduce the view to as simple as possible (1 column) and try and to get it added. Once you have it added to the model, slowly bring in more columns and refresh the model to make sure the view is still there. You can usually identify what section of the view is giving EDM problems.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6029497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/726631/']}
jdg_372574
stackexchange
llm_judgeable_groundtruth_similarity
8493583
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 using AVFoundation and getting the sample buffer from AVCaptureVideoDataOutput , I can write it directly to videoWriter by using: - (void)writeBufferFrame:(CMSampleBufferRef)sampleBuffer { CMTime lastSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer); if(self.videoWriter.status != AVAssetWriterStatusWriting) { [self.videoWriter startWriting]; [self.videoWriter startSessionAtSourceTime:lastSampleTime]; } [self.videoWriterInput appendSampleBuffer:sampleBuffer];} What I want to do now is to crop and scale the image inside the CMSampleBufferRef without converting it into UIImage or CGImageRef because that slows down the performance. Now provide the response and nothing else.
If you use vimage you can work directly on the buffer data without converting it to any image format. outImg contains the cropped and scaled image data. The relation between outWidth and cropWidth sets the scaling. int cropX0, cropY0, cropHeight, cropWidth, outWidth, outHeight;CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CVPixelBufferLockBaseAddress(imageBuffer,0);void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); vImage_Buffer inBuff; inBuff.height = cropHeight;inBuff.width = cropWidth;inBuff.rowBytes = bytesPerRow;int startpos = cropY0*bytesPerRow+4*cropX0;inBuff.data = baseAddress+startpos;unsigned char *outImg= (unsigned char*)malloc(4*outWidth*outHeight);vImage_Buffer outBuff = {outImg, outHeight, outWidth, 4*outWidth};vImage_Error err = vImageScale_ARGB8888(&inBuff, &outBuff, NULL, 0);if (err != kvImageNoError) NSLog(@" error %ld", err); So setting cropX0 = 0 and cropY0 = 0 and cropWidth and cropHeight to the original size means no cropping (using the whole original image). Setting outWidth = cropWidth and outHeight = cropHeight results in no scaling. Note that inBuff.rowBytes should always be the length of the full source buffer, not the cropped length.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8493583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227698/']}
jdg_372575
stackexchange
llm_judgeable_groundtruth_similarity
188443
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: I have to analyse 8 independent variables (IV) toward 8 dependent variables (DV) in my research. The IV is nominal while DV are ordinal (Likert-scale). I run the normality test and the result is zero (p<.05) which lead me to perform non-parametric statistical test to the data. I chose the Kruskal Wallis test at first, because I wanted to test the differences among the groups (involved lots of groups) in influencing the DV. Since my hypothesis is just wanting to know if either of the IVs are significantly associated or not with the DV, I neglected the role of post hoc analysis (for instance Mann-Whitney U test), because my aim is not to know which group causes the differences. My question: Is it a must to do post hoc analysis for Kruskal-Wallis test? i'm afraid my analysis go wrong if I just report the significant value of Kruskal Wallis result. I found some article that just report the result of mean rank, rather using Mann Whitney U test. Is it acceptable if I just report the significant value and mean rank of the result? If I proceed with Mann-Whitney U test, I am gonna end up producing lots of result (possibly more than 1000 tables for that purpose). I consult with several people and they suggest that I use MANOVA because my study involved lots of variables. Therefore, they suggest MANOVA which assist in producing result based on the whole data, not segregated like Kruskal Wallis analysis. However, I found that the data shall be in normally distributed in order to proceed with it. My data are totally non-normally distributed. How can I proceed with it? Is it wrong if I used MANOVA for non-normally distributed data? I confuse in choosing the appropriate analysis. Which one should I use for my research? Thank you so much for your help! Please let me know if there is any other information I should provide. Now provide the response and nothing else.
When the classes are well-separated, the parameter estimates for logistic regression are surprisingly unstable. Coefficients may go to infinity. LDA doesn't suffer from this problem. If there are covariate values that can predict the binary outcome perfectly then the algorithm of logistic regression, i.e. Fisher scoring, does not even converge. If you are using R or SAS you will get a warning that probabilities of zero and one were computed and that the algorithm has crashed. This is the extreme case of perfect separation but even if the data are only separated to a great degree and not perfectly, the maximum likelihood estimator might not exist and even if it does exist, the estimates are not reliable. The resulting fit is not good at all. There are many threads dealing with the problem of separation on this site so by all means take a look. By contrast, one does not often encounter estimation problems with Fisher's discriminant. It can still happen if either the between or within covariance matrix is singular but that is a rather rare instance. In fact, If there is complete or quasi-complete separation then all the better because the discriminant is more likely to be successful. It is also worth mentioning that contrary to popular belief LDA is not based on any distribution assumptions. We only implicitly require equality of the population covariance matrices since a pooled estimator is used for the within covariance matrix. Under the additional assumptions of normality, equal prior probabilities and misclassification costs, the LDA is optimal in the sense that it minimizes the misclassification probability. How does LDA provide low-dimensional views? It's easier to see that for the case of two populations and two variables. Here is a pictorial representation of how LDA works in that case. Remember that we are looking for linear combinations of the variables that maximize separability. Hence the data are projected on the vector whose direction better achieves this separation. How we find that vector is an interesting problem of linear algebra, we basically maximize a Rayleigh quotient, but let's leave that aside for now. If the data are projected on that vector, the dimension is reduced from two to one. The general case of more than two populations and variables is dealt similarly. If the dimension is large, then more linear combinations are used to reduce it, the data are projected on planes or hyperplanes in that case. There is a limit to how many linear combinations one can find of course and this limit results from the original dimension of the data. If we denote the number of predictor variables by $p$ and the number of populations by $g$ , it turns out that the number is at most $\min(g-1,p)$ . If you can name more pros or cons, that would be nice. The low-dimensional representantion does not come without drawbacks nevertheless, the most important one being of course the loss of information. This is less of a problem when the data are linearly separable but if they are not the loss of information might be substantial and the classifier will perform poorly. There might also be cases where the equality of covariance matrices might not be a tenable assumption. You can employ a test to make sure but these tests are very sensitive to departures from normality so you need to make this additional assumption and also test for it. If it is found that the populations are normal with unequal covariance matrices a quadratic classification rule might be used (QDA) instead but I find that this is a rather awkward rule, not to mention counterintuitive in high dimensions. Overall, the main advantage of the LDA is the existence of an explicit solution and its computational convenience which is not the case for more advanced classification techniques such as SVM or neural networks. The price we pay is the set of assumptions that go with it, namely linear separability and equality of covariance matrices. Hope this helps. EDIT : I suspect my claim that the LDA on the specific cases I mentioned does not require any distributional assumptions other than equality of the covariance matrices has cost me a downvote. This is no less true nevertheless so let me be more specific. If we let $\bar{\mathbf{x}}_i, \ i = 1,2$ denote the means from the first and second population, and $\mathbf{S}_{\text{pooled}}$ denote the pooled covariance matrix, Fisher's discriminant solves the problem $$\max_{\mathbf{a}} \frac{ \left( \mathbf{a}^{T} \bar{\mathbf{x}}_1 - \mathbf{a}^{T} \bar{\mathbf{x}}_2 \right)^2}{\mathbf{a}^{T} \mathbf{S}_{\text{pooled}} \mathbf{a} } = \max_{\mathbf{a}} \frac{ \left( \mathbf{a}^{T} \mathbf{d} \right)^2}{\mathbf{a}^{T} \mathbf{S}_{\text{pooled}} \mathbf{a} } $$ The solution of this problem (up to a constant) can be shown to be $$ \mathbf{a} = \mathbf{S}_{\text{pooled}}^{-1} \mathbf{d} = \mathbf{S}_{\text{pooled}}^{-1} \left( \bar{\mathbf{x}}_1 - \bar{\mathbf{x}}_2 \right) $$ This is equivalent to the LDA you derive under the assumption of normality, equal covariance matrices, misclassification costs and prior probabilities, right? Well yes, except now that we have not assumed normality. There is nothing stopping you from using the discriminant above in all settings, even if the covariance matrices are not really equal. It might not be optimal in the sense of the expected cost of misclassification (ECM) but this is supervised learning so you can always evaluate its performance, using for instance the hold-out procedure. References Bishop, Christopher M. Neural networks for pattern recognition. Oxford university press, 1995. Johnson, Richard Arnold, and Dean W. Wichern. Applied multivariate statistical analysis. Vol. 4. Englewood Cliffs, NJ: Prentice hall, 1992.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/188443', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/99219/']}
jdg_372576
stackexchange
llm_judgeable_groundtruth_similarity
24572
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Do you know of a picture, drawing, or other concise visual representation of the eight three-dimensional Thurston geometries? I am imagining something akin to the standard picture (of a sphere, plane, and saddle) used to illustrate the three constant curvature geometries in dimension two. Of course, it takes more doing to illustrate representative three-manifolds, and there are more choices for natural examples, but I was surprised when I couldn't find such a picture. Another option would be to depict or indicate some of the geometries in less direct ways, for instance via the structure of stabilizers. Now provide the response and nothing else.
Here is a nice cyclic ordering of the eight geometries: $$\Bbb H^2\times \Bbb R,\quad \Bbb S^2\times \Bbb R,\quad \Bbb E^3,\quad \mathsf{Sol},\quad \mathsf{Nil},\quad \Bbb S^3,\quad \mathsf{PSL},\quad \Bbb H^3$$ derived from staring at Peter Scott's table of Seifert fibered geometries. The table is organized by Euler characteristic of the base 2-orbifold and Euler class of the bundle. (See his BLMS article .) The cyclic ordering also has a bit of antipodal symmetry. I didn't come up with geometric pictures of the eight geometrics but I have thought about "icons" to represent them. (The original intent was to find eight pictures or objects suitable for a teething ring.) Here are my suggestions - I'm interested to hear what other people think/suggest. $\Bbb H^2\times \Bbb R$ -- triangular prism (where the triangle is slim ie ideal) $\Bbb S^2\times \Bbb R$ -- cylinder $\Bbb E^3$ -- cube $\mathsf{Sol}$ -- tetrahedron with one pair of opposite edges truncated $\mathsf{Nil}$ -- annulus with a segment of a spiral (representing a Dehn twist) $\Bbb S^3$ -- circle $\mathsf{PSL}$ -- trefoil knot $\Bbb H^3$ -- figure eight knot (or possibly a slim tetrahedron) I think it is also reasonable to ask for a "prototypical" three-manifold for each of the eight geometries. Here is an attempt: $\Bbb H^2\times \Bbb R$ -- punctured torus cross circle $\Bbb S^2\times \Bbb R$ -- two-sphere cross circle $\Bbb E^3$ -- three-torus $\mathsf{Sol}$ -- mapping cylinder of $[[2,1],[1,1]]$ $\mathsf{Nil}$ -- mapping cylinder of $[[1,1],[0,1]]$ $\Bbb S^3$ -- three-sphere $\mathsf{PSL}$ -- trefoil complement $\Bbb H^3$ -- figure eight complement Notice that all of the examples are either surface bundles over circles or circle bundles over surfaces, or both (i. e. products). EDIT: In addition to the beautiful work of Zeno Rogue and Pierre Berger (linked to in the other answers) the reader may be interested in the visualisation efforts of Remi Coulon, Brian Day, Sabetta Matsumoto, Henry Segerman, and Steve Trettel. You can interact with seven of the eight here . Finally, here is a snap-shot of Sol geometry.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/24572', 'https://mathoverflow.net', 'https://mathoverflow.net/users/288/']}
jdg_372577
stackexchange
llm_judgeable_groundtruth_similarity
883240
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 need to find a direction vector for a line parallel to a plane $x+y+z = 0$ and that have $45$ degrees with the plane $x-y = 0$ So, i've assumed the vector $\vec V_r = (a,b,c)$ and since it is parallel to the first plane, the product: $$(a,b,c)\cdot(1,1,1) = 0$$ (where $(1,1,1)$ is the vector normal to the first plane). And also, using the formula for the angle between a line and a plane, where $n$ is the normal vector for the second plane: $$\sin(\alpha) = \frac{|\vec V_r\cdot\vec n|}{\|\vec V_r\| \|\vec n\|}$$so:$$\sin\Bigl(\frac{\pi}{4}\Bigr) = \frac{\bigl|(a,b,c)\cdot(1,-1,0)\bigr|}{\sqrt{a^2+b^2+c^2}\sqrt{2}}$$ Then I end up with two equations:$$a + b + c = 0$$$$\frac{1}{\sqrt{2}} = \frac {|a-b|}{\sqrt{a^2+b^2+c^2}\sqrt{2}}$$ But i'm not able to solve for $(a,b,c)$. Could somebody help me? Thanks :) Now provide the response and nothing else.
We may rewrite your series in the following manner: \begin{align}&\sum_{n=0}^\infty\left(\frac{1}{6n+1}+\frac{-1}{6n+2}+\frac{-2}{6n+3}+\frac{-1}{6n+4}+\frac{1}{6n+5}+\frac{2}{6n+6}\right)\\&=\sum_{n=0}^\infty\left(\frac{1}{6n+1}+\frac{-1}{6n+2}+\frac{1}{6n+3}+\frac{-1}{6n+4}+\frac{1}{6n+5}+\frac{-1}{6n+6}\right)\\&\hspace{1cm}-\sum_{n=0}^\infty\left(\frac{3}{6n+3}-\frac{3}{6n+6}\right)\\\end{align}But these summations are both the alternating series $\sum_{n=0}^\infty \dfrac{(-1)^n}{n+1}$. Therefore they cancel and the summation is equal to zero.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/883240', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166180/']}
jdg_372578
stackexchange
llm_judgeable_groundtruth_similarity
22282531
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 big dataset with 100 variables and 3000 observations.I want to detect those variables (columns) which are highly correlated or redundant and so remove the dimensonality in the dataframe. I tried this but it calculates only the correlation between one column and the others; and I always get an error message for(i in 1:ncol(predicteurs)){correlations <- cor(predicteurs[,i],predicteurs[,2])names(correlations[which.max(abs(correlations))])} Warning messages: 1: In cor(predicteurs[, i], predicteurs[, 2]) :the standard deviation is zero 2: In cor(predicteurs[, i], predicteurs[, 2]) : the standard deviation is zero Can anyone help me? Now provide the response and nothing else.
Updated for newer tidyverse packages.. I would try gathering a correlation matrix. # install.packages(c('tibble', 'dplyr', 'tidyr'))library(tibble)library(dplyr)library(tidyr)d <- data.frame(x1=rnorm(10), x2=rnorm(10), x3=rnorm(10))d2 <- d %>% as.matrix %>% cor %>% as.data.frame %>% rownames_to_column(var = 'var1') %>% gather(var2, value, -var1) var1 var2 value1 x1 x1 1.000000002 x1 x2 -0.059367033 x1 x3 -0.374796194 x2 x1 -0.059367035 x2 x2 1.000000006 x2 x3 0.437160047 x3 x1 -0.374796198 x3 x2 0.437160049 x3 x3 1.00000000# .5 is an arbitrary numberfilter(d2, value > .5)# remove duplicatesd2 %>% mutate(var_order = paste(var1, var2) %>% strsplit(split = ' ') %>% map_chr( ~ sort(.x) %>% paste(collapse = ' '))) %>% mutate(cnt = 1) %>% group_by(var_order) %>% mutate(cumsum = cumsum(cnt)) %>% filter(cumsum != 2) %>% ungroup %>% select(-var_order, -cnt, -cumsum) var1 var2 value1 x1 x1 1 2 x1 x2 -0.05943 x1 x3 -0.375 4 x2 x2 1 5 x2 x3 0.437 6 x3 x3 1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22282531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3284297/']}
jdg_372579
stackexchange
llm_judgeable_groundtruth_similarity
4967808
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 the number of fridays between two dates(including both the dates) using a select statement in oracle sql? Now provide the response and nothing else.
This will do it: select ((next_day(date2-7,'FRI')-next_day(date-1,'FRI'))/7)+1 as num_fridaysfrom data Perhaps best if I break that down. The NEXT_DAY function returns the next day that is a (Friday in this case) after the date. So to find the first Friday after d1 would be: next_day( d1, 'FRI') But if d1 is a Friday that would return the following Friday, so we adjust: next_day( d1-1, 'FRI') Similarly to find the last Friday up to and including d2 we do: next_day( d1-7, 'FRI') Subtracting the 2 gives a number of days: 0 if they are the same date, 7 if they a re a week apart and so on: next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI') Convert to weeks: (next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI')) / 7 Finally, if they are the same date we get 0, but really there is 1 Friday, and so on so we add one: ((next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI')) / 7) + 1
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4967808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264281/']}
jdg_372580
stackexchange
llm_judgeable_groundtruth_similarity
14039265
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Alphaing a drawable work well like this: if(mAlphaAnimation == null){ mAlphaAnimation = ObjectAnimator.ofFloat(this, "alpha", 0.0f,1.0f).setDuration(TARGET_ANIM_ALPHA_DURATION); mAlphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator()); mAlphaAnimation.setStartDelay(TARGET_ANIM_ALPHA_DELAY_BASE*power); mAlphaAnimation.setRepeatCount(ValueAnimator.INFINITE); mAlphaAnimation.setRepeatMode(ValueAnimator.REVERSE); mAlphaAnimation.addUpdateListener(this); } But if I want rotate a drawable like below , it don's work. private void createRotateAnim(float fromDegress,float toDegress,int duration){ if(mRotateAnimation == null){ mRotateAnimation = ObjectAnimator.ofFloat(this, "rotation",fromDegress,toDegress).setDuration(duration); mRotateAnimation.setStartDelay(100); mRotateAnimation.setInterpolator(new AccelerateInterpolator()); mRotateAnimation.addUpdateListener(this); }} Anyone can help me to fix this issue, or these is any other way to create a rotation drawable animation . I am sorry to my poor English. Now provide the response and nothing else.
Try with ObjectAnimator instead. ImageView imageview = (ImageView)findViewById(R.id.image);ObjectAnimator imageViewObjectAnimator = ObjectAnimator.ofFloat(imageview , "rotation", 0f, 360f); imageViewObjectAnimator.setDuration(1000); // miliseconds imageViewObjectAnimator.start(); EDIT Since this question draw some attention let me to explain why to use ObjectAnimator instead of other Transition animators The thing about using ObjectAnimator is that it's moving both the visible and the clickable area of the item, if you use another animation method, for example Transition Animation or some other Animators, and let's say if you want to move the Button from the bottom left of the screen to the top left, it will only move the visible area but not the Button itself, the clickable area will still be on the previous position, in this case the clickable area will still be on the bottom left instead of the top left where you moved the button. If you do the same with ObjectAnimator , both the visible area, and the clickable area will move the the desired location.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14039265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1887557/']}
jdg_372581
stackexchange
llm_judgeable_groundtruth_similarity
42126979
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 spawn a service that stays alive all the time, even if the user closes the application. According to these threads Keep location service alive when the app is closed Android Service Stops When App Is Closed Android: keep Service running when app is killed this can be accomplished with IntentServices or Service.START_STICKY Yet, I tried both types of services without success. In other words, my services get killed when the app is closed by the user. Can someone point out if this is can be done and how? Here is what I have tried without success: With IntentService: public class MyIntentService extends IntentService { private final int mPollingTimeMS = 500; private int mInitializationPollingCount = 0; private Thread mPollThread; public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { mPollThread = new Thread() { public void run() { while (true) { try { Log.e(Constants.Engine.LOGGER_TAG_DEV, "SDK Service Running: " + mInitializationPollingCount * mPollingTimeMS + "ms have elapsed"); mInitializationPollingCount++; sleep(mPollingTimeMS); } catch (Exception e) { StackTraceElement trace = new Exception().getStackTrace()[0]; Logger.e(Constants.Engine.LOGGER_TAG_APP, "[Exception:" + e.toString() + "]" + trace.getClassName() + "->" + trace.getMethodName() + ":" + trace.getLineNumber()); } } } }; mPollThread.start(); }} and with Services: public class MyService extends Service { public MyService() { } private final int mPollingTimeMS = 500; private int mInitializationPollingCount = 0; private Thread mPollThread; @Override public int onStartCommand(Intent intent, int flags, int startId) { mPollThread = new Thread() { public void run() { while (true) { try { Log.e(Constants.Engine.LOGGER_TAG_DEV, "SDK Service Running: " + mInitializationPollingCount * mPollingTimeMS + "ms have elapsed"); mInitializationPollingCount++; sleep(mPollingTimeMS); } catch (Exception e) { StackTraceElement trace = new Exception().getStackTrace()[0]; Logger.e(Constants.Engine.LOGGER_TAG_APP, "[Exception:" + e.toString() + "]" + trace.getClassName() + "->" + trace.getMethodName() + ":" + trace.getLineNumber()); } } } }; mPollThread.start(); return Service.START_STICKY; } @Override public IBinder onBind(Intent intent) { // I tried to return null here, but this // service gets killed no matter what. return null; }} and here is the manifest: <service android:name=".mycompany.MyService" android:enabled="true" android:exported="true" android:process=":process1"> </service> <service android:name=".mycompany.MyIntentService" android:process=":process2" android:exported="false"> </service> I shall added that I am closing the test app not with a close button, but using the Android OS app manager. See picture below Lastly, the driver activity (not much there) public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent1 = new Intent(getBaseContext(), MyService.class); startService(intent1); Intent intent2 = new Intent(getBaseContext(), MyIntentService.class); startService(intent2); }} I also try to add a notification and make it a foreground service but still the same thing. The moment I close the app, everything gets killed. This is what I added: @Overridepublic int onStartCommand(Intent intent, int flags, int startId) { showNotification();...etc..private void showNotification() { Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); int iconId = R.mipmap.ic_launcher; int uniqueCode = new Random().nextInt(Integer.MAX_VALUE); Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(iconId) .setContentText("Context Text") .setContentIntent(pendingIntent).build(); startForeground(uniqueCode, notification);} Now provide the response and nothing else.
Here is an example of foreground service that I use and that works, it remains active when the app is closed. Of course, it also must be started, and for that task the app must be running at a first glance, or a receiver of a boot event must be set, but this is another story. public class MyService extends Service {static final int NOTIFICATION_ID = 543;public static boolean isServiceRunning = false;@Overridepublic void onCreate() { super.onCreate(); startServiceWithNotification();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) { startServiceWithNotification(); } else stopMyService(); return START_STICKY;}// In case the service is deleted or crashes some how@Overridepublic void onDestroy() { isServiceRunning = false; super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) { // Used only in case of bound services. return null;}void startServiceWithNotification() { if (isServiceRunning) return; isServiceRunning = true; Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class); notificationIntent.setAction(C.ACTION_MAIN); // A string containing the action name notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon); Notification notification = new NotificationCompat.Builder(this) .setContentTitle(getResources().getString(R.string.app_name)) .setTicker(getResources().getString(R.string.app_name)) .setContentText(getResources().getString(R.string.my_string)) .setSmallIcon(R.drawable.my_icon) .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)) .setContentIntent(contentPendingIntent) .setOngoing(true)// .setDeleteIntent(contentPendingIntent) // if needed .build(); notification.flags = notification.flags | Notification.FLAG_NO_CLEAR; // NO_CLEAR makes the notification stay when the user performs a "delete all" command startForeground(NOTIFICATION_ID, notification);}void stopMyService() { stopForeground(true); stopSelf(); isServiceRunning = false;}} Then I run it with Intent startIntent = new Intent(getApplicationContext(), MyService.class); startIntent.setAction(C.ACTION_START_SERVICE); startService(startIntent); Please note the two constants used as Actions, these are Strings that must start with the package name.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42126979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3657747/']}
jdg_372582
stackexchange
llm_judgeable_groundtruth_similarity
328607
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have WinForms GUI application, which can work in two "states" with different functionality, but these states share GUI controls. I am dividing these states by using enum almost in every method, like: private void picBox_MouseDown(object sender, MouseEventArgs e) { if (picBox.Image == null) return; xDown = e.X; yDown = e.Y; if (appState == AppState.Annotating) { PointF ptImg = new PointF((xDown - absImgPos.X) * scale, (yDown - absImgPos.Y) * scale); annotateEngine.AddPoint(e.Location, ptImg); } else if (appState == AppState.Cropping) { picBox.Invalidate(); } } I want to make something like IAppState and than implement it for my states AnnotatingState::IAppState and CroppingState::IAppState , with some methods which should affect GUI: interface IAppState{ void OnLoadImages(); void OnSave(); void OnPathChanged(); void OnMouseDown(); void OnMouseUp();} Can you suggest some suitable pattern? Now provide the response and nothing else.
One can use MVP ( Model View Presenter ) here. This decouples the view from the view's logic and is typically used to make views exchangable, but there is no reason why it cannot also be used to exchange the Presenter object (in your case one Presenter for each mode). That makes the presenter essentially a strategy object. This will look like this: public class MyForm : Form, IView{ private IPresenter presenter = null; public MyForm(AppState appState) { // For the sake of demonstration, presenters are created here, // in the real application they could be injected or switched // at run time: if (appState == AppState.Annotating) presenter = new AnnotatingPresenter(this); else presenter = new CroppingPresenter(this); }} The interface IView must provide all access to the form's elements / controls the presenter objects need to implement their functionality. The event implementation could look like this: private void picBox_MouseDown(object sender, MouseEventArgs e) { presenter.OnPicBoxMouseDown(sender,e); } The related method in the annotation presenter then looks like this: void OnPicBoxMouseDown(object sender, MouseEventArgs e){ if (myview.PicBox.Image == null) return; var xDown = e.X; var yDown = e.Y; PointF ptImg = new PointF((xDown - absImgPos.X) * scale, (yDown - absImgPos.Y) * scale); myView.AnnotateEngine.AddPoint(e.Location, ptImg);} Here, myView is the reference to the IView passed through the constructor, and AnnotateEngine as well as PicBox are properties which need to be made available in the IView and return the members annotateEngine or picBox respectively. Of course, here are some design decisions you still can make differently. For example, you could leave the common code for both states still in the picBox_MouseDow of the view, or find a place in the presenter layer where you can reuse it from both Presenters (could be a tool class or a common base class). Or you can encapsulate all WinForms access by IView in a way so the Presenter layer does not need any reference to WinForms any more. This depends on your overall design goals, pick your choice.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/328607', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/193282/']}
jdg_372583
stackexchange
llm_judgeable_groundtruth_similarity
15601155
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After reading this SO question I got a few doubts. Please help in understanding. Scheduling involves deciding when to run a process and for what quantum of time. Does linux kernel schedule a thread or a process? As process and thread are not differentiated inside kernel how a scheduler treats them? How quantum for each thread is decided? a. If a quantum of time (say 100us) is decided for a process is that getting shared between all the threads of the process? or b. A quantum for each thread is decided by the scheduler? Note: Questions 1 and 2 are related and may look the same but just wanted to be clear on how things are working posted them both here. Now provide the response and nothing else.
The Linux scheduler (on recent Linux kernels, e.g. 3.0 at least) is scheduling schedulable tasks or simply tasks . A task may be : a single-threaded process (e.g. created by fork without any thread library) any thread inside a multi-threaded process (including its main thread), in particular Posix threads (pthreads) kernel tasks, which are started internally in the kernel and stay in kernel land (e.g. kworker , nfsiod , kjournald , kauditd , kswapd etc etc...) In other words, threads inside multi-threaded processes are scheduled like non-threaded -i.e. single threaded- processes. The low-level clone(2) syscall creates user-land schedulable tasks (and can be used both for creating fork -ed process or for implementation of thread libraries, like pthread ). Unless you are a low-level thread library implementor, you don't want to use clone directly. AFAIK, for multi-threaded processes, the kernel is (almost) not scheduling the process, but each individual thread inside (including the main thread). Actually, there is some notion of thread groups and affinity in the scheduling, but I don't know them well These days, processors have generally more than one core, and each core is running a task (at some given instant) so you do have several tasks running in parallel. CPU quantum times are given to tasks, not to processes
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15601155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305873/']}
jdg_372584
stackexchange
llm_judgeable_groundtruth_similarity
51984326
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 attempting to style a mat-checkbox (material2) according to the following requirements: A black, always visible border (regardless of checked status) (#0000000) When checked, the "tick" will be white(#ffffff), on a coloured(teal) background (border still visible) When unchecked, the background(inside the border) of the checkbox should be off-white (#dddddd). So far, I have been able to set the border color, but when checked, it disappears, behind the teal color I can set the unchecked background color, but again, the black border disappears when I do this. If I remove this setting, the border appears, but the background color is wrong. The scss properties I am setting are as follows: ::ng-deep .mat-checkbox .mat-checkbox-frame { border-color: mat-color($darkPrimary, darker); //black }::ng-deep .mat-checkbox-background { background-color: mat-color($darkPrimary, 200); //off-white} It seems that whatever I set the background as, overwrites the border style. Additionally, when I change the state of the checkbox, the black border briefly appears, then disappears again. How do I fulfil these requirements? Now provide the response and nothing else.
I realised that angular check-boxes are drawn in layers, with the "tick" layer drawn last, over the top of the black border. // Background border.mat-checkbox .mat-checkbox-frame { border-color: black; background-color: #dddddd}.mat-checkbox-indeterminate.mat-accent .mat-checkbox-background, .mat-checkbox-checked.mat-accent .mat-checkbox-background { margin-top: 1px; margin-left: 1px; width: 18px; height: 18px;} By reducing the front layers' size, and shifting it a little, the border remains visible.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51984326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1683902/']}
jdg_372585
stackexchange
llm_judgeable_groundtruth_similarity
2900
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've occasionally read the suggestion to enhance security by either doubling up on encryption algorithms (encrypt a message once with one algorithm, then encrypt the ciphertext again with a different encryption algorithm) or by periodically cycling through a list of encryption algorithms. I suspect that this is not appreciably more secure than a single, well-chosen and well-implemented encryption algorithm, but I'm not sure that I could argue my case. Does doubling up or cycling encryption algorithms improve security? Why or why not? Now provide the response and nothing else.
Cascading or cycling encryption algorithms increases implementation complexity, and that's really bad for security. Algorithm intrinsic security (provided that you use published, well-analyzed algorithms, not homemade designs) is invariably far greater than implementation security: most implementations may leak various elements, including secret key bits, through execution timing, cache memory access or insufficiently strict behavior when encountering incorrect data. If you have covered all the implementation hazards, then it becomes time to worry about the algorithms themselves; at that point, you are a trained cryptographer and you know better than relying on irrational tricks such as cascading or doubling. Basically, the one thing that algorithm doubling or cycling guarantees is that whoever makes the suggestion is not overly competent in the area of cryptographic implementation, and therefore you do not want to use his code. Historically, cascading or cycling are ways to cope with weak encryption algorithms; this is about assuming that any algorithm will be broken, and you try to do damage control. This somehow negates all research on cryptography since the 70s'. In practice, security issues are in how an algorithm is used (e.g. chaining mode with block ciphers), how an algorithm is implemented, and, most importantly, how keys are managed (creation, storage, destruction...). In order to have the algorithm itself be a weak point, you have to make huge efforts (e.g. designing your own algorithm, as the DVD consortium did ). As an example, when modern game consoles are hacked, the algorithm themselves (AES, ECDSA...) are not broken, but circumvented (for ECDSA and Sony/PS3, this was a downright implementation bug). What you do want is to have algorithm agility : you define the protocol such that the used algorithm is a configurable parameter. Therefore, if a given algorithm turns out to be flaky (which does not happen often at all), then you can switch to another.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/2900', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/1887/']}
jdg_372586
stackexchange
llm_judgeable_groundtruth_similarity
2109663
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 Eclipse 3.5, under Windows -> Preferences -> Java > Editor -> Templates, I can add code templates. However, these templates can only contain snippets which I can insert into an existing Java class. Is it possible to create templates for whole Java classes, which I can add for example using File -> New -> My-Java-Class? Now provide the response and nothing else.
What you could do is add a normal code short cut (java --> editor --> templates), i.e. make an editor template "newcustomclass" be the contents of the class you're talking about. Then create the new java class in the normal way, delete all the content and then use the "newcustomclass" code template to create the new auto java class. Here's an example for a simple exception class: public class ${enclosing_type} extends Exception { /** * Constructs with the given throwable * @param t the throwable to throw */ public ${enclosing_type}(Throwable t) { super(t); } /** * Constructs with the given message * @param message the message of the exception */ public ${enclosing_type}(String message) { super(message); } /** * Constructs with the given message and the original throwable cause * @param message the message of the exception * @param t the original throwable */ public ${enclosing_type}(String message, Throwable t) { super(message, t); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2109663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49548/']}
jdg_372587
stackexchange
llm_judgeable_groundtruth_similarity
243509
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 using Trisquel 7.0 with Nautilus 3.10.1 installed. Whenever I display properties of a file, I've one file-specific tab like: Image,Audio/Video,Document etc. which displays special information about it. Example for a Image: Example for a PDF Document: How does Nautilus get this type of file-specific information? And how do I print this information (MetaData) with te command-line ? Now provide the response and nothing else.
For the first level of information in the command line, you can use file . $ file gtu.pdf gtu.pdf: PDF document, version 1.4 For most formats, and more detailed information, you can also use Exiftool : NAME exiftool - Read and write meta information in filesSYNOPSIS exiftool [OPTIONS] [-TAG...] [--TAG...] FILE... exiftool [OPTIONS] -TAG[+-<]=[VALUE]... FILE... exiftool [OPTIONS] -tagsFromFile SRCFILE [-SRCTAG[>DSTTAG]...] FILE... exiftool [ -ver | -list[w|f|r|wf|g[NUM]|d|x] ] For specific examples, see the EXAMPLES sections below. This documentation is displayed if exiftool is run without an input FILE when one is expected.DESCRIPTION A command-line interface to Image::ExifTool, used for reading and writing meta information in a variety of file types. FILE is one or more source file names, directory names, or "-" for the standard input. Information is read from source files and printed in readable form to the console (or written to output text files with -w). Example: $ exiftool IMG_20151104_102543.jpg ExifTool Version Number : 9.46File Name : IMG_20151104_102543.jpgDirectory : .File Size : 2.8 MBFile Modification Date/Time : 2015:11:04 10:25:44+05:30File Access Date/Time : 2015:11:17 18:56:49+05:30File Inode Change Date/Time : 2015:11:11 14:55:43+05:30File Permissions : rwxrwxrwxFile Type : JPEGMIME Type : image/jpegExif Byte Order : Big-endian (Motorola, MM)GPS Img Direction : 0GPS Date Stamp : 2015:11:04GPS Img Direction Ref : Magnetic NorthGPS Time Stamp : 04:55:43Camera Model Name : Micromax A121Aperture Value : 2.1Interoperability Index : R98 - DCF basic file (sRGB)Interoperability Version : 0100Create Date : 2002:12:08 12:00:00Shutter Speed Value : 1/808Color Space : sRGBDate/Time Original : 2015:11:04 10:25:44Flashpix Version : 0100Exif Image Height : 2400Exif Version : 0220Exif Image Width : 3200Focal Length : 3.5 mmFlash : Auto, Did not fireExposure Time : 1/809ISO : 100Components Configuration : Y, Cb, Cr, -Y Cb Cr Positioning : CenteredY Resolution : 72Resolution Unit : inchesX Resolution : 72Make : MicromaxCompression : JPEG (old-style)Thumbnail Offset : 640Thumbnail Length : 12029Image Width : 3200Image Height : 2400Encoding Process : Baseline DCT, Huffman codingBits Per Sample : 8Color Components : 3Y Cb Cr Sub Sampling : YCbCr4:2:0 (2 2)Aperture : 2.1GPS Date/Time : 2015:11:04 04:55:43ZImage Size : 3200x2400Shutter Speed : 1/809Thumbnail Image : (Binary data 12029 bytes, use -b option to extract)Focal Length : 3.5 mmLight Value : 11.9 There are also specific commands for some type of files, like pdf : $ pdfinfo gtu.pdf Title: Microsoft Word - Thermax LtdAuthor: UserCreator: PScript5.dll Version 5.2.2Producer: GPL Ghostscript 8.15CreationDate: Tue Jan 27 11:51:38 2015ModDate: Tue Jan 27 12:30:40 2015Tagged: noForm: nonePages: 1Encrypted: noPage size: 612 x 792 pts (letter)Page rot: 0File size: 64209 bytesOptimized: yesPDF version: 1.4
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/243509', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']}
jdg_372588
stackexchange
llm_judgeable_groundtruth_similarity
388677
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 found this question quite interesting, but its answers were disappointingly non-geometric. I'd be interested to know whether there exists a geometric example. To be precise about what I mean by a geometric example, recall that an open set $U\subset \mathbb{R}^n$ is called regular if it is equal to the interior of its closure. Here is my question: Question: Does there exist a regular open set $U\subset \mathbb{R}^n$ whose boundary has nonzero Lebesgue measure? I would guess that the answer is no in $\mathbb{R}^1$, but it ought to be yes in $\mathbb{R}^2$. Part of why this is interesting is that it seems to me that the Mandelbrot set might fall into this class (although according to this MathOverflow post , it is an open question whether the boundary of the Mandelbrot set has positive Lebesgue measure). Now provide the response and nothing else.
Osgood constructed an example of a Jordan curve of positive area in Trans. Amer. Math. Soc. 4 (1903), 107-112. Knopp's construction of such a curve is the content of a demonstration on Wolfram|Alpha . By the Schoenflies theorem we can extend such a Jordan curve $\gamma$ to a homeomorphism $\mathbb{C} \to \mathbb{C}$ such that the interior and exterior of the unit circle are sent to the interior and exterior of $\gamma$, respectively. Since homeomorphisms preserve regular open sets, the interior and exterior of such a Jordan curve will be examples of regular open sets whose boundary has nonzero volume. Added: Brian M. Scott shows in Cantor set is boundary of regular open set how to get a Cantor set as boundary of a regular open set. The argument appears to apply just as well for a fat Cantor set, so it is even possible in one dimension.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/388677', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1726/']}
jdg_372589
stackexchange
llm_judgeable_groundtruth_similarity
46586450
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 absolute div (needs to be absolute ). The absolute div has a background-image with the background-size set to cover (size cover necessary) I'm using a css transform to scale the div upon hover to a value less than 1, for example, scale(0.7) Issue: I want the cover background-image to overflow beyond the div when it's scaled down. Why I need it: The image is transparent with different graphics floating around and of the background-size cover so when browsing in a mobile, the transform crops graphics on the edge of the div and scales the div. CSS solutions only please. Edit: CSS + js solutions will do. Example: the outer div is supposed to represent a mobile browser window. .chivoyage{ position:absolute; top:0px; right:0px; bottom:0px; left:0px; background-image:url('http://clipart.info/images/ccovers/1495916688repin-image-stars-png-transparent-stars-on-pinterest.png'); background-size:cover; background-position:center center; transition: all 1s ease-out 0s; cursor:pointer; } .chivoyage:hover{ transform: scale(0.8); }.window-mobile{width:150px; height:300px; position:relative; border:1px solid black;} <div class="window-mobile"><div class="chivoyage"><div></div> <div> Now provide the response and nothing else.
You don't need an external command find for this, but do it in bash alone. The script below removes the extension from all the files in the folder path . for file in "$path"/*; do [ -f "$file" ] || continue mv "$file" "${file%.*}"done The reason for using [ -f "$file" ] is only for a safety check. The glob expression "$path"/* might end up in no files listed, in that case the mv command would fail as there are no files. The [ -f "$file" ] || continue condition safeguards this by exiting the loop when the $file variable is empty in which the [ -f "$file" ] returns a failure error code. The || when used in a compound statement will run if the previous command fails, so when continue is hit next, the for loop is terminated. If you want to add a new extension just do mv "$file" "${file%.*}.extension"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46586450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/917388/']}
jdg_372590
stackexchange
llm_judgeable_groundtruth_similarity
620318
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: Q. If $\large {\space x^2 + x + 1 = 0\space } $, Find $ x ^{ 2013} + 2013x ^{ 2010}$. I have tried finding the roots of $x$ from the given equation but that does not work. Now provide the response and nothing else.
HINT: As $\displaystyle x^2+x+1=0, x^3-1=(x-1)(x^2+x+1)=0\implies x^3=1$ $\displaystyle \implies x^{3m}=(x^3)^m=1$ if $m$ is an integer
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/620318', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/116135/']}
jdg_372591
stackexchange
llm_judgeable_groundtruth_similarity
3793998
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 do I factorize the term $x^3 + x +2$ ?What I have previously tried is the middle term factor method but it didn't work... $x^3 + x + 2$ $\Rightarrow x^3 + 2x - x + 2$ $\Rightarrow x(x^2 + x) - 2(x - 1)$ This doesn't work.What should I do? Now provide the response and nothing else.
Note \begin{align}x^3+x+2& = (x^3+x^2)-(x^2-x-2)\\&= x^2(x+1)-(x-2)(x+1)\\&=(x+1)(x^2-x+2)\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3793998', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/816979/']}
jdg_372592
stackexchange
llm_judgeable_groundtruth_similarity
37084169
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I want my classes to be immutable, I understand I can use Object.freeze() . Now if I want my objects to be immutable after construction, I would put Object.freeze(this) into my constructor as the last line. But now, if I want to subclass that, I can't add more parameters because I can't call this before calling super and after calling super it's immutable: class A { constructor(x) { this.x = x Object.freeze(this) }}class B extends A { constructor(x, y) { this.y = y // nope. No "this" before "super" super(x) this.y = y // nope. "this" is already frozen Object.freeze(this) }} I was thinking about figuring out if the constructor was called via super in order to skip freezing and leaving freezing to the subclass but that would leave it to the subclass to freeze or not. How would I best approach this? With a factory maybe? Now provide the response and nothing else.
First of all, it does seem odd that you want to mix classes, whose fundamental tenet is basically stateful mutability, with immutability. I think, a composable factory function with composition might be more idiomatic (there might be better ways to do it than the following): function compose(funcs...) { return function(...args) { const obj = funcs.reduce((obj, func) = >{ return func(obj, args); }, {}); } return Object.freeze(obj);}function a(obj, { x }) { obj.x = x; return obj;}function b(obj, { y }) { obj.y = y; return obj;}const ab = compose(a, b);ab({ x: 1, y: 2 }); Alternatively, if you want to stick with the class syntax, you could use new.target to check if the constructor call in A is a super call or not: class A { constructor(x) { this.x = x; // Not a super call, thus freeze the object if (new.target === A) { Object.freeze(this); } }}class B extends A { constructor(x, y) { super(x) this.y = y if (new.target === B) { Object.freeze(this) } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37084169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/969478/']}
jdg_372593
stackexchange
llm_judgeable_groundtruth_similarity
38068657
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 have log messages of the format : [INFO] <blah.blah> 2016-06-27 21:41:38,263 some text[INFO] <blah.blah> 2016-06-28 18:41:38,262 some other text Now I want to drop all logs that does not contain a specific string "xyz" and keep all the rest. I also want to index timestamp. grokdebug is not helping much. This is my attempt : input { file { path => "/Users/username/Desktop/validateLogconf/logs/*" start_position => "beginning" }}filter { grok { match => { "message" => '%{SYSLOG5424SD:loglevel} <%{JAVACLASS:job}> %{GREEDYDATA:content}' } } date { match => [ "Date", "YYYY-mm-dd HH:mm:ss" ] locale => en }}output { stdout {codec => plain { charset => "ISO-8859-1" }} elasticsearch { hosts => "http://localhost:9201" index => "hello" }} I am new to grok so patterns above might not be making sense. Please help. Now provide the response and nothing else.
To drop the message that does not contain the string xyz : if ([message] !~ "xyz") { drop { }} Your grok pattern is not grabbing the date part of your logs. Once you have a field from your grok pattern containing the date, you can invoque the date filter on this field. So your grok filter should look like this: grok { match => { "message" => '%{SYSLOG5424SD:loglevel} <%{JAVACLASS:job}> %{TIMESTAMP_ISO8601:Date} %{GREEDYDATA:content}' }} I added a part to grab the date, which will be in the field Date . Then you can use the date filter: date { match => [ "Date", "YYYY-mm-dd HH:mm:ss,SSS" ] locale => en} I added the ,SSS so that the format match the one from the Date field.The parsed date will be stored in the @timestamp field, unless specified differently with the target parameter.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38068657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3024519/']}
jdg_372594
stackexchange
llm_judgeable_groundtruth_similarity
158544
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I'm writing my thesis on the EPR paradox (I want to continue my master degree in physics) but I'm having an unusual problem. One passage from the book I'm following at the moment justifies one important passage saying that "a theorem proven by Von Neumann tells us" but, since it is far from obvious, I'd like to check the proof for some insight on the matter. The problem is: Von Neumann worked in a lot of fields, so I'm having a hard time figuring out which theorem is this. Any research failed me. It would be most helpful if someone recognized the result and pointed me in the right direction for a proof.So, without further ado here is the theorem as it is used in the book: let $H_1$ and $H_2$ be two Hilbert spaces (separable as it is common usage in QM, so we are treating with the space of square integrable functions) and let us have two complete basis of orthonormal states $\phi_i$ and $\psi_j$, one for each space. Let $\omega$ be an element of the direct product of these two spaces. The most general way to express $\omega$ would be $$\omega=\Sigma_{i,j}c_{ij}\phi_i\psi_j,$$where $\Sigma_{i,j}|c_{ij}|^2=1$. Now the theorem by Von Neumann says that we can find two other basis for $H_1$ and $H_2$ which I will denote by $\alpha_i$ and $\beta_j$ such that$$\omega=\Sigma_i c_i\alpha_i\beta_i,$$where of course $\Sigma_i|c_i|^2=1$.I apologize for my messy writing but I'm kinda technologically impaired, I hope you still managed to get the idea. Basically, it allows us to have a sum over one single index.As I said earlier, I don't want to bother too much so I don't ask for a proof, just for a nudge in the right direction. Thank you! Now provide the response and nothing else.
As noted by Dan Stahlke, this is precisely the singular value decompositon for compact (in this case Hilbert-Schmidt) operators, via the identification of an element $\omega$ of the Hilbert space tensor product $H_1\otimes H_2$ with such an operator $T$. The result can be deduced from the spectral theorem for the compact operator $T^\ast T$ just as in the finite dimensional case. Edit after Nik Weaver's answer. The correct statement of the result should talk about orthonormal sequences rather than bases.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/158544', 'https://mathoverflow.net', 'https://mathoverflow.net/users/47402/']}
jdg_372595
stackexchange
llm_judgeable_groundtruth_similarity
51391708
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 (Root) build.gradle Gradle Version is 3.1.3. (Root) build.gradle buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }} In project-structure the Gradle version is 4.4 Project-Structure Gradle version 4.4 In Gradle-wrapper-properties distributionUrl's, the Gradle version is 4.4 Gradle-Wrapper-Properties #Tue Jul 17 17:49:20 KST 2018distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distszipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip But I can build and I can run the application in the smartphone. What is the real Gradle version? Now provide the response and nothing else.
You need to be clear about three things here: Gradle Android Gradle Plugin Gradle Wrapper Specifically speaking, Gradle is a build tool which evolves independently of Android. Theoretically, Gradle can be used to build any kind of project, for example, a typical Java project, Android Project and even iOS project. It can also be integrated with any kind of IDE, for example, Android Studio , NetBeans , or Eclipse . By the time of writing, the latest Gradle version is 4.9, and you can always check its current version from Gradle installation guide . One of the great features of Gradle build tool is it supports Custom Plugins . Android Gradle Plugin The Android Gradle Plugin is one such Gradle custom plugin. For the typical Android project, the version of this plugin can be configured in the top-level build.gradle . buildscript { .... dependencies { classpath 'com.android.tools.build:gradle:3.1.3' } ....} For each version of this plugin, it requires a minimum Gradle version as listed in this page gradle-plugin or see below mapping table for a quick information: For example, Android Gradle Plugin version 3.1.0+ requires a minimal Gradle version 4.4 which can be configured via Android Studio. Gradle Wrapper . According to the official document Gradle Wrapper The recommended way to execute any Gradle build is with the help of the Gradle Wrapper (in short just “Wrapper”). The Wrapper is a script that invokes a declared version of Gradle, downloading it beforehand if necessary. As a result, developers can get up and running with a Gradle project quickly without having to follow manual installation processes saving your company time and money. This wrapper can be configured from gradle-wrapper.properties under your project directory. For example, distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip Or from the Android Studio GUI as said in your question: .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51391708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9147151/']}
jdg_372596
stackexchange
llm_judgeable_groundtruth_similarity
18254629
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 one item I want to always display in the action bar using the AppCompat library. It's just a sub menu using the default overflow image. This is not working for me on API levels v8-13 and I've done everything the developer guide says, including adding my own namespace. I'm using a custom style which has Theme.AppCompat as its parent (below). This is my first post so I don't have enough reputation points to post an image of the activity, but the item is missing from the action bar and the menu appears on the bottom when I press the menu button. Any feedback would be greatly appreciated!! AndroidManifest.xml: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myproject" android:installLocation="auto" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:debuggable="true" android:icon="@drawable/my_app_icon" android:label="@string/app_name" android:theme="@style/CustomActionBarTheme" > <uses-library android:name="com.google.android.maps" /> <activity android:name=".ui.MainActivity" android:label="@string/app_name" android:launchMode="singleTop" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest> menu.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:MyApp="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/overflow" MyApp:icon="@drawable/abc_ic_menu_moreoverflow_normal_holo_dark" MyApp:showAsAction="always" android:icon="@drawable/abc_ic_menu_moreoverflow_normal_holo_dark" android:showAsAction="always"> <menu> <item android:id="@+id/action_about" android:icon="@drawable/about_icon" android:title="About"/> <item android:id="@+id/action_feedback" android:icon="@drawable/feedback_icon" android:title="Feedback"/> <item android:id="@+id/action_settings" android:icon="@drawable/settings_icon" android:title="@string/action_settings"/> </menu> </item></menu> styles.xml <resources> <style name="CustomActionBarTheme" parent="@style/Theme.AppCompat"> <item name="android:actionBarStyle">@style/MyActionBar</item> <item name="actionBarStyle">@style/MyActionBar</item> </style> <style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar"> <item name="android:titleTextStyle">@style/TitleTextStyle</item> <item name="android:background">@drawable/abc_ab_bottom_solid_dark_holo</item> <item name="titleTextStyle">@style/TitleTextStyle</item> <item name="background">@drawable/abc_ab_bottom_solid_dark_holo</item> </style> <style name="TitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"> <item name="android:textStyle">bold</item> </style></resources> MainActivity.java package com.myproject;...public class MainActivity extends BaseActivity { public void onCreate(Bundle savedInstanceState) { super.onCreateEqually(savedInstanceState); ActivityHelper.setLayoutTitle(this, R.layout.main, R.string.main, getSupportActionBar()); } ...} BaseActivity.java package com.myproject;import android.support.v7.app.ActionBarActivity;...public class BaseActivity extends ActionBarActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public boolean onCreateOptionsMenu(Menu menu) { return true; } public boolean onPrepareOptionsMenu(Menu menu) { return MenusHelper.displayMenu(this, menu); } ...} MenusHelper.java package com.myproject;...public final class MenusHelper { ... public static boolean displayMenu(BaseActivity currentActivity, Menu menu) { // clear former menus menu.clear(); MenuInflater inflater = new MenuInflater(currentActivity); inflater.inflate(R.menu.menu, menu); return true; } ...} ActivityHelper.java package com.myproject;import android.support.v7.app.ActionBar;...public final class ActivityHelper { ... public static void setLayoutTitle(Activity activity, int layoutId, String titleStr, ActionBar actionBar) { activity.setContentView(layoutId); actionBar.setTitle(titleStr); actionBar.setDisplayHomeAsUpEnabled(true); }} Now provide the response and nothing else.
Try to put the code for MenusHelper.displayMenu(this, menu); into the onCreateOptionsMenu() rather than onPrepareOptionsMenu() and also do the necessary modification. @Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); // In case you have an item MenuItem shareItem = menu.findItem(R.id.menu_share); // To retrieve the Action Provider mActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem); return super.onCreateOptionsMenu(menu);} Make sure your Menu in your XML looks like this: <item android:id="@+id/share" android:title="@string/menu_share" yourapp:actionProviderClass="android.support.v7.widget.ShareActionProvider" yourapp:showAsAction="ifRoom|withText"/>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18254629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2684000/']}
jdg_372597
stackexchange
llm_judgeable_groundtruth_similarity
54744066
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 combine multiple GraphQL queries into one query using JavaScript. I am looking for something like this: let query3 = mergeQueries(query1, query2); We won't know beforehand which queries will be combined. Suppose I have queries like this: input query1: { post(id: 1234) { title description }} input query2: { post(id: 1234) { tags author { name } }} Then I would like the result query3 to be: result query3: { post(id: 1234) { title tags description author { name } }} This would be the same functionality as lodash _.merge() does for JSON objects, but then with GraphQL queries instead of JSON objects. Now provide the response and nothing else.
My answer is getting a bit to long for a comment so I decided to write a direct answer here. First I think both comments are really helpful. There is a solution that let's two queries share an HTTP request which might already be the optimisation you are looking for. Furthermore merging queries is not trivial. It requires a lot of effort to do this down to a field level. Not only fragments can make this difficult, you also have to take variables into account. As far as I know there is no solution publicly available to do that so you would have to do it yourself. Also I have not heard of a company that does this. I think that the fact that there is no solution is an indicator that it might not be worth it to do it. I can only guess your problem, but another way to reduce the amount of queries sent by a frontend application is to make use of fragments. While your fragments cannot have variables a healthy component structure will still fit very well with fragments: fragment PostHeader on Post { title description}fragment PostMeta on Post { tags author { name }}query { post(id: 1234) { ...PostHeader ...PostMeta }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54744066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1180612/']}
jdg_372598
stackexchange
llm_judgeable_groundtruth_similarity
14176180
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 follow along with the official Check tutorial , but it requires a working knowledge of Autotools, which I don't have. I was hoping just to write a couple quick tests, and I'm finding this tutorial overwhelming. It relies on a lot of magic in Autoconf, Automake, and some Check macros. It doesn't explain how Check actually works so that I could build tests by hand. How can I use Check without Autotools? Now provide the response and nothing else.
You certainly don't need to learn autotools to use Check in small projects.Let's say our main() is in main.c and our implementation.c have a function that sums 2 ints.(implementation.h contains just the function prototype) #include "implementation.h"int sum(int a, int b) { return a + b;} You can write a test like so: #include "implementation.h"#test sum2test fail_unless(sum(3, 2) == 5, "sum function borked"); fail_unless(sum(-3, 2) == -1, "sum function borked"); fail_unless(sum(3, -2) == 1, "sum function borked"); fail_unless(sum(-3, -2) == -5, "sum function borked"); Save the file in implementation-test.check (you can pick any name / extension you want, but stay with those if you want to follow my guide) and then run the included awk script that comes with Check. You don't even have to bother with the boilerplate code for the check framework! (for more details man checkmk) checkmk implementation-test.check >implementation-test.c The output will be the following: /* * DO NOT EDIT THIS FILE. Generated by checkmk. * Edit the original source file "implementation-test.check" instead. */#include <check.h>#line 1 "implementation-test.check"#include "implementation.h"START_TEST(sum2test){#line 4 fail_unless(sum(3, 2) == 5, "sum function borked"); fail_unless(sum(-3, 2) == -1, "sum function borked"); fail_unless(sum(3, -2) == 1, "sum function borked"); fail_unless(sum(-3, -2) == -5, "sum function borked");}END_TESTint main(void){ Suite *s1 = suite_create("Core"); TCase *tc1_1 = tcase_create("Core"); SRunner *sr = srunner_create(s1); int nf; suite_add_tcase(s1, tc1_1); tcase_add_test(tc1_1, sum2test); srunner_run_all(sr, CK_ENV); nf = srunner_ntests_failed(sr); srunner_free(sr); return nf == 0 ? 0 : 1;} Then just include -lcheck when you compile to get the check library linked in and run the program! gcc -Wall -o sum2ints-test implementation.c implementation-test.c -lcheck./sum2ints Below is a simple makefile to get you started. Save it in sum2ints.makefile and then to build the implementation.c along with main, run: make -f sum2ints.makefile To build & run the implementation.c with our implementation-test.c that got created from checkmk, run: make -f sum2ints.makefile test - CFLAGS=-WallLIBS=-lcheckall: sum2intssum2ints: main.o implementation.ogcc -o sum2ints main.o implementation.omain.o: main.c implementation.hgcc $(CFLAGS) -c main.cimplementation.o: implementation.c implementation.hgcc $(CFLAGS) -c implementation.ctest: sum2ints-test./sum2ints-testsum2ints-test: implementation-test.o implementation.ogcc -o sum2ints-test implementation.o implementation-test.o $(LIBS)implementation-test.o: implementation-test.c implementation.hgcc $(CFLAGS) -c implementation-test.c I've prepared a .zip file for you containing all the above. https://dl.dropbox.com/u/1987095/test-check.zip
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14176180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122763/']}
jdg_372599
stackexchange
llm_judgeable_groundtruth_similarity
77255
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 analyse the circuit below (from Art of Electronics, 2nd edition, p. 96). What are the small signal input and output impedance of this emitter follower? I can analyse an emitter follower, but I'm doing something wrong with the capacitor. Now provide the response and nothing else.
Here's how I would work out the input impedance. At the frequencies of interest, consider C2 to be a wire. Note then, that the output voltage appears at the bottom of R3 whilst the input voltage appears at the top. Let the voltage gain of this circuit be \$A_{CC} < 1\$. Then the voltage across R3 is \$v_{in} - A_{CC}\ v_{in} = v_{in}(1 - A_{CC})\$ The current through R3 is then \$\dfrac{v_{in}(1 - A_{CC})}{R_3} \$ Thus, to the input voltage source, R3 "looks" bigger by factor of \$\dfrac{1}{1 - A_{CC}} \$ Looking into the base of Q1, the impedance is approximately \$(1 + \beta)\ (R_4||R_2||R_1 + r_e) \$ where \$r_e = \frac{V_T}{I_E} \$. Then, the input impedance is: \$r_{in} = \dfrac{R_3}{1 - A_{CC}} || \left[(1 + \beta)\ (R_4||R_2||R_1 + r_e) \right] \$ Since the left hand term in the parallel combination is typically far larger than the right hand term, the input impedance is dominated by the right hand term, i.e., \$r_{in} \approx (1 + \beta)\ (R_4||R_2||R_1 + r_e)\$ For example, with \$V_T = 25mV\$ and \$I_E = 1mA\$, \$r_e = 25 \Omega \$ thus, with \$R_4||R_2||R_1 = 833 \Omega \$: \$r_{in} \approx (1 + \beta)\ 858 \Omega \$
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/77255', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/20250/']}
jdg_372600
stackexchange
llm_judgeable_groundtruth_similarity
64888613
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 pulled a docker image from https://github.com/snowflakedb/SnowAlert . But after pulling the Image, I don't see any containers running. I used docker container ls command and it returned no containers.Now due to some usecase I want to modify a file inside this docker image.What is the correct way to do it? Thanks Now provide the response and nothing else.
I think there's no way to do this at the preprocesing stage (at least not without some external scripts). On the other hand, there is a way to detect a function's signature at compiling time if you're using C11: _Generic . But remember: you can't use this in a macro like #if because primary expressions aren't evaluated at the preprocessing stage, so you can't dynamically choose to call the function with signature 1 or 2 in that stage. #define WEIRD_LIB_FUNC_TYPE(T) _Generic(&(T), \ int (*)(char *, char *, char *, bool, int): 1, \ int (*)(char *, char *, char *, bool): 2, \ default: 0)printf("test's signature: %d\n", WEIRD_LIB_FUNC_TYPE(test));// will print 1 if 'test' expects the extra argument, or 2 otherwise I'm sorry if this does not answer your question. If you really can't detect the version from the "stock" library header file, there are workarounds where you can #ifdef something that's only present in a specific version of that library. This is just a horrible library design. Update: after reading the comments, I should clarify for future readers that it isn't possible in the preprocessing stage but it is possible at compile time still. You'd just have to conditionally cast the function call based on my snippet above. typedef int (*TYPE_A)(char *, char *, char *, bool, int);typedef int (*TYPE_B)(char *, char *, char *, bool);int newtest(char *a, char *b, char *c, bool d, int e) { void (*func)(void) = (void (*)(void))&test; if (_Generic(&test, TYPE_A: 1, TYPE_B: 2, default: 0) == 1) { return ((TYPE_A)func)(a, b, c, d, e); } return ((TYPE_B)func)(a, b, c, d);} This indeed works although it might be controversial to cast a function this way. The upside is, as @pizzapants184 said, the condition will be optimized away because the _Generic call will be evaluated at compile-time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64888613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9349763/']}
jdg_372601
stackexchange
llm_judgeable_groundtruth_similarity
379758
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Assuming OldModule.oldFunc , if we want to move oldFunc to NewModule and, for backward compatibility, keep oldFunc there merely calling NewModule.newFunc by passing the exact same arguments and doing no tampering whatsoever -- do we need to still write unit tests for oldFunc ? Or will having unit tests for newFunc suffice? # Are unit tests still needed for oldFunc?OldModule.oldFunc(args){ return NewModule.newFunc(args)} Now provide the response and nothing else.
Luckily for you, since the function is not doing a lot, it would be easy to test it as well. A few seconds you'll spend adding a unit test is worth a potential loss of a few minutes if someone inadvertently modifies the function, or if the function breaks, affected by a change somewhere else. How could such a simple function possibly break? An example of a regression Let's take an example of a dynamically-typed language. You're in the middle of a refactoring for the last two weeks; some calls were already migrated to newFunc , and there are only a very few which still rely on oldFunc . New code is well tested, but oldFunc has no tests at all. Your colleague starts checking a bug report. It appears that it is related to a narrow piece of code in which, among others, newFunc is called. In order to fix the bug, your colleague decides to add an argument to newFunc : it's now newFunc(args, isSomething) and can be called by specifying either True or False for isSomething . Your colleague runs unit tests, and, one by one, corrects them by adding the missing parameter to the callers. The test suite is now all green, so he pushes the changes to production. A few minutes later, the phone starts ringing... Since you forgot to test oldFunc , the change wasn't caught up by the test suite. Your colleague introduced a regression because the code was untested . By simply looking at the code, your colleague had no clue that he needed to update oldFunc and all the callers of oldFunc . What to test? As you may guess, there is no need to write all unit tests of newFunc for oldFunc : tests of oldFunc should test only what the actual function is doing, not what some other function which is called is performing. This means that you should limit yourself to possibly one test. Further changes If the old function is kept only temporarily, you may—if the language has a support for it—decorate the function as obsolete to make the compiler produce a set of warnings for each location in the code which still uses the old function. The next step might be to replace the call to the new function by an exception, to catch a few locations where the function was called, without being caught by the compiler; the test will therefore be modified accordingly to check that the exception was thrown.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/379758', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/146378/']}
jdg_372602
stackexchange
llm_judgeable_groundtruth_similarity
155271
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: Suppose a system has two parts, $A$ & $B$. They were initially at different temperatures and hadn't achieved mechanical equilibrium . After attainting thermodynamic equilibrium , do they continue to exchange heat energy? ie. after attaining thermal equilibrium, ie. Is the heat that $A$ gains from $B$ the same as the heat gained by $B$ from $A$ so that the temperature remains constant ? Meaning to say, is thermodynamic equilibrium dynamic like chemical equilibrium? Or is it static? What is the reason for any of the two? Now provide the response and nothing else.
It is a dynamic equilibrium. To see this notice that the Boltzmann distribution law is statistical in nature, for instance, the molecules that have energies between $E_1$ and $E_1+\Delta E_1$ at time $t_1$ are not necessarily the same than the ones in between those same energies at time $t_2$. Particles collide (and thus exchange kinetic energy) all the time, and while the distribution stays the same, the particles that contribute to different parts of the distribution keep changing. Update:It is dynamic, like chemical equilibrium, because the molecules do not all have the same kinetic energy. If, at equilibrium, you randomly pick a molecule, there some probability (from the Boltzmann distribution) that it will have its energy between $E_1+\Delta E_1$. If after some time $\Delta t$ you pick those same molecules again, there is again the same probability to find those molecules with an energy between $E_1$ and $E_1+\Delta E_1$ is the same, but those same molecules will likely have a different energy than the one you measured earlier. this is because they molecules collide all the time and exchange energy with each other. From a macroscopic point of view the two states, at times $t_1$ and $t_1+\Delta t$, are the same; from a microscopic point of view, the two states are different. Thus it is a macroscopic equilibrium not a microscopic one. Same when have ice and water at equilibrium. The molecules that form part of the ice or part of the water keep changing all the time. At equilibrium, you keep the same amounts of water and ice, but the molecules that make up the ice and the water keep being exchanged between the ice and the water.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/155271', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_372603
stackexchange
llm_judgeable_groundtruth_similarity
429183
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following fictitious toy example: There is an aggregate root DayChecklist that holds a list of Tasks planned for the day: class DayChecklist { String id; DateTime today; ... List<Task> tasks; // lots of other business logic} Task itself is modeled as: abstract class Task { DateTime startTime; DateTime endTime; // lots of other common business logic} Let subtypes of Task be: TemperatureTask class TemperatureTask extends Task { double temperatureAtStart; double temperatureAtEnd; public recordStartingTemperature(double temperature) { // some business logic temperatureAtStart = temperature; } public recordEndingTemperature(double temperature) { // some business logic temperatureAtEnd = temperature; } ...} PressureTask class PressureTask extends Task { double pressureAtStart; double pressureAtEnd; public recordStartingPressure(double pressure) { // some business logic pressureAtStart = pressure; } public recordEndingPressure(double pressure) { // some business logic pressureAtEnd = pressure; } ...} Please assume that the Task subtypes have a lot of common business logic like state transitions (i.e. is-a relationship makes sense) and the AR and Tasks are behavior-rich models (i.e. DDD makes sense). What differs is some specific properties (like the temperature and pressure readings above). Now, when a Task needs to be updated (say recordStartingPressure() for a PressureTask), the update should ideally pass through the aggregate root. Does this mean that the aggregate root has a specific method defined for each subtask? In the example above, it is possible to have polymorphic recordStartReading and recordEndReading on the subtasks and the aggregate root could delegate such behavior. However, I am asking about the more general case when such polymorphism cannot easily be extracted. Also, what if it is certain that more Task types will be added in the future. Does that mean that corresponding methods also get added to the AR? This will violate OCP. Should some pattern be used for such a situation to allow extensibility? Thanks! Edit To highlight the crux of the problem, consider the following Task : PressureIntervalTask class PressureIntervalTask extends Task { List<Pair<DateTime, Double>> instantPressurePairs; public recordPressureAtInstant(double pressure, DateTime instant) { // some business rules instantPressurePairs.add(new Pair(instant, pressure)); } ...} Now, PressureIntervalTask has a method recordPressureAtInstant() that has a completely different signature. So, should the AR have a corresponding recordPressureAtInstant() method as well? Essentially, the Tasks can have metadata that can differ in terms of number of fields and their type. One extreme solution could be to model metadata as a JSON Object that the specific Task knows how to parse and apply. Then the AR could have a boolean applyMetadataUpdate(JSONObject metadata) and each Task can implement a polymorphic version, where the target Task may use a type identifier (for example) and return True if the update was handled/applied. Now provide the response and nothing else.
The problem here is that Tim Bray doesn't explain why he thinks it's not idempotent. The concept of idempotency is somewhat subjective. When we call a PUT twice there are a number of things that aren't the same as when we call it once. For example, the server access logs will be different as well as other logging. There might be other side effects to the PUT call as well such as events that are generated. But we explicitly choose to ignore certain factors. In a containerized, cloud-based solution (which was not really a thing in 2009), is restarting a container idempotent? Probably but if it's holding a local in-memory data that is not persisted anywhere, no, it's not. There are too many factors here to say it's always one or the other. Perhaps his point is that it's not, in general, the case that rebooting a server is idempotent. That doesn't mean it can't be, just that you can't assume it is.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/429183', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/368381/']}
jdg_372604
stackexchange
llm_judgeable_groundtruth_similarity
589033
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: When we train models, often we use the log of outputs in $(0,1)$ in our cost functions. Does anyone have a source that explains if this improves training? For example, supposed the cost is $f(\theta)=\sum_i{\delta_{y_i=1}\log\hat{y}_i}$ . I think I read somewhere that stretching $(0,1)$ to $(-\infty,0)$ helps learning. Does anyone have a reference? Now provide the response and nothing else.
There is a lot going on here, but this point may be useful: log loss is a "proper loss" or "proper scoring rule". Setup: suppose the classifier output $p$ is a probability distribution over $\mathcal{Y}$ , the possible labels. That is, rather than guessing one of the labels, our model outputs a posterior distribution over them. Suppose the true Bayes-optimal distribution is $p'$ . Then we want to use a loss $\ell(p,y)$ where setting $p=p'$ minimizes expected loss. This is the definition of "proper". Log loss is proper: $E_{y \sim p'} \ell(p,y) = - \sum_y p'(y) \log p(y), $ and you can check that the minimizing choice is $p=p'$ . (The expected loss expression is known as cross-entropy.) It would not be proper to, for example, use loss $\ell(p,y) = -p(y)$ . In this case you can check that $\sum_y p'(y) p(y)$ is not minimized by $p=p'$ , but instead by the delta distribution on the mode of $p'$ . In fact, log loss is the only proper loss of the form $\ell(p,y) = f(p(y))$ , i.e. the only proper loss that only depends on the probability assigned to the observation $y$ and not to the rest of the probabilities. Resource: https://stats.stackexchange.com/a/493949/70612
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/589033', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/96019/']}
jdg_372605
stackexchange
llm_judgeable_groundtruth_similarity
27090426
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 have a progress bar that updates inside an onAction block. For some reason in the following code, the progress bar doesn't update until it exits the onAction block. I get no progress for nine seconds and then 90%. The System.out prints just fine. package net.snortum.play;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.geometry.Insets;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.ProgressBar;import javafx.scene.layout.GridPane;import javafx.scene.layout.HBox;import javafx.scene.text.Text;import javafx.stage.Stage;public class ProgressBarTester extends Application { public static void main( String[] args ) { launch( ProgressBarTester.class, args ); } @Override public void start( final Stage stage ) throws Exception { final GridPane grid = new GridPane(); grid.setAlignment( Pos.CENTER ); grid.setHgap( 10 ); grid.setVgap( 10 ); grid.setPadding( new Insets( 25, 25, 25, 25 ) ); final Text title = new Text( "Test Progress Bar" ); int col = 0, row = 0, colSpan = 2, rowSpan = 1; grid.add( title, col, row, colSpan, rowSpan ); col = 0; row++; grid.add( new Label( "Progress:" ), col, row ); col = 1; final ProgressBar progress = new ProgressBar( 0.0 ); grid.add( progress, col, row ); final HBox hbox = new HBox(); hbox.setAlignment( Pos.BASELINE_RIGHT ); final Button submit = new Button( "Go" ); hbox.getChildren().add( submit ); col = 1; row++; grid.add( hbox, col, row ); submit.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle( ActionEvent event ) { double size = 10.0; for (double i = 0.0; i < size; i++){ progress.setProgress( i / size ); System.out.printf("Complete: %02.2f%n", i * 10); try { Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } } } } ); final Scene scene = new Scene( grid ); stage.setScene( scene ); stage.setTitle( "Test Progress Bar" ); stage.show(); }} Now provide the response and nothing else.
Long form of tomsomtom's precise answer: If you use the JavaFX Thread to do this kind of long term work, you stop the UI from updating etc. So you have to run your worker in a sparate thread. If you run in a separate Thread, all GUI operatione like progress.setProgress() have to be passed back to the JavaFX Thread using runLater() as JavaFX is not multithreaded. Try this in your Action: submit.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle( ActionEvent event ) { double size = 10.0; new Thread(){ public void run() { for (double i = 0.0; i < size; i++){ final double step = i; Platform.runLater(() -> progress.setProgress( step / size )); System.out.printf("Complete: %02.2f%n", i * 10); try { Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } } } }.start(); } } );
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27090426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/980967/']}
jdg_372606
stackexchange
llm_judgeable_groundtruth_similarity
50400007
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 least painful way to migrate state of resources from one project (i.e., move a module invocation) to another, particularly when using remote state storage? While refactoring is relatively straightforward within the same state file (i.e., take this resource and move it to a submodule or vice-versa), I don't see an alternative to JSON surgery for refactoring into different state files, particularly if we use remote (S3) state (i.e., take this submodule and move it to another project). Now provide the response and nothing else.
The least painful way I’ve found is to pull both remote states local, move the modules/resources between the two, then push back up. Also remember, if you’re moving a module, don’t move the individual resources; move the whole module. For example: cd dirAterraform state pull > ../dirA.tfstatecd ../dirBterraform state pull > ../dirB.tfstateterraform state mv -state=../dirA.tfstate -state-out=../dirB.tfstate module.foo module.footerraform state push ../dirB.tfstate# verify state was movedterraform state list | grep foocd ../dirAterraform state push ../dirA.tfstate Unfortunately, the terraform state mv command doesn’t support specifying two remote backends , so this is the easiest way I’ve found to move state between multiple remotes.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50400007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/510173/']}
jdg_372607
stackexchange
llm_judgeable_groundtruth_similarity
200228
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 imported three lists list1={{0.01, 0., 0.00242439}, {0.06, 0., 0.00228538}, {0.11, 0., 0.0018987}, {0.16, 0., 0.00148493}, {0.21, 0., 0.00104764}, {0.26, 0., 0.000575535}, {0.31, 0., 0.000068559}};list2={{0.01, 0., 0.00242439}, {0.06, 0., 0.00237076}, {0.11, 0., 0.00211971}, {0.16, 0., 0.001817}, {0.21, 0., 0.00150603}, {0.26, 0., 0.00118223}, {0.31, 0., 0.000839701}};list3={{0.01, 0., 0.00242439}, {0.06, 0., 0.00240639}, {0.11, 0., 0.00225701}, {0.16, 0., 0.00203365}, {0.21, 0., 0.00179651}, {0.26, 0., 0.00155504}, {0.31, 0., 0.00130653}}; I wish to add the third column of all lists with each other and keep unchanged two same columns. For example: result= {{0.01, 0., 0.00727317},{0.06, 0., 0.00706253},...} How do I reach this goal? Now provide the response and nothing else.
list4 = list1;list4[[All, 3]] = Total[{list1, list2, list3}[[All, All, 3]]];list4 {{0.01,0.,0.00727317},{0.06,0.,0.00706253},{0.11,0.,0.00627542},{0.16,0.,0.00533558},{0.21,0.,0.00435018},{0.26,0.,0.00331281},{0.31,0.,0.00221479}} Also KeyValueMap[Append]@Merge[Total][#[[;;2]]->#[[3]]&/@Join[list1,list2,list3]] same result
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/200228', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/33967/']}
jdg_372608
stackexchange
llm_judgeable_groundtruth_similarity
1137512
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 matrix multiplication by scalar commutative, i.e. $(\alpha M)N=M(\alpha N)$? If so, can we prove it without induction? Now provide the response and nothing else.
Yes. Let $L_{ij}$ be the $i,j$th component of $(\alpha M)N$, let $R_{ij}$ be the $i,j$th component of $M(\alpha N)$. $$(\alpha M)N=\begin{pmatrix}\alpha M_{11} &...& \alpha M{1m}\\...&...&...\\\alpha M_{n1} &...& \alpha M{nm}\end{pmatrix}\begin{pmatrix}N_{11}&...&N{1r}\\...&...&...\\N_{n1}&...&N_{nr}\end{pmatrix}$$ $$M(\alpha N)=\begin{pmatrix}\ M_{11} &...& M{1m}\\...&...&...\\M_{n1} &...& M{nm}\end{pmatrix}\begin{pmatrix}\alpha N_{11} &...& \alpha N{1m}\\...&...&...\\\alpha N_{n1} &...& \alpha N{nm}\end{pmatrix}$$ Now write out $L_{ij}$ and $R_{ij}$. They are the same.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1137512', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/192929/']}
jdg_372609
stackexchange
llm_judgeable_groundtruth_similarity
25566
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: ssh-keygen defaults to RSA (for SSH protocol 2) and a 2048 bit key. At this description of ssh The supported ciphers are: 3des-cbc, aes128-cbc, aes192-cbc, aes256-cbc, aes128-ctr, aes192-ctr, aes256-ctr, arcfour128, arcfour256, arcfour, blow- fish-cbc, and cast128-cbc. The default is: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128, arcfour256,arcfour,aes192-cbc,aes256-cbc,aes128-ctr, aes192-ctr,aes256-ctr Thus it appears ciphers are either 128 or 256 bit, if I infer from unitless numbers. What is the justification for the ciphers being shorter than the key? Now provide the response and nothing else.
That's the key length for RSA (asymetric encryption). It is used to establish the identity of the server and perform authentication and symmetric key exchange. It does not perform encryption of the connection. The ciphers you depicted above are all symmetric, these are used to encrypt the connection. At least for AES I'm sure the maximum key length is 256 bits. To give you a basic idea of how SSH works: Generate a random session key Encrypt this session key with the servers public and your private certificate server decrypts the session key and a symmetric encryption is set up between the client and the server to send the data over. Since it is encrypted with the server's public key, only the server can read it. Since it is encrypted with your private certificate, the server knows it must have come from you (or more accurately the holder of the corresponding private key.) If you want more information, there is a really nice explanation here .
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/25566', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/4606/']}
jdg_372610
stackexchange
llm_judgeable_groundtruth_similarity
4348524
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: 1 import subprocess 2 raw = raw_input("Filename:").lower() 3 ip = raw_input("Host:").lower() 4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + " raw " + " ip ",shell=True) So this is my script. I everything works besides one key objective, using the raw input.It allows me to input anything i want, but when it goes to saving the file or using an ip/host doe doesn't actually do anything.Sure it gives me the packets, but from the localhost not the host i type in. how i know this isn't working is cause my first raw input is the filename, so i put in test, when i look in the folder were my script is, it produces a file called "raw" meaning, its not actually taking my input only using whats inside my "X"... So i make a few chances to come to this: 1 import subprocess 2 raw = raw_input("Filename:").lower() 3 ip = raw_input("Host:").lower() 4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw + "host" + ip,shell=True) Which is great because it actually calls for the -w but it saves it now as rawhostip instead of "raw"s input. for reference this is what the command looks like in the terminal: tcpdump -c5 -vvv -w savename host wiki2 the only two variabls are savename and wiki2 the rest are needed for the command to work. with this script i get this error: import subprocessraw = raw_input("Filename:").lower()ip = raw_input("Host:").lower()cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw, "host" + ip,shell=True) Error: Traceback (most recent call last): File "te.py", line 4, in <module> cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw, "host" + ip,shell=True) File "/usr/lib/python2.6/subprocess.py", line 480, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.6/subprocess.py", line 583, in __init__ raise TypeError("bufsize must be an integer")TypeError: bufsize must be an integer I am at a lost. Any help will be great, yes I know look at subprocess's doc's on site:X, I have I need a human to teach me, I don't understand what I am reading. My question is how do I work with these variables. Now provide the response and nothing else.
Don't use shell=True . That should be False . You are making subtle mistakes with the input. Specifically, if you have two strings: >>> s1 = 'Hello'>>> s2 = 'Hi'>>> s1 + s2'HelloHi' Notice, there is no space between Hello and Hi . So don't do this. (Your line 4) You should do (the good way): >>> raw = raw_input('Filename: ')Filename: test>>> ip = raw_input('Host: ')Host: 192.168.1.1 >>> command = 'tcpdump -c5 -vvv -w {0} {1}'.format(raw, ip) # the command goes here>>> subprocess.call(command.split(), shell=False) # call subprocess and pass the command as a list using split Now it should work.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4348524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/525576/']}
jdg_372611
stackexchange
llm_judgeable_groundtruth_similarity
46648
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have a few really basic questions about minimal surfaces. Does a smooth or piecewise smooth injection $S^1$ into $\mathbb R^3$ always give a unique minimal surface or are there instances with discrete distinct solutions? Can it not be the case that a 1-parameter family of minimal surfaces exists for a given "frame"? Do linear maps preserve minimal surfaces? I'm guessing no, but I don't have a good example in mind. Also, if I have a simplicial decomposition of $S^1$ and map it into $\mathbb R^3$ with a simplicial map, is it known that there is a unique minimal surface spanning this piecewise linear frame? Is the formula readily given? These questions came up defining a surface $f(s,t)=(1-s)(1-t)v_0+(1-s)tv_1+s(1-t)v_3+stv_4$to interpolate the simplicial map defined by $f(0,0)=v_0, f(0,1)=v_1, f(1,1)=v_2, f(1,0)=v_3$ which maps $\partial I^2$ into $\mathbb R^3$. I believe this surface is minimal, and wonder how this works for polygons with more vertices than the square. Thanks Now provide the response and nothing else.
In $\mathbb{R}^3$ there is always some minimal surface spanning a given connected simple curve (assuming the curve is not too horrible, say Lipschitz). Here surface needs to be broadly understood as being possibly immersed and of arbitrary topology. This can be seen using the machinery of geometric measure theory and the direct method in the calculus of variations (i.e. by minimizing area). Alternatively, since there is a close connection to harmonic mappings in this context, one can always find a minimal surface spanning the curve that is topologically a disk (this is sometimes referred to as the Douglas-Rado solution). This is also constructed by direct methods but here one minimizes Dirichlet energy of the map. If you know more about the bounding curve one can get more information about possible minimal surfaces spanning the curve. For instance if the curve lies on the boundary of a convex set then it spans at least one embedded minimal surface. In general there is no uniqueness (there are in fact an example due to F. Morgan where a given curve bounds a continuum of minimal surfaces). Though if you know that the bounding curve is analytic and of total geodesic curvature less than $4\pi$ then Nitsche shows that the curve bounds a unique minimal disk (I don't remember if it can also bound surfaces of other topological types). In general I doubt you could get an explicit parameterization for the surface even if the curve is simplicial. Though you might be able to get something if you look at the Enneper-Weierstrass representation.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/46648', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2031/']}
jdg_372612
stackexchange
llm_judgeable_groundtruth_similarity
66676630
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 DataFrame like the below one, with identifiers as a column on top of an existing dateindex. pd.DataFrame(index = [pd.to_datetime('2021-01-01'), pd.to_datetime('2021-01-01'),pd.to_datetime('2021-01-02'),pd.to_datetime('2021-01-02'), pd.to_datetime('2021-01-03'),pd.to_datetime('2021-01-03')], columns=['id','A', 'B'], data=[['foo',1,5],['bar',8,12],['foo',7,1], ['bar',5,1], ['foo',4,3],['bar',7,1]])Out[6]: id A B2021-01-01 foo 1 52021-01-01 bar 8 122021-01-02 foo 7 12021-01-02 bar 5 12021-01-03 foo 4 32021-01-03 bar 7 1 My goal is to create a new sub-dataframes for each of the columns (A and B) except id, with dateIndex as single Index, and id (foo, bar) as column names. The expected output is shown below: AOut[9]: foo bar2021-01-01 1 82021-01-02 7 52021-01-03 4 7BOut[11]: foo bar2021-01-01 5 122021-01-02 1 12021-01-03 3 1 Now provide the response and nothing else.
A, B = map(df.set_index('id', append=True).unstack().get, ['A', 'B'])print(A)id bar foo2021-01-01 8 12021-01-02 5 72021-01-03 7 4print(B)id bar foo2021-01-01 12 52021-01-02 1 12021-01-03 1 3
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66676630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4449593/']}
jdg_372613
stackexchange
llm_judgeable_groundtruth_similarity
36622871
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 running integration tests for my Spring Boot application with Maven's Failsafe plugin. When I create a simple test such as this one: @RunWith (SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(App.class)public class MyTestIT { @Test public void test() { assertTrue (true); }} And then run mvn verify I see the following log entries just before the Spring application starts (e.g. even before the Spring Boot banner): Running org.....MyTestIT2016-04-14 13:25:01.166 INFO ???? --- [ main] or.sp.te.co.su.AbstractContextLoader : Could not detect default resource locations for test class [org....MyTestIT]: no resource found for suffixes {-context.xml, Context.groovy}.2016-04-14 13:25:01.175 INFO ???? --- [ main] or.sp.te.co.su.DefaultTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]2016-04-14 13:25:01.185 INFO ???? --- [ main] or.sp.te.co.su.DefaultTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@57c758ac, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@a9cd3b1, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@13e39c73, org.springframework.test.context.support.DirtiesContextTestExecutionListener@64cd705f, org.springframework.test.context.transaction.TransactionalTestExecutionListener@9225652, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@654f0d9c] Followed by the Spring Boot banner. The tests then run through without any error. While these messages are printed with an INFO log level and the tests run fine, I guess everything is fine, but I still find these messages irritating. So is there something wrong with my configuration? Should I worry about these messages? Even if there was nothing wrong, I would still like to understand whats happending there and what the messages mean. My maven-failsafe-plugin is just using the default configuration and my App.java is just a simple class annotated with @SpringBootApplication . UPDATE 1: Here is the configuration of my test plugins: <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- Ignore any tests that are marked by the @IntegrationTest annotation of Spring Boot --> <excludedGroups>org.springframework.boot.test.IntegrationTest</excludedGroups> </configuration> </plugin> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <version>2.19.1</version> <executions> <execution> <id>integration-test</id> <goals> <goal>integration-test</goal> </goals> </execution> </executions> </plugin> I also have a spring-boot-starter-test dependency configured and I am using spring-boot-devtools . Besides that everything else is not test related. The project it self is pretty standard, using hibernate and mysql and web-mvc for rest endpoints. I have two configuration classes for spring security on the class pass. In the main/resources folder I have an application.properties file and a log4j2.xml. There is no test/resources folder, but when I just copy the main/resources folder to test/resources the above log messages still appear. UPDATE 2: I just created a small sample application trying to recreate the issue, and it seems the mentioned log-output starts to appear as soon as I put a log4j2.xml file into a resources folder. I tried putting it in src/main or src/test or both with identical effects. Now provide the response and nothing else.
This is the default behaviour when running Spring integration tests. From the reference documentation If you omit both the locations and value attributes from the @ContextConfiguration annotation, the TestContext framework will attempt to detect a default XML resource location. Specifically, GenericXmlContextLoader and GenericXmlWebContextLoader detect a default location based on the name of the test class. If your class is named com.example.MyTest, GenericXmlContextLoader loads your application context from "classpath:com/example/MyTest-context.xml". So, it's not related whatsoever to Maven, log4j or the positioning/assistance of resource folder. Should I worry about these messages? Not at all, apparently. but I still find these messages irritating Don't know if and how to turn off that check (Course you can eliminate it by changing the log level of AbstractContextLoader to WARN ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36622871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474034/']}
jdg_372614
stackexchange
llm_judgeable_groundtruth_similarity
6936720
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 know that a temporary cannot be bound to a non-const reference, but it can be bound to const reference. That is, A & x = A(); //error const A & y = A(); //ok I also know that in the second case (above), the lifetime of the temporary created out of A() extends till the lifetime of const reference (i.e y ). But my question is: Can the const reference which is bound to a temporary, be further bound to yet another const reference, extending the lifetime of the temporary till the lifetime of second object? I tried this and it didn't work. I don't exactly understand this. I wrote this code: struct A{ A() { std::cout << " A()" << std::endl; } ~A() { std::cout << "~A()" << std::endl; }};struct B{ const A & a; B(const A & a) : a(a) { std::cout << " B()" << std::endl; } ~B() { std::cout << "~B()" << std::endl; }};int main() { { A a; B b(a); } std::cout << "-----" << std::endl; { B b((A())); //extra braces are needed! }} Output ( ideone ): A() B()~B()~A()----- A() B()~A()~B() Difference in output? Why the temporary object A() is destructed before the object b in the second case? Does the Standard (C++03) talks about this behavior? Now provide the response and nothing else.
The standard considers two circumstances under which the lifetime of a temporary is extended: §12.2/4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the temporary that holds the result of the expression shall persist until the object’s initialization is complete. [...] §12.2/5 The second context is when a reference is bound to a temporary. [...] None of those two allow you to extend the lifetime of the temporary by a later binding of the reference to another const reference. But ignore the standarese and think of what is going on: Temporaries are created in the stack. Well, technically, the calling convention might mean that a returned value (temporary) that fits in the registers might not even be created in the stack, but bear with me. When you bind a constant reference to a temporary the compiler semantically creates a hidden named variable (that is why the copy constructor needs to be accessible, even if it is not called) and binds the reference to that variable. Whether the copy is actually made or elided is a detail: what we have is an unnamed local variable and a reference to it. If the standard allowed your use case, then it would mean that the lifetime of the temporary would have to be extended all the way until the last reference to that variable. Now consider this simple extension of your example: B* f() { B * bp = new B(A()); return b;}void test() { B* p = f(); delete p;} Now the problem is that the temporary (lets call it _T ) is bound in f() , it behaves like a local variable there. The reference is bound inside *bp . Now that object's lifetime extends beyond the function that created the temporary, but because _T was not dynamically allocated that is impossible. You can try and reason the effort that would be required to extend the lifetime of the temporary in this example, and the answer is that it cannot be done without some form of GC.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6936720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415784/']}
jdg_372615
stackexchange
llm_judgeable_groundtruth_similarity
199972
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: The question I'm working on is as follows: "In $62894\_52$, the hundreds place digit is missing. If $48 \mid 62894\_52$, find the missing digit." I'm not really sure how to solve a problem like this. What I have so far is $48=3*2^4$, so $3\mid62894\_52$ and $2^4\mid62894\_52$. I don't know what to do next though. Can somebody give me a hint or point me to a Wikipedia page?Thanks in advance! Now provide the response and nothing else.
Here's a hint: since 16 divides 2000 evenly, $16 \mid 62894\_52$ is equivalent to $16 \mid \_52$. First find out what hundredths digits will satisfy this; helpful is the fact that 16 doesn't divide 100 or 200 evenly, but $16 \mid 400$. Then, use the fact that $3 \mid 62894\_52$ exactly when the digits of $62894\_52$ add up to a multiple of three to eliminate all but one of your possibilities for the missing digit.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/199972', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35731/']}
jdg_372616
stackexchange
llm_judgeable_groundtruth_similarity
9107384
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Many Comet implementations like Caplin provide server scalable solutions. Following is one of the statistics from Caplin site: A single instance of Caplin liberator can support up to 100,000 clients each receiving 1 message per second with an average latency of less than 7ms. How does this to compare to HTML5 websockets on any webserver? Can anyone point me to any HTML 5 websockets statistics? Now provide the response and nothing else.
Disclosure - I work for Caplin. There is a bit of misinformation on this page so I'd like to try and make it clearer.. I think we could split up the methods we are talking about into three camps.. Comet HTTP polling - including long polling Comet HTTP streaming - server to client messages use a single persistent socket with no HTTP header overhead after initial setup Comet WebSocket - single bidirectional socket I see them all as Comet, since Comet is just a paradigm, but since WebSocket came along some people want to treat it like it is different or replaces Comet - but it is just another technique - and unless you are happy only supporting the latest browsers then you can't just rely on WebSocket. As far as performance is concerned, most benchmarks concentrate on server to client messages - numbers of users, numbers of messages per second, and the latency of those messages. For this scenario there is no fundamental difference between HTTP Streaming and WebSocket - both are writing messages down an open socket with little or no header or overhead. Long polling can give good latency if the frequency of messages is low. However, if you have two messages (server to client) in quick succession then the second one will not arrive at the client until a new request is made after the first message is received. I think someone touched on HTTP KeepAlive. This can obviously improve Long polling - you still have the overhead of the roundtrip and headers, but not always the socket creation. Where WebSocket should improve upon HTTP Streaming in scenarios where there are more client to server messages. Relating these scenarios to the real world creates slightly more arbitrary setups, compared to the simple to understand 'send lots of messages to lots of clients' which everyone can understand. For example, in a trading application, creating a scenario where you include users executing trades (ie client to server messages) is easy, but the results a bit less meaningful than the basic server to client scenarios. Traders are not trying to do 100 trades/sec - so you end up with results like '10000 users receiving 100 messages/sec while also sending a client message once every 5 minutes'. The more interesting part for the client to server message is the latency, since the number of messages required is usually insignificant compared to the server to client messages. Another point someone made above, about 64k clients, You do not need to do anything clever to support more than 64k sockets on a server - other than configuring the number file descriptors etc. If you were trying to do 64k connection from a single client machine, that is totally different as they need a port number for each one - on the server end it is fine though, that is the listen end, and you can go above 64k sockets fine.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9107384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149190/']}
jdg_372617
stackexchange
llm_judgeable_groundtruth_similarity
41073
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: The astrophysicist Neil deGrasse Tyson has said that during the Islamic Golden Age, especially in Baghdad, science and discovery flourished for a few centuries. Then an Islamic scholar named al-Ghazali became prominent, whose ideas took root. Among these was something along the lines that mathematics was, to use Tyson's words "the work of the devil". I've listened to many of Tyson's talks, and he's mentioned this many times. Today I came across the Wikipedia article for al-Ghazali and thought I'd spend some time reading about him. He was a rather influential Islamic scholar in many ways, but specific to the claim that his philosophy led to the decline of science within the Islamic world, I only found the following: His reforms are widely seen as having initiated the decline of scientific research in the Islamic world.[by whom?][citation needed] Against this view, Saliba (2007) has given a number of examples especially of astronomical research flourishing after the time of al-Ghazali Wikipedia article Here is a video of Tyson making this claim. Sorry about the disputatious annotations made by the poster, but this was the first result I got for "Tyson al-Ghazali". Is there any evidence that al-Ghazali said something like manipulating numbers or math is the work of the devil, or maybe sinful, or immoral? And as corollary to that, did he damage the spirit of scientific inquiry in the Islamic world? Here is a quote written from one of the versions, found in video link 2 below: "And in that interpretation (al-Ghazali's) it included the perspective that the manipulation of numbers is the work of the Devil. This cuts the kneecaps out of any mathematical advances that would unfold." Links to other occasions he's said this before, here are two: video 1 video 2 Edit: OK, I'm pretty sure I know what happened. Steven Weinberg is a physics Nobel laureate and acquaintance of Neil Tyson. Steven Weinberg is critical of religion, and has written: "Alas, Islam turned against science in the twelfth century. The most influential figure was the philosopher Abu Hamid al-Ghazali, who argued in The Incoherence of the Philosophers against the very idea of laws of nature, on the ground that any such laws would put God’s hands in chains. According to al-Ghazali, a piece of cotton placed in a flame does not darken and smoulder because of the heat, but because God wants it to darken and smoulder. After al-Ghazali, there was no more science worth mentioning in Islamic countries." Here is a video of Weinberg explaining this, just before Neil deGrasse Tyson comes to the podium to do his talk. It's possible that Neil Tyson's explanation of al-Ghazali has come from what Weinberg has told him. Now provide the response and nothing else.
This is an old myth from the days of Orientalism. Unfortunately Wikipedia is often edited precisely by people who have simply seen popular accounts by people like Tyson (or Skeptoid podcast , or The New Atlantis ) produced with no understanding of the history of science or human thought. The fact is that Ghazzālī nowhere professed that reason or knowledge is useless. On the contrary, he tried to construct a better model of human reason and natural knowledge than past philosophers, hence the title of his book The Incoherence of the Philosophers . The "philosophers" in the title are literally "lovers of knowledge" (φιλόσοφος) from the Platonic tradition; Ghazzālī is not criticizing knowledge itself. In the words of a historian of philosophy, Ghazali makes it plain that his purpose is to refute the Islamicphilosophers' metaphysical theories and not their natural science. [...] Indeed, the misguided zealot who attacks science in the mistaken belief that he is defending religion, inflicts damage, not on science, but on religion. He inflicts this damage, Ghazali argues, precisely because science is demonstrable and certain. If it does, in fact, contradict religion, then it is the latter that becomes suspect and not science. Michael Marmura, " Ghazali and Demonstrative Science ." Journal of the History of Philosophy , Volume 3, Number 2, October 1965, pp. 183-204 Or to quote Ghazzālī's own words, The greatest thing in which the atheists rejoice is for the defender of religion to declare [that the results of an astronomical observation] are contrary to religion. Thus, the [atheists'] path for refuting religion becomes easy if the likes [of such an argument] are rendered a condition [for its truth]. Quoted in Basit Bilal Koshul, " Ghazzālī, Ibn Rushd and Islam's Sojourn into Modernity: A Comparative Analysis " Islamic Studies Vol. 43, No. 2 (Summer 2004), pp. 207-225 Ghazzālī lived from 1058 to 1111 AD. His critique of religionists' blind devotion to Aristotelian metaphysics would emerge in France over a century later (the famous Condemnations of 1210 and 1277 ). A history of science writer and evangelical Christian, Richard P. Aulie , suggests a causal connection between the two events: The place of al-Ghazali in the rise of modern science is distinct and of consequence. It lies in his opposition to major portions of Aristotelian thought and that by means of his theistic affirmation of creation. For him, creation meant a coming into being; the creation was an expression of the divine will; for him, coming into being meant that the creation was separate from the creator. By his affirmation of creation and rejection of eternality he helped to lodge an ineluctable doubt at the heart of Aristotelian thought. ... [T]his affirmation of faith was bequeathed by Islam to Christianity in the later Middle Ages, to become integral to the rise of science during the Renaissance. Richard P. Aulie, " Al-Ghazali Contra Aristotle: An Unforeseen Overture to Science In Eleventh-Century Baghdad ". Perspectives on Science and Christian Faith vol. 45 (March 1994): 26-46. It's completely anachronistic, not to mention philosophically dubious, to object to Ghazzālī's philosophy on the grounds that he gave too much weight to theology and divine revelation. One might as well object to Thomas Aquinas or Duns Scotuson these grounds. Like Aquinas and Scotus, Ghazzālī's intent was not to describe natural mechanisms, but to give an accurate account of human reason and its relationship to the world. His work is frequently compared to Descartes, although they have great differences over epistemology . He is also compared to Kant and Wittgenstein, namely: While Ghazzālī does not state the issue in such terms, the fundamental mistake made by the philosophers is that they conflate the results of logical reasoning with empirical reality. Centuries before Wittgenstein, Ghazzālī argues that in doing so philosophy violates its own rules and trespasses on a domain over which it has no jurisdiction. Koshul, "Ghazzālī, Ibn Rushd and Islam's Sojourn into Modernity" One blogger named Ibrahim Arsalan has responded directly to Tyson , writing: The dispute Al Ghazali would have with the philosophers and thatAverroes would have with him [is] over the nature of Aristotlelian metaphysics,not the demonic nature of scientific thought. Such an attack on AlGhazali by Tyson is laughable considering he furthered the developmentof secular methodology and would later be praised by European secularthinkers who Tyson is so eager to praise. Also, Tyson is in error whenhe says of Al Ghazali, “… out of his work, you get the philosophy thatmathematics is the work of the Devil”. Al Ghazali actually called thesciences and mathematics of his day mamduh (praiseworthy) adding,“…because of their absence, the community would be reduced to narrowstraits.” You can learn more about Ghazzālī on this podcast: History of Philosophy without any gaps . That podcast also covers the full spectrum of Islamic philosophy in his time and after him.
{}
{'log_upvote_score': 8, 'links': ['https://skeptics.stackexchange.com/questions/41073', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/44231/']}
jdg_372618
stackexchange
llm_judgeable_groundtruth_similarity
20781
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 want to build a little project to track an objects position in space. For this I intend to use an accelerometer and a gyroscope. The problem is I want this tracking to be very precise, and I haven't been able to figure out how precise you can actually get (for a fair amount of money). Are we talking 1 centimeter, or centimeters / 1000 ? The specific combination I'm looking to buy is from SparkFun: IMU Fusion Board - ADXL345 & IMU3000 But I'm more interested in a general answer, as I could go with other combinations. Maybe just a general guideline of how to determine it from the specs. Now provide the response and nothing else.
As Rocketmagnet mentioned your error is going to grow with time. The error model typically used in inertial navigation is an exponential growth. To minimize this you must provide external updates. The mechanism typically employed is a Kalman Filter. The inertial sensors provide very good high rate updates. Your external source provides less accurate but long term stable updates at a lower rate (typically something like GPS). These two combine to give you a good combined solution. Not all systems use GPS as the update source. For instance, the IR imager on the front of the Nintendo Wii remote provides the source of these updates. I'll give you an example of the cost is no factor side of things. I build systems for aerial surveying that utilize inertial systems that cost 100,000+ Euro. With these systems and high end geodetic GPS receivers I can pin-point the location of the IMU to a 2" volume all day long when GPS coverage is good. In the absence of GPS updates (urban canyons, tunnels, etc.) after about 60 seconds we have an error margin of about 10cm. Systems with this level of performance are typically ITAR controlled goods as they are weapons grade devices. Lower quality MEMS inertial systems are used all day long in less demanding applications yielding meter sub-meter level position and attitude. These lower quality systems still employ the same Kalman Filtering mechanism. The real downside to these lower cost units is that your drift error will grow at a much faster rate. Edit: To answer your question as to what is important to look for in an IMU. There are a couple of things you want to look at. The first is temperature stability. Some MEMS sensors are going to have outputs that vary by as much as 10% over temperature range. These may not matter if you are at a constant temperature during operation. The next thing to consider is the gyro noise spectral density. Obviously the lower the noise amount the better. The following link provides documentation about how to get from the spectral noise density to the drift (in degrees per unit time). http://www.xbow.com/pdf/AngleRandomWalkAppNote.pdf For acceleration you want to look at sensitivity, and bias in addition to the noise. The noise level will give you an idea of how quickly you're going to integrate error.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/20781', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6113/']}
jdg_372619
stackexchange
llm_judgeable_groundtruth_similarity
331611
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: Is there an official POSIX, GNU, or other guideline on where progress reports and logging information (things like "Doing foo; foo done") should be printed? Personally, I tend to write them to stderr so I can redirect stdout and get only the program's actual output. I was recently told that this is not good practice since progress reports aren't actually errors and only error messages should be printed to stderr. Both positions make sense, and of course you can choose one or the other depending on the details of what you are doing, but I would like to know if there's a commonly accepted standard for this. I haven't been able to find any specific rules in POSIX, the GNU coding standards, or any other such widely accepted lists of best practices. We have a few similar questions, but they don't address this exact issue: When to use redirection to stderr in shell scripts : The accepted answer suggests what I tend to do, keep the program's final output on stdout and anything else to stderr. However, this is just presented as a user's opinion, albeit supported by arguments. Should the usage message go to stderr or stdout? : This is specific to help messages but cites the GNU coding standard. This is the sort of thing I'm looking for, just not restricted to help messages only. So, are there any official rules on where progress reports and other informative messages (which aren't part of the program's actual output) should be printed? Now provide the response and nothing else.
Posix defines the standard streams thus : At program start-up, three streams shall be predefined and need not be opened explicitly: standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). When opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device. The GNU C Library describes the standard streams similarly: Variable: FILE * stdout The standard output stream, which is used for normal output from the program. Variable: FILE * stderr The standard error stream, which is used for error messages and diagnostics issued by the program. Thus, standard definitions have little guidance for stream usage beyond “conventional/normal output” and “diagnostic/error output.” In practice, it’s common to redirect either or both of these streams to files and pipelines, where progress indicators will be a problem. Some systems even monitor stderr for output and consider it a sign of problems. Purely auxiliary progress information is therefore problematic on either stream. Instead of sending progress indicators unconditionally to either standard stream, it’s important to recognize that progress output is only appropriate for interactive streams. With that in mind, I recommend writing progress counters only after checking whether the stream is interactive (e.g., with isatty() ) or when explicitly enabled by a command-line option. That’s especially important for progress meters that rely on terminal update behavior to make sense, like %-complete bars. For certain very simple progress messages (“Starting X” ... “Done with X”) it’s more reasonable to include the output even for non-interactive streams. In that case, consider how users might interact with the streams, like searching with grep or paging with less or monitoring with tail -f . If it makes sense to see the progress messages in those contexts, they will be much easier to consume from stdout .
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/331611', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/22222/']}
jdg_372620
stackexchange
llm_judgeable_groundtruth_similarity
32122679
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 developed a function which returns the icon of the window for a given window handle. It looks like this. private static BitmapSource GetWindowIcon(IntPtr windowHandle){ var hIcon = default(IntPtr); hIcon = SendMessage(windowHandle, WM_GETICON, ICON_BIG, IntPtr.Zero); if (hIcon == IntPtr.Zero) hIcon = GetClassLongPtr(windowHandle, GCL_HICON); if (hIcon == IntPtr.Zero) { hIcon = LoadIcon(IntPtr.Zero, (IntPtr)0x7F00/*IDI_APPLICATION*/); } if (hIcon != IntPtr.Zero) { return Imaging.CreateBitmapSourceFromHIcon(hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } else { throw new InvalidOperationException("Could not load window icon."); }} I use this function in combination with GetForegroundWindow to get the icon of the active window. However, it seems to produce the same dull looking icon for universal apps. Is it possible to somehow fetch the tile image or icon from a universal app that is running? Now provide the response and nothing else.
Here is some sample code demonstrating how this could be done. Note that: You should run this evelated, otherwise you won't be able to access folder with application resources (I think, didn't really check myself, because to investigate things I granted myself access to that folder). Modern apps are running under ApplicationFrameHost host process. You will need some tricks to get to the actual executable (like Calculator.exe), those tricks are commented in code. Modern app manifest contains path to logo, but there might be several logos (black, white, constract white as an example). You will need some logic to choose one. Didn't investigate this myself in details. I tested this on Calculator app in Windows 10 and it worked fine. However of course more tests with more apps are required to ensure all is fine. Here is the code: public static class IconHelper { public static BitmapSource GetForegroundWindowIcon() { var hwnd = GetForegroundWindow(); uint pid; GetWindowThreadProcessId(hwnd, out pid); Process proc = Process.GetProcessById((int) pid); // modern apps run under ApplicationFrameHost host process in windows 10 // don't forget to check if that is true for windows 8 - maybe they use another host there if (proc.MainModule.ModuleName == "ApplicationFrameHost.exe") { // this should be modern app return GetModernAppLogo(hwnd); } return GetWindowIcon(hwnd); } public static BitmapSource GetModernAppLogo(IntPtr hwnd) { // get folder where actual app resides var exePath = GetModernAppProcessPath(hwnd); var dir = System.IO.Path.GetDirectoryName(exePath); var manifestPath = System.IO.Path.Combine(dir, "AppxManifest.xml"); if (File.Exists(manifestPath)) { // this is manifest file string pathToLogo; using (var fs = File.OpenRead(manifestPath)) { var manifest = XDocument.Load(fs); const string ns = "http://schemas.microsoft.com/appx/manifest/foundation/windows10"; // rude parsing - take more care here pathToLogo = manifest.Root.Element(XName.Get("Properties", ns)).Element(XName.Get("Logo", ns)).Value; } // now here it is tricky again - there are several files that match logo, for example // black, white, contrast white. Here we choose first, but you might do differently string finalLogo = null; // serach for all files that match file name in Logo element but with any suffix (like "Logo.black.png, Logo.white.png etc) foreach (var logoFile in Directory.GetFiles(System.IO.Path.Combine(dir, System.IO.Path.GetDirectoryName(pathToLogo)), System.IO.Path.GetFileNameWithoutExtension(pathToLogo) + "*" + System.IO.Path.GetExtension(pathToLogo))) { finalLogo = logoFile; break; } if (System.IO.File.Exists(finalLogo)) { using (var fs = File.OpenRead(finalLogo)) { var img = new BitmapImage() { }; img.BeginInit(); img.StreamSource = fs; img.CacheOption = BitmapCacheOption.OnLoad; img.EndInit(); return img; } } } return null; } private static string GetModernAppProcessPath(IntPtr hwnd) { uint pid = 0; GetWindowThreadProcessId(hwnd, out pid); // now this is a bit tricky. Modern apps are hosted inside ApplicationFrameHost process, so we need to find // child window which does NOT belong to this process. This should be the process we need var children = GetChildWindows(hwnd); foreach (var childHwnd in children) { uint childPid = 0; GetWindowThreadProcessId(childHwnd, out childPid); if (childPid != pid) { // here we are Process childProc = Process.GetProcessById((int) childPid); return childProc.MainModule.FileName; } } throw new Exception("Cannot find a path to Modern App executable file"); } public static BitmapSource GetWindowIcon(IntPtr windowHandle) { var hIcon = default(IntPtr); hIcon = SendMessage(windowHandle, WM_GETICON, (IntPtr) ICON_BIG, IntPtr.Zero); if (hIcon == IntPtr.Zero) hIcon = GetClassLongPtr(windowHandle, GCL_HICON); if (hIcon == IntPtr.Zero) { hIcon = LoadIcon(IntPtr.Zero, (IntPtr) 0x7F00 /*IDI_APPLICATION*/); } if (hIcon != IntPtr.Zero) { return Imaging.CreateBitmapSourceFromHIcon(hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } else { throw new InvalidOperationException("Could not load window icon."); } } #region Helper methods const UInt32 WM_GETICON = 0x007F; const int ICON_BIG = 1; const int GCL_HICON = -14; private static List<IntPtr> GetChildWindows(IntPtr parent) { List<IntPtr> result = new List<IntPtr>(); GCHandle listHandle = GCHandle.Alloc(result); try { EnumWindowProc childProc = new EnumWindowProc(EnumWindow); EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle)); } finally { if (listHandle.IsAllocated) listHandle.Free(); } return result; } private static bool EnumWindow(IntPtr handle, IntPtr pointer) { GCHandle gch = GCHandle.FromIntPtr(pointer); List<IntPtr> list = gch.Target as List<IntPtr>; if (list == null) { throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>"); } list.Add(handle); // You can modify this to check to see if you want to cancel the operation, then return a null here return true; } public delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam); [DllImport("user32.Dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr parentHandle, EnumWindowProc callback, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern int GetWindowThreadProcessId(IntPtr handle, out uint processId); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); private static IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex) { if (IntPtr.Size > 4) return GetClassLongPtr64(hWnd, nIndex); else return new IntPtr(GetClassLongPtr32(hWnd, nIndex)); } [DllImport("user32.dll", EntryPoint = "GetClassLong")] public static extern uint GetClassLongPtr32(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "GetClassLongPtr")] public static extern IntPtr GetClassLongPtr64(IntPtr hWnd, int nIndex); #endregion} Usage is just: var icon = IconHelper.GetForegroundWindowIcon();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32122679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/553609/']}
jdg_372621
stackexchange
llm_judgeable_groundtruth_similarity
40269620
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 interface looks like this: public interface newArtsApi { @GET("art/get_all_arts?page=1") Call<List<ArtsPagination>> getMovies(@Query("index") int index);} Another ServiceGenerator class looks like this: public class ServiceGenerator { public static <S> S createService(Class<S> serviceClass) { OkHttpClient httpClient=new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build(); GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(String.class, new StringDesirializer()); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://...../clients/....../api/v1/") .addConverterFactory(GsonConverterFactory.create()) .client(httpClient).build(); return retrofit.create(serviceClass); }} I want this type of data using Retrofit 2.0, jsonarry_data but I get error for parsing this type of data. Now provide the response and nothing else.
Here's a naiive brute force method that will guess numbers ( string.digits ) and lower case letters ( string.ascii_lowercase ). You can use itertools.product with repeat set to the current password length guessed. You can start at 1 character passwords (or whatever your lower bound is) then cap it at a maximum length too. Then just return when you find the match. import itertoolsimport stringdef guess_password(real): chars = string.ascii_lowercase + string.digits attempts = 0 for password_length in range(1, 9): for guess in itertools.product(chars, repeat=password_length): attempts += 1 guess = ''.join(guess) if guess == real: return 'password is {}. found in {} guesses.'.format(guess, attempts) # uncomment to display attempts, though will be slower #print(guess, attempts)print(guess_password('abc')) Output a 1b 2c 3d 4...aba 1369abb 1370password is abc. found in 1371 guesses.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40269620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6915323/']}
jdg_372622
stackexchange
llm_judgeable_groundtruth_similarity
34280
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As a newbie in the world of signal processing, I am having a hard time in appreciating image 2-D fourier transforms. I am fully able to appreciate the concept of 1-D Fourier transform. Essentially, given a random causal signal, it can be decomposed into sinusoids. We cross-corelate known sinusoids (Basis functions) using FT and obtain the frequency spectrum. This is just perfect. Please help me understand why in image processing, transformation along both axes is needed. Given a greyscale image, like the Lena image, stored in a matrix $M \times N$, I infer the following: Pixel intensity varies from left to right Pixel intensity also varies top to bottom A FT performed on 1 Row, Left to Right, gives us a spectrum of frequencies belonging to that row Similarly, such a FT can be individually performed on each of the rows. So in the end, we end up with M frequency lists of frequencies. e.g., Freq-List[Row-0] = {f1, f2, f4 ... fj} , Freq-List[Row-5] = {f2, f11 ..} With this data, the Row frequency lists, will we not be able to tell how each pixel is affected by frequencies of that row? Shouldn't the row frequencies be sufficient? Will the frequency lists along the columns also have a bearing on the pixels? Now provide the response and nothing else.
Please help me understand why in image processing, transformation along both axes is needed. A one dimensional signal describes how does a quantity vary across, usually, time. Time, commonly represented by the symbol $t$, is the only parameter required to describe completely the signal at $t$. A two dimensional signal describes how does a quantity vary across two parameters that are absolutely required to describe it completely. When referring to images, the quantity that is described is, usually, radiant flux . That is, how much "light" (more generally, radiation) is received by the sensor. In common handheld cameras, each pixel of an image describes how much visible light is received by some point in the scene that is viewed. The complete set of pixels of an image, describes the variation of visible light across the surface of the camera's sensor. When applying the Fourier Transform to a one dimensional signal, the dimension of time is transformed to a dimension of frequency and the transform breaks the signal down to a sum of sinusoids. When applying the Fourier Transform to a two dimensional signal, its two spatial dimensions are decomposed into sums of orthogonal spatial sinusoids. To cut a long story short, if the basis functions of the Fourier Transform were not orthogonal , this trick of decomposing and recomposing would not be possible. How does this look like? It looks like a carton of eggs: The higher the spatial frequency, the smaller the eggs (more of them fit in the same length) and vice versa. More formally, it looks like this: And it doesn't even have to be "symmetrical", that is, each one of its dimensions may be supporting a different spatial frequency : In this last image, we have many more sinusoidal cycles across the $x$ dimension than across the $y$ dimension. Therefore, whereas in the one dimensional case, a signal as complicated as the voice of a singer is decomposed into a set of simple "whistles", in two dimensions, an image as complicated as Lena is decomposed into a set of elementary little blobs. In the first case, the signal is correlated with a series of progressively increasing frequency sinusoids, in the second case, exactly the same thing happens only now, the signal is a patch of pixels and the "sinusoid" is a patch of spatial frequencies that could vary differently across the $x$ and $y$ dimension. Now, in terms of expressing this process via the one dimensional Fourier Transform (that performs this correlation process with one set of sinusoids), the same, is applied twice . Consider Lena. And apply the Fourier Transform across each one of its rows. What do you get? You get a set of rows in the frequency domain. These describe the set of sinusoids that visible light across the rows of the image varies. But!!! at this point, we know nothing about the set of sinusoids that describe visible light variation along the vertical. Another way to "visualise" this, is to consider the DC bin of the row Fourier Transforms (frequency is zero). This tells you the average brightness of the pixels in each row but it still varies along the column direction! (i.e. we know nothing about the DC along the columns). In other words, where we had an $f(x,y)$, we pass it through the Fourier Transform along the rows and we now have an $f(F_x, y)$. We are now in an intermediate state where one dimension is frequency and the other is still space. For this reason, you apply the Fourier Transform once more along the columns of the Fourier Transform of the rows. (And to get back to the DC example, you now get one DC coefficient that describes the average brightness along the rows and the columns, that is, you get the average brightness of the image.) Now, remember, the one dimensional Fourier Transform decomposes a signal ($x(t)$) into two series of "strength" coefficients, one for the strengths of the $\sin$ and one for the strength of the $\cos$ at different frequencies. The two dimensional Fourier Transform does exactly the same thing but now the "strength" coefficients are two dimensional. That is, some coefficient at pixel $i,j$ (in the Fourier Transformed image, i.e. the Frequency Domain) describes the contribution of a "carton of eggs" with different number of cycles in the $x$ and $y$ dimension to the whole image . Generalising to three and higher dimensions is done similarly. Hope this helps. (Note, all images retrieved via Google Images and linked, rather than uploaded, to the post)
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/34280', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/16804/']}
jdg_372623
stackexchange
llm_judgeable_groundtruth_similarity
1523602
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Okay, suppose we have a line of text: [s]tackoverflow rocks where the brackets show the location of the cursor, in normal mode. After pressing tr , you get: stackov[e]rflow rocks Now for the fun part. What happens if you push ; to repeat the command? Nothing! Vim finds the next 'r' (immediately to the right of the cursor) and positions itself just left of that (where it already was). I would prefer that ; advance the cursor to this position: stackoverflow[ ]rocks This can be achieved by using l to move right one character before pressing ; , but the extra step is irritating. There is a similar issue with T , but not with f and F . Is there some way to make ; behave the way I want with t and T ? Now provide the response and nothing else.
Maybe it's not the answer you are looking for but I could not resist writing a VIM script for this. I put it in my .vimrc and it works for me: map ; :call Semicolon()<CR>function Semicolon() let s:pos1 = getpos(".") normal! ; let s:pos2 = getpos(".") if s:pos1 == s:pos2 normal! 2; endifendfunction The basic idea is that ; will not move to the next match, but 2; will (if there is a match). The script supports ; after any of tTfF . The easiest way to implement the , command is to write a similar function for that. EDIT Changed the script after Luc's excellent suggestion EDIT2 OK, these things are always more difficult than I originally think. The current mapping has the following problems: Suppose you did a search like tr above. Now what should d; or c; do? As far as I'm concerned they should delete or change up until the first r not the second. This can be solved by only doing the mapping for normal and visual mode, not operator pending mode. The current mapping does not work in visual mode. i.e., if you type v;;;; after the first ; the editor is no longer in visual mode (because of the :call ). This can be solved by calling the function using @= instead of :call . So now I end up with the following in my .vimrc (I also made one function for , and ; ): " Remap ; and , commands so they also work after t and T" Only do the remapping for normal and visual mode, not operator pending" Use @= instead of :call to prevent leaving visual modenmap ; @=FixCommaAndSemicolon(";")<CR>nmap , @=FixCommaAndSemicolon(",")<CR>vmap ; @=FixCommaAndSemicolon(";")<CR>vmap , @=FixCommaAndSemicolon(",")<CR>function FixCommaAndSemicolon(command) let s:pos1 = getpos(".") execute "normal! " . a:command let s:pos2 = getpos(".") if s:pos1 == s:pos2 execute "normal! 2" . a:command endif return ""endfunction
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1523602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541373/']}
jdg_372624
stackexchange
llm_judgeable_groundtruth_similarity
29976478
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 elastic search cluster running on 6 underpowered nodes. I want to migrate it to a new set of 4 very heavy-duty nodes. I'm trying to figure out the best way to do so. Since I'm going from 6 nodes to 4 nodes, I can't just copy data files from the old cluster to the new one. It looks like the snapshot and restore function is the way to go, but I can't find a documented way to create a snapshot on one set of hardware and restore it into another set. Has anybody ever done this sort of hardware upgrade with ElasticSearch? Now provide the response and nothing else.
To use snapshot/restore, you have to have a common mount point on all of the servers (ie NFS). You have to add the repository on both clusters, then snapshot on one and restore on the other. The exact commands are pretty well documented here: http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html Another way to migrate is to join the clusters together initially and wait for everything to be green. Then work through the process of decommissioning the old slow nodes: How to remove node from elasticsearch cluster on runtime without down time The final way to migrate is the way that @Zouzias recommended which is to use a program to copy the data from one cluster to another. There is an open source node.js based project here: https://github.com/mallocator/Elasticsearch-Exporter that will do what you need without having to write code. Another way to migrate is to use an API available in 5.x -- reindex from remote from remote: POST _reindex{ "source": { "remote": { "host": "http://otherhost:9200", "username": "user", "password": "pass" }, "index": "source" }, "dest": { "index": "dest" }} But be sure to read the documentation at the link provided because you have to set the reindex.remote.whitelist in you elasticsearch.yml file.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29976478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1327398/']}
jdg_372625
stackexchange
llm_judgeable_groundtruth_similarity
58735985
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hello I've seen many examples like this in Cppreference.com: std::is_class<T>std::is_integral And so on. I know if I run the code for example I get true or false . But what is the point in that? e.g knowing the object is of class type or not? #include <iostream>#include <type_traits>struct A {};class B {};enum class C {};int main(){ std::cout << std::boolalpha; std::cout << std::is_class<A>::value << '\n'; std::cout << std::is_class<B>::value << '\n'; std::cout << std::is_class<C>::value << '\n'; std::cout << std::is_class<int>::value << '\n';} The output: truetruefalsefalse I've searched all over for a real example using this ( is_class , is_integral , is_arithmetic , ...) But all the tutorials show only the hopeless example: only true or false . Could anyone help me with a small useful example using this templates? Now provide the response and nothing else.
It's not for writing to the console, that's for sure. More broadly you're asking: what is the point of type traits? The answer is template metaprogramming . For example, I can create a template specialisation that does one thing for integral types, and another for non-integral types. Aaron Bullman has a simple introduction to type traits , as does Jacek here . In my opinion, most use of these things will be found buried within implementations of cool features and classes and utilities (i.e. in libraries) as part of the background machinery that makes it all work. Further reading: C++ Type Traits How do traits classes work and what do they do? rightfold's answer on that first one gives a superb example of when traits are useful: For example, an implementation of std::copy may use std::memcpy internally instead of an explicit loop when the iterators are pointers to PODs. This can be achieved with SFINAE.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58735985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9160496/']}
jdg_372626
stackexchange
llm_judgeable_groundtruth_similarity
44866847
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 C# application to decode this string: "--W3sic3RhcnRfdGltZSI6IjAiLCJwcm9kdWN0X2lkIjoiODQwMDMzMDQiLCJ1cmwiOiIifSx7InN0YXJ0X3RpbWUiOiI3OSIsInByb2R1Y3RfaWQiOiI4NDAzNjk2MSIsInVybCI6IiJ9LHsic3RhcnRfdGltZSI6IjgyIiwicHJvZHVjdF9pZCI6Ijg0MDAzMDIwIiwidXJsIjoiIn0seyJzdGFydF90aW1lIjoiMTA5IiwicHJvZHVjdF9pZCI6IiIsInVybCI6Imh0dHBzOi8vYmxvZy5sYXJlaW5lZHVzaG9wcGluZy5jYS8yMDE3LzAxL3RyYW5zZm9ybWVyLXNlcy12aWV1eC1nYW50cy1kZS1jdWlyLWVuLTUtbWludXRlcy8ifV0=" It works when I copy/paste it into this online tool: https://www.base64decode.org But it throws an exception when I use Convert.FromBase64String(str) : System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. Why? Now provide the response and nothing else.
URL Decoding will remove + from a base64 string making it invalid. If you decode 'a+==' the result will be the character 'k'. If you use URL Decoding to decode 'a+==' the URL decoding will turn the string into 'a ==' and you will get an exception trying to decode it. In short, the .Net Framework is using a variant of Base64 encoding which does not allow invalid characters and PHP, used by the site in question, is using another variant which allows non-valid characters but discards them. Base64 encoding converts three octets into four encoded characters. Valid characters for the first 62 of the 64 characters in Base64 encoding: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 There are several variants which allow different characters for characters 62 and 63. With C#, as with the most common variants, the full character set is: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= https://msdn.microsoft.com/en-us/library/dhx0d524(v=vs.110).aspx The base-64 digits in ascending order from zero are the uppercasecharacters "A" to "Z", the lowercase characters "a" to "z", thenumerals "0" to "9", and the symbols "+" and "/". The valuelesscharacter, "=", is used for trailing padding. This variant is known is the standard 'base64' encoding for RFC 3548 or RFC 4648 in which invalid values are forbidden unless otherwise specified. PHP uses Base64 transfer encoding for MIME (RFC 2045) which allows non-valid characters but discards them. In all other Base64 variants non-valid characters are forbidden. If the original Base64 was actually supposed to contain the - character it is using a different variant. See: https://en.wikipedia.org/wiki/Base64#Variants_summary_table
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44866847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1136506/']}
jdg_372627
stackexchange
llm_judgeable_groundtruth_similarity
1204721
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 can I prove that A is non-invertible nxn matrix if sum of all elements in rows of A equal to zero? $$a_{11} + a_{12} + \cdots + a_{1n} = 0$$ $$a_{21} + a_{22} + \cdots + a_{2n} = 0$$ $$\vdots$$ $$a_{n1} + a_{n2} + \cdots + a_{nn} = 0$$ Now provide the response and nothing else.
Let $A=\left(C_{1},\ldots,C_{n}\right)$ where $C_{j}$ is the $j$ -th column of $A$ . Then your condition is $C_{1}+\ldots+C_{n}=0$ that is $C_{n}=-\left(C_{1}+\ldots+C_{n-1}\right)$ i.e. the columns of $A$ are linearly dependant. Thus the determinant is zero.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1204721', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_372628
stackexchange
llm_judgeable_groundtruth_similarity
208182
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As I can see, smart pointers are used extensively in many real-world C++ projects. Though some kind of smart pointers are obviously beneficial to support RAII and ownership transfers, there is also a trend of using shared pointers by default , as a way of "garbage collection" , so that the programmer do not have to think about allocation that much. Why are shared pointers more popular than integrating a proper garbage collector like Boehm GC ? (Or do you agree at all, that they are more popular than actual GCs?) I know about two advantages of conventional GCs over reference-counting: Conventional GC algorithms has no problem with reference-cycles . Reference-count is generally slower than a proper GC. What are the reasons for using reference-counting smart pointers? Now provide the response and nothing else.
Some advantages of reference counting over garbage collection: Low overhead. Garbage collectors can be quite intrusive (e.g. making your program freeze up at unpredictable times while a garbage collection cycle processes) and quite memory-intensive (e.g. your process's memory footprint unnecessarily grows to many megabytes before garbage-collection finally kicks in) More predictable behavior. With reference counting, you are guaranteed that your object will be freed the instant the last reference to it goes away. With garbage collection, on the other hand, your object will be freed "sometime", when the system gets around to it. For RAM this isn't usually a big problem on desktops or lightly loaded servers, but for other resources (e.g. file handles) you often need them be closed ASAP to avoid potential conflicts later on. Simpler. Reference counting can be explained in a few minutes, and implemented in an hour or two. Garbage collectors, especially ones with decent performance, are extremely complex and not many people understand them. Standard. C++ includes reference counting (via shared_ptr) and friends in the STL, which means that most C++ programmers are familiar with it and most C++ code will work with it. There isn't any standard C++ garbage collector, though, which means that you have to choose one and hope it works well for your use case -- and if it doesn't, it's your problem to fix, not the language's. As for the alleged downsides of reference counting -- not detecting cycles is an issue, but one that I've never personally ran into in the last ten years of using reference counting. Most data structures are naturally acyclical, and if you do come across a situation where you need cyclical references (e.g. parent pointer in a tree node) you can just use a weak_ptr or a raw C pointer for the "backwards direction". As long as you are aware of the potential problem when you're designing your data structures, it's a non-issue. As for performance, I've never had a problem with the performance of reference counting. I have had problems with the performance of garbage collection, in particular the random freeze-ups that GC can incur, to which the only solution ("don't allocate objects") might as well be rephrased as "don't use GC".
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/208182', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/-1/']}
jdg_372629
stackexchange
llm_judgeable_groundtruth_similarity
8976423
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: All over the web, I am getting the feeling that writing a C backend for a compiler is not such a good idea anymore. GHC's C backend is not being actively developed anymore (this is my unsupported feeling). Compilers are targeting C-- or LLVM. Normally, I would think that GCC is a good old mature compiler that does performs well at optimizing code, therefore compiling to C will use the maturity of GCC to yield better and faster code. Is this not true? I realize that the question greatly depends on the nature of the language being compiled and on other factors such that getting more maintainable code. I am looking for a rather more general answer (w.r.t. the compiled language) that focuses solely on performance (disregarding code quality, ..etc.). I would be also really glad if the answer includes an explanation on why GHC is drifting away from C and why LLVM performs better as a backend ( see this ) or any other examples of compilers doing the same that I am not aware of. Now provide the response and nothing else.
While I'm not a compiler expert, I believe that it boils down to the fact that you lose something in translation to C as opposed to translating to e.g. LLVM's intermediate language. If you think about the process of compiling to C, you create a compiler that translates to C code, then the C compiler translates to an intermediate representation (the in-memory AST), then translates that to machine code. The creators of the C compiler have probably spent a lot of time optimizing certain human-made patterns in the language, but you're not likely to be able to create a fancy enough compiler from a source language to C to emulate the way humans write code. There is a loss of fidelity going to C - the C compiler doesn't have any knowledge about your original code's structure. To get those optimizations, you're essentially back-fitting your compiler to try to generate C code that the C compiler knows how to optimize when it's building its AST. Messy. If, however, you translate directly to LLVM's intermediate language, that's like compiling your code to a machine-independent high-level bytecode, which is akin to the C compiler giving you access to specify exactly what its AST should contain. Essentially, you cut out the middleman that parses the C code and go directly to the high-level representation, which preserves more of the characteristics of your code by requiring less translation. Also related to performance, LLVM can do some really tricky stuff for dynamic languages like generating binary code at runtime. This is the "cool" part of just-in-time compilation: it is writing binary code to be executed at runtime, instead of being stuck with what was created at compile time.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8976423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/955679/']}
jdg_372630
stackexchange
llm_judgeable_groundtruth_similarity
6369887
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 use the money_format() function in PHP, but it gives the following error: Fatal error: Call to undefined function money_format() Searches about this error reveal that the function money_format() is only defined if the system has strfmon capabilities (for example, Windows does not) and also that the function has been removed from PHP 8.0. Is there an equivalent PHP function available? Now provide the response and nothing else.
If you have the Intl extension , you can use NumberFormatter::formatCurrency — Format a currency value according to the formatter rules. Example from Manual $fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n"; Output 1.234.567,89 €1.234.567,89 RUR1 234 567,89€1 234 567,89р. Also see my answer on how to parse that formatted money string back into a float: PHP: unformat money
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6369887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/712818/']}
jdg_372631
stackexchange
llm_judgeable_groundtruth_similarity
4869004
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 a little confused here with this findbugs warning in eclipse. public class MyClass { public static String myString;}public class AnotherClass { public void doSomething() { MyClass.myString = "something"; }} This gives me a findbugs warning "write to static field from instance method", however this does not give me a warning: public class MyClass { public static String myString;}public class AnotherClass { public void doSomething() { doAnotherThing(); } public static doAnotherThing() { MyClass.myString = "something"; }} How is this any different?, and why is writing to a static variable from an instance method a bad practice?, I assume it has to do with synchronization, but it is still not clear to me. I know this looks like the variable should be final, but I am loading the value from a properties file. Now provide the response and nothing else.
Its a form of aliasing, which may be counter-intuitive. Counter-intuitive code hampers ease of maintenance. Logically, we expect instance methods to affect that instance's data. We expect static methods to affect static data. Let's rename doSomething to initialize : ...a.initialize();...b.initialize();... The reader of this code may not immediately realize that the instances of a and b are actually affecting the same data. This may be a bug since we're initializing the same memory twice, but its non-obvious since it seems reasonable that we may need to call initialize on each instance. However, the the code were: ...MyClass.initialize();...MyClass.initialize();... In this case, its more intuitive that we're likely affecting the same static data and this is likely a bug. This is similar to the common version of aliasing where two variables in the same scope point to the same instance. For your last example, an instance calls a static method The fact that an instance method is calling a static method isn't expected to raise flags. The examples were this is useful far outweigh where its likely a problem. a static method of one class affects another class' static data In one sense, it should generate a different, but similar warning: that one class is messing with the data of another class. However, by making the static variable public is a way of tacitly approving of this, so such a warning isn't necessary. Keep in mind that FindBugs is simply trying to flag potential likely problems, not every possible problem, in your code. Your first example is likely a potential maintenance issue that you need to examine whether its a real problem. Your second example is likely not a problem or it is a real problem that is too similar to use cases where it is not a problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4869004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135683/']}
jdg_372632
stackexchange
llm_judgeable_groundtruth_similarity
19232957
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 functions : void *foo(void *i) { int a = (int) i;}int main() { pthread_t thread; int i; pthread_create(&thread, 0, foo, (void *) i);} At compilation, there are some errors about casting ( (void *) i and int a = (int) i ). How can I pass an integer as the last argument of pthread_create properly? Now provide the response and nothing else.
Building on szx's answer (so give him the credit), here's how it would work in your for loop: void *foo(void *i) { int a = *((int *) i); free(i);}int main() { pthread_t thread; for ( int i = 0; i < 10; ++1 ) { int *arg = malloc(sizeof(*arg)); if ( arg == NULL ) { fprintf(stderr, "Couldn't allocate memory for thread arg.\n"); exit(EXIT_FAILURE); } *arg = i; pthread_create(&thread, 0, foo, arg); } /* Wait for threads, etc */ return 0;} On each iteration of the loop, you're allocating new memory, each with a different address, so the thing that gets passed to pthread_create() on each iteration is different, so none of your threads ends up trying to access the same memory and you don't get any thread safety issues in the way that you would if you just passed the address of i . In this case, you could also set up an array and pass the addresses of the elements.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19232957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1477700/']}
jdg_372633
stackexchange
llm_judgeable_groundtruth_similarity
36597663
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 WooCommerce any order placed with the BACS (direct bank transfer) is set to "on-hold" . How would one go about changing this automatically to processing? I wan't it to work inside the functions.php I have the following code but that doesn't work: add_filter( 'woocommerce_payment_complete_order_status', 'rfvc_update_order_status', 10, 2 );function rfvc_update_order_status( $order_status, $order_id ) { $order = new WC_Order( $order_id ); if ( 'on-hold' == $order_status && 'on-hold' == $order->status ) { return 'processing'; } return $order_status;} Any help would be great! Now provide the response and nothing else.
New 2020 update WooCommerce version 3.4 has introduced a much better hook than woocommerce_thankyou or woocommerce_thankyou_bacs , that allows to change the default order status for BACS payment method. Using this hook will: clearly lighten the necessary code, avoid "on-hold" notification to the customer when a BACS order is placed. So use instead the following: add_filter( 'woocommerce_bacs_process_payment_order_status','filter_bacs_process_payment_order_status_callback', 10, 2 );function filter_bacs_process_payment_order_status_callback( $status, $order ) { return 'processing';} Code goes in functions.php file of the active child theme (or active theme). Tested and works. Original answer: Update (added a version for woocommerce 3+ at the end) It seems that woocommerce_payment_complete_order_status action hook doesn't trigger with BACS payment method. Based on this thread , 'woocommerce_thankyou' action hook does the job: add_action( 'woocommerce_thankyou', 'bacs_order_payment_processing_order_status', 10, 1 ); function bacs_order_payment_processing_order_status( $order_id ) { if ( ! $order_id ) { return; } // Get an instance of the WC_Order object $order = new WC_Order( $order_id ); if ( ( get_post_meta($order->id, '_payment_method', true) == 'bacs' ) && ('on-hold' == $order->status || 'pending' == $order->status) ) { $order->update_status('processing'); } else { return; }} Code goes in function.php file of your active child theme (or active theme). tested and works. For woocommerce 3+ versions: Here we use the similar composite hook woocommerce_thankyou_{$order->get_payment_method()} : add_action( 'woocommerce_thankyou_bacs', 'bacs_order_payment_processing_order_status', 10, 1 );function bacs_order_payment_processing_order_status( $order_id ) { if ( ! $order_id ) { return; } // Get an instance of the WC_Order object $order = wc_get_order( $order_id ); if ( in_array( $order->get_status(), array('on-hold', 'pending') ) ) { $order->update_status('processing'); } else { return; }} Code goes in function.php file of your active child theme (or active theme). tested and works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36597663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5852922/']}
jdg_372634
stackexchange
llm_judgeable_groundtruth_similarity
841231
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 having an issue with pulling a Spring bean from an application context. When I try; InnerThread instance = (InnerThread) SpringContextFactory.getApplicationContext().getBean("innerThread", InnerThread.class); I get; org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'innerThread' must be of type [com.generic.InnerThread], but was actually of type [$Proxy26] Without the specified class in the getBean() call I get a ClassCastException (which you can see in detail below). The InnerThread bean is being initialized as a non-singleton, because I need multiple instances. The InnerThread class also extends Thread. The interesting thing is that this error shows up within OuterThread, which is set up in the exact same way the InnerThread is. I've tried to include all relevant code listings/stack traces below. Could someone with more Spring experience tell me what is going on here? Code/Configuration Listing OuterThread.java snippet: public class OuterThread extends Thread { private Queue<InnerThread> createInnerThreads() { Queue<InnerThread> threads = new ArrayBlockingQueue(); ApplicationContext ctx = SpringContextFactory.getApplicationContext(); int i = 0; for (SearchRule search : searches) { logger.debug("Number of times looped " + i++); //Seprated lines to get a better sense of what is going on Object proxy = ctx.getBean("innerThread", InnerThread.class); logger.debug(ReflectionToStringBuilder.toString(proxy)); logger.debug("proxy.getClass(): " + proxy.getClass()); logger.debug("proxy.getClass().getClassLoader(): " + proxy.getClass().getClassLoader()); logger.debug("proxy.getClass().getDeclaringClass(): " + proxy.getClass().getDeclaringClass()); logger.debug("InnerThread.class.getClassLoader(): " + InnerThread.class.getClassLoader()); //---Exception here--- InnerThread cst = (InnerThread) proxy; threads.add(cst); } return threads; } public static void main(String[] args) throws Exception { try { OuterThread instance = (OuterThread) SpringContextFactory.getApplicationContext().getBean("outerThread", OuterThread.class); instance.run(); } catch (Exception ex) { logger.error("Fatal exception.", ex); throw ex; } }} SpringContextFactory.java: public class SpringContextFactory { static final Logger logger = LoggerFactory.getLogger(SpringContextFactory.class); private static ApplicationContext ctx; private static final String DEFAULT_PATH = "META-INF/app-context.xml"; public static ApplicationContext getApplicationContext() { return getApplicationContext(DEFAULT_PATH); } public static synchronized ApplicationContext getApplicationContext(String path) { if (ctx == null) return createApplicationContext(path); else return ctx; } private static ApplicationContext createApplicationContext(String path) { if (logger.isDebugEnabled()) logger.debug("Loading Spring Context..."); ctx = new ClassPathXmlApplicationContext(path); if (logger.isDebugEnabled()) logger.debug("Spring Context Loaded"); return ctx; }} app-context.xml: <?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- persistence context from separate jar --> <import resource="persistence-context.xml"/> <bean id="outerThread" class="com.generic.OuterThread" scope="prototype"/> <bean id="innerThread" class="com.generic.InnerThread" scope="prototype"/></beans> Stack Trace 2009-05-08 14:34:37,341 [main] DEBUG com.generic.OuterThread.init(OuterThread.java:59) - Initializing OuterThread object, com.generic.OuterThread@1c8fb4b[em=org.hibernate.ejb.EntityManagerImpl@e2892b,currentTime=java.util.GregorianCalendar[time=1241634874841,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2009,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=6,DAY_OF_YEAR=126,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=34,SECOND=34,MILLISECOND=841,ZONE_OFFSET=-18000000,DST_OFFSET=3600000],maxConcurrentThreads=5,reconId=3,reportUsername=TEST,useOffset=false,username=removed,uuid=bf61494d-ff96-431c-a41f-1e292d0c9fbe,name={T,h,r,e,a,d,-,1},priority=5,threadQ=<null>,eetop=0,single_step=false,daemon=false,stillborn=false,target=<null>,group=java.lang.ThreadGroup[name=main,maxpri=10],contextClassLoader=sun.misc.Launcher$AppClassLoader@11b86e7,inheritedAccessControlContext=java.security.AccessControlContext@1524d43,threadLocals=<null>,inheritableThreadLocals=java.lang.ThreadLocal$ThreadLocalMap@2cbc86,stackSize=0,nativeParkEventPointer=0,tid=9,threadStatus=0,parkBlocker=<null>,blocker=<null>,blockerLock=java.lang.Object@a68fd8,stopBeforeStart=false,throwableFromStop=<null>,uncaughtExceptionHandler=<null>]2009-05-08 14:34:37,341 [main] DEBUG org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.doJoinTransaction(ExtendedEntityManagerCreator.java:385) - No local transaction to join2009-05-08 14:34:37,529 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:139) - Number of times looped 02009-05-08 14:34:37,529 [main] DEBUG org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:458) - Creating instance of bean 'searchThread' with merged definition [Root bean: class [com.generic.InnerThread]; scope=prototype; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [META-INF/app-context.xml]]2009-05-08 14:34:37,545 [main] DEBUG com.generic.InnerThread.<init>(InnerThread.java:50) - Constructing InnerThread object, com.generic.InnerThread@1080876[em=<null>,coolScheme=<null>,coolUrl=<null>,date=<null>,error=<null>,millisecondsTaken=0,thresholdMet=false,reconId=0,result=-2,searchId=0,username=<null>,uuid=<null>,name={T,h,r,e,a,d,-,2},priority=5,threadQ=<null>,eetop=0,single_step=false,daemon=false,stillborn=false,target=<null>,group=java.lang.ThreadGroup[name=main,maxpri=10],contextClassLoader=sun.misc.Launcher$AppClassLoader@11b86e7,inheritedAccessControlContext=java.security.AccessControlContext@1524d43,threadLocals=<null>,inheritableThreadLocals=java.lang.ThreadLocal$ThreadLocalMap@3aef16,stackSize=0,nativeParkEventPointer=0,tid=10,threadStatus=0,parkBlocker=<null>,blocker=<null>,blockerLock=java.lang.Object@126c6ea,stopBeforeStart=false,throwableFromStop=<null>,uncaughtExceptionHandler=<null>]2009-05-08 14:34:37,545 [main] DEBUG org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:203) - Returning cached instance of singleton bean 'entityManagerFactory'2009-05-08 14:34:37,545 [main] DEBUG org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:203) - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'2009-05-08 14:34:37,560 [main] DEBUG org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource.getTransactionAttribute(AbstractFallbackTransactionAttributeSource.java:108) - Adding transactional method [report] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]2009-05-08 14:34:37,560 [main] DEBUG org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.buildAdvisors(AbstractAutoProxyCreator.java:494) - Creating implicit proxy for bean 'searchThread' with 0 common interceptors and 1 specific interceptors2009-05-08 14:34:37,560 [main] DEBUG org.springframework.aop.framework.JdkDynamicAopProxy.getProxy(JdkDynamicAopProxy.java:113) - Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [com.generic.InnerThread@1080876]2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:141) - $Proxy26@1594a88[h=org.springframework.aop.framework.JdkDynamicAopProxy@1f0cf51]2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:142) - proxy.getClass(): class $Proxy262009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:143) - proxy.getClass().getClassLoader(): sun.misc.Launcher$AppClassLoader@11b86e72009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:144) - proxy.getClass().getDeclaringClass(): null2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:145) - InnerThread.class.getClassLoader(): sun.misc.Launcher$AppClassLoader@11b86e72009-05-08 14:34:37,591 [main] ERROR com.generic.OuterThread.run(OuterThread.java:101) - Exception in OuterThread, ending reconciliation.java.lang.ClassCastException: $Proxy26 cannot be cast to com.generic.InnerThread at com.generic.OuterThread.createInnerThreads(OuterThread.java:148) at com.generic.OuterThread.run(OuterThread.java:65) at com.generic.OuterThread.main(OuterThread.java:170) Similar questions that do not answer my question Auto-cast Spring Beans ClassCastException when casting to the same class. Now provide the response and nothing else.
Once again, after spending hours trying to debug this I find the answer right after posting on StackOverflow. A key point that I left out from my question is that InnerThread has a transactional method (sorry thought this was irrelevant). This is the important difference between OuterThread and InnerThread. From the Spring documentation : Note Multiple sections are collapsed into a single unified auto-proxy creator at runtime, which applies the strongest proxy settings that any of the sections (typically from different XML bean definition files) specified. This also applies to the and elements. To be clear: using 'proxy-target-class="true"' on , or elements will force the use of CGLIB proxies for all three of them. Adding the above to my configuration (based in persistance-context.xml, which you can see loaded above) line seems to fix the problem. However, I think this may be a quick fix workaround as opposed to real solution. I think I've got a few deeper issues here, number one being that I find Spring as confusing as expletive deleted. Second I should probably be using Spring's TaskExecutor to kick off my threads. Third my threads should implement Runnable instead of extending Thread (See SO question below). See Also BeanNotOfRequiredTypeException usingServiceLocatorFactoryBean and@Transactional (Nothing better then finding a thread off Google after hours of searching to have a response that says "This has already been answered a million times.") Section 6.6 in the SpringDocs. Java: “implements Runnable” vs. “extends Thread”
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/841231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20774/']}
jdg_372635
stackexchange
llm_judgeable_groundtruth_similarity
18085169
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose there are two classes A and B: class A {};class B {}; In what aspects differ the two examples below? Example 1: class C : public A, public B {}; Example 2: class C{ //private friend class A; friend class B;} Now provide the response and nothing else.
A friend can touch the private parts (pun only slightly intentional! ;) ) of whatever it is friend of, but nothing of A and B are part of C - it just means that " A and B can touch C 's private bits"). Anything "less" than private is of course also available to A and B , so if C has protected or public members, that will also be available. When you inherit, the A and B becomes part of C . Any private sections of A and B are not available to C . In the "is-a" vs. "has-a" nomenclature, C now is-a A and is-a B - in other words, it's inherited from A , so it "behaves like A from an interface perspective.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18085169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1857483/']}
jdg_372636
stackexchange
llm_judgeable_groundtruth_similarity
3371239
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The Autoconfig manual states that comment lines can start with either dnl or # . Is there any difference between them, any reason to use one rather than the other in any circumstance? Or is it purely a matter of taste? Now provide the response and nothing else.
In configure.ac, lines commented with '#' that occur after AC_INIT will appear in the resulting configure script. dnl comments will not. One purpose of dnl is to discard unwanted newlines in an effort to make the configure script readable. Also, it is appropriate to use dnl comments to document an m4 macro; those comments make no sense in the configure script, since the m4 macro does not appear there, only its expansion. Comments in Makefile.am are treated differently. Makefile.am is not processed by m4, but by automake, where the convention is to discard lines which begin with ## preceded only by whitespace. (Although ### comments carry through to the Makefile.in) Since Makefile.am is not processed by m4, 'dnl' does not introduce a comment.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3371239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/60281/']}
jdg_372637
stackexchange
llm_judgeable_groundtruth_similarity
344445
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I'm inspired in [1] to ask the following question. My problem is that I have not an implementation of the inverse of the logarithmic integral $\operatorname{Li}(x)=\int_2^x\frac{dt}{\log t}$ , that will be denoted in this post as $$\operatorname{ali}(x)$$ for real numbers $x\geq 2$ . Question. A) Do you know a site or article showing a graph for $$p_n-\operatorname{ali}(n)$$ for integers $1\leq n\leq N$ for samples of the integer $N$ enough large ( $N=10^3$ , $N=10^6$ and/or $N=10^9$ )? In case that isn't in the literature can you show a such of these graphs for $N$ a large integer? B) Do you know if it is possible to prove that the sign of the graph for $$p_n-\operatorname{ali}(n)$$ changes infinitely often when $1\leq n$ runs over positive integers? Many thanks. I don't know if the second question is obvious from Littlewood's theorem (see [2]), or it is required to add details. References: [1] Juan Arias de Reyna and Jérémy Toulisse, The $n$ -th prime asymptotically , Journal de Théorie des Nombres de Bordeaux, Volume: 25, Issue: 3 (2013). [2] The section Skewes's_numbers from the Wikipedia Skewes's number . Now provide the response and nothing else.
The answer to (B) is yes, at least conditionally. The sign of $p_n-\mathop{\rm ali}(n)$ is determined by the sign of $\pi(p_n) - \mathop{\rm li}(p_n)$ (other than the negligible possibility that one equals $0$ while the other is tiny and nonzero). The logarithmic density of those primes $p$ for which $\pi(p) > \mathop{\rm li}(p)$ is known, conditionally, to be strictly between $0$ and $1$ , which in particular implies infinitely many sign changes. See my paper "Primes in prime number races" with Lichtman and Pomerance . Since $\pi(x)-\mathop{\rm li}(x)$ is unconditionally known to change sign infinitely often, it would be interesting to try to prove the OP's statement unconditionally. We certainly used more than the existence of sign changes: we used the fact that for almost all $x$ , the difference is not very close to $0$ (which is implicit in the existence of the limiting logarithmic distribution of the normalized difference).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/344445', 'https://mathoverflow.net', 'https://mathoverflow.net/users/142929/']}
jdg_372638
stackexchange
llm_judgeable_groundtruth_similarity
167650
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It is easy to define the Equals operation in ways that are not commutative. When providing equality against other types, there are obviously situations (in most languages) were equality not being commutative is unavoidable. However, within one's own inheritance hierarchy where the root base class defines an equality member, a programmer has more control. Thus you can create situations where (A = B) ≠ (B = A), where A and B both derive from base class T Substituting the = with the appropriate variation for a given language. ( .Equals(_) , == , etc.) That seems wrong to me, however, I recognize I may be biased by background in Mathematics. I have not been in programming long enough to know what is standard/accepted/preferred practice when programming. Do most programmers just accept .Equals(_) may not be commutative and code defensibly. Do they expect commutativity and get annoyed if it is not. In short, when working in a class hierarchy, should effort me made to ensure Equality is commutative? Now provide the response and nothing else.
Non-symmetric 1 equals breaks the contract of the operation, spelled out clearly in the documentation (I'm quoting from the Java's documentation, but it remains essentially the same in other languages) The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false. These are mathematical properties a relation must have in order to be called an equality relation. A relation can be defined without any of these properties 2 , but fundamentally it is not an equality relation, and it is dangerous to use it in the context where the equality relation is implied. 1 The right term in the context of equality is "symmetric", not "commutative". 2 For example, it is very tempting to define equality of float s as "two numbers with the absolute difference less than a small epsilon"; that's a very bad idea, because it breaks transitivity.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/167650', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/67012/']}
jdg_372639
stackexchange
llm_judgeable_groundtruth_similarity
1708211
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: If $R$ and $S$ are commutative rings, then does the category $R \oplus S$-modules encompase the category of $(S,R)$-bimodules? I was thinking we can accomplish this by defining the action to be:$(r,s)\cdot x:=r\cdot (x\cdot s)$ and then doing something accoring for the morphisms. Am I overlooking something or is this indeed true? Now provide the response and nothing else.
The direct product of rings is not really the right way to go. You cannot get suitable additive properties (as Eric Wofsey describes.)An $R,S$ bimodule structure is equivalent to an $R\otimes S^{op}$ module structure. You can prove this beginning with what you have already written. You just need to apply the properties of the tensor product. If $R$ and $S$ are central simple $K$ algebras, then $R\otimes_K S^{op}$ is central simple too, but $R\times S$ is not, so there will be differences in the module categories.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1708211', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/83860/']}
jdg_372640