text
stringlengths
175
47.7k
meta
dict
Q: Mapkit, how to detect annotations have loaded I want the annotations callout to popup when the pin has finished it's drop animation. Currently I am able to simulate it with the following method: - (void)showCallOut { [myMapView selectAnnotation:[myMapView.annotations objectAtIndex:0] animated:YES]; } In my viewDidLoad is where my annotation is created [myMapView addAnnotation:annotation]; The problem is that you simply can't callout [self showCallOut]; after that because at run time it responds before MapKit has "acknowledged" the annotation drop. I need to either create a delay (Would like to avoid this) or find the proper way to detect when annotations are in place and then run the showCallOut method. Thanks for any help! Thanks to aBitObvious below for providing a solution: - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views { [self performSelector:@selector(showCallOut) withObject:nil afterDelay:1]; } A: Try using the didAddAnnotationViews delegate method: - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views { [self showCallOut]; } Make sure your map view's delegate is set. Edit: If you need to add a delay regardless, then try this instead (example with 1/2 second delay): - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views { [self performSelector:@selector(showCallOut) withObject:nil afterDelay:0.5]; }
{ "pile_set_name": "StackExchange" }
Q: C++: I need some guidance in how to create dynamic sized bitmaps I'm trying to create a simple DBMS and although I've read a lot about it and have already designed the system, I have some issues about the implementation. I need to know what's the best method in C++ to use a series of bits whose length will be dynamic. This series of bits will be saved in order to figure out which pages in the files are free and not free. For a single file the number of pages used will be fixed, so I can probably use a bitset for that. However the number of records per page AND file will not be fixed. So I don't think bitset would be the best way to do this. I thought maybe to just use a sequence of characters, since each character is 1 byte = 8 bits maybe if I use an array of them I would be able to create the bit map that I want. I never had to manipulate bits at such a low level, so I don't really know if there is some other better method to do this, or even if this method would work at all. thanks in advance A: If you are just wanting the basics on the bit twiddling, the following is one way of doing it using an array of characters. Assume you have an array for the bits (the length needs to be (totalitems / 8 )): unsigned char *bits; // this of course needs to be allocated somewhere You can compute the index into the array and the specific bit within that position as follows: // compute array position int pos = item / 8; // 8 bits per byte // compute the bit within the byte. Could use "item & 7" for the same // result, however modern compilers will typically already make // that optimization. int bit = item % 8; And then you can check if a bit is set with the following (assumes zero-based indexing): if ( bits[pos] & ( 1 << bit )) return 1; // it is set else return 0; // it is not set The following will set a specific bit: bits[pos] |= ( 1 << bit ); And the following can be used to clear a specific bit: bits[pos] &= ~( 1 << bit );
{ "pile_set_name": "StackExchange" }
Q: Xamarin cross-platform visual studio bottom navigation I just started using xamarin in visual studio for building cross-platform apps, and i was searching on the internet for some tutorial etc, and i ran into a website "material.io" and i found this amazing bottom navigation So i searched on google for a tutorial to make that bottom navigation in xamarin.forms cross-platform environment. But i didn,'t find anything, so i hoped that someone here at stackoverflow knew how to or could provide me with code or a tutorial. thanks in advance A: As Jason already mentioned, something like this requires a custom renderer. However, you're lucky since someone has already done the hard work for you. There's a Xamarin.Android control called BottomNavigationBar which has been ported to Xamarin.Forms in the project BottomNavigationBarXF. You'll also find an example of how to get started on the latter repository. On iOS, the control defaults to the standard page with tabs on the bottom.
{ "pile_set_name": "StackExchange" }
Q: sed over ssh doesn't escape backslash I'm trying to add a line before "rezhome" in the file as it would look like below: ... app3-reservation, \ app4-reservation, \ app5-reservation, \ rezhome When I run locally with below command it works fine. sed -i 's/rezhome/app5-reservation, \\\n&/' grouphost.cfg But using ssh backslash is not escaped and I get below result ssh localhost "sed -i 's/rezhome/app5-reservation, \\\n&/' /path/grouphost.cfg" ... app3-reservation, \ app4-reservation, \ app5-reservation, \nrezhome Any help please? A: The \ gets processed by both the sed and the ssh so you'll need to further escape them to use it with both. Try: ssh localhost "sed -i 's/rezhome/app5-reservation, \\\\\n&/' /path/grouphost.cfg"
{ "pile_set_name": "StackExchange" }
Q: Generalization of Lévy's continuity theorem for nuclear spaces I am interested in a generalization of the following finite-dimensional results in infinite dimensional vector-space with nuclear structure, especially for the cases of the spaces of distributions $\mathcal{D}'(\mathrm{R}^N)$ and $\mathcal{S}'(\mathrm{R}^N)$. Theorem 1: Let $X_n$, $n\in\mathbb{N}$ and $X$ be random variables in $\mathbb{R}^N$ and $\Phi_n$ and $\Phi$ their characteristic functions. Then, $$\left( X_n \overset{\mathcal{L}}{\rightarrow} X \right) \Leftrightarrow \left( \forall \omega, \Phi_n(\omega) \rightarrow \Phi(\omega) \right).$$ Theorem 2: (Lévy's continuity theorem) Again, the $X_n$'s are random variable and the $\Phi_n$'s are their characteristic functions. Assume that the limit $\lim \Phi_n(\omega)$ exists pointwise and is denoted by $\Phi(\omega)$. We then have the equivalence: $(X_n)$ converges in law to some random variable $X$. $\Phi$ is continuous at $0$. Now I precise my question. Given a probability measure $\mu$ on $\mathcal{N}' = \mathcal{D}'(\mathrm{R}^N)$ or $\mathcal{S}'(\mathrm{R}^N)$, we can define its characteristic functional on $\mathcal{N}$ by $$\hat{\mu}(\varphi) = \int_{\mathcal{N}'} \mathrm{e}^{\mathrm{j} \langle u , \varphi \rangle} \mathrm{d}\mu (u).$$ This generalizes the concept characteristic function of a random variable (Bochner's theorem being generalized by Minlos's theorem). Is the following result true? Possible generalization of theorem 1: Let $\mu_n$, $n\in\mathbb{N}$ and $\mu$ be probability measures on $\mathcal{N}'$ and $\hat{\mu}_n$ and $\mu$ their characteristic functionals. Then, $$\left( \mu_n \overset{\mathrm{weakly}}{\rightarrow} \mu \right) \Leftrightarrow \left( \forall \varphi, \hat{\mu}_n(\varphi) \rightarrow \mu(\varphi) \right).$$ Similarly, can we generalize the Lévy's continuity theorem? Thanks for attention. A: There is a partial result due to Boulicaut (1973), which states Theorem: Let $E$ be a separable metrizable Hausdorff locally convex topological vector space. Then $E$ is nuclear if and only if for every sequence $\{\mu_n\}$ of tight probability measures, weak convergence to a tight probability measure $\mu$ is equivalent to the pointwise convergence of the characteristic functions of $\mu_n$ to the ch. f. of $\mu$. This makes characteristic function(al)s more useful than in separable Banach spaces, where they are only used for uniqueness but not weak convergence.
{ "pile_set_name": "StackExchange" }
Q: SSRS 2008 R2 / 2012 Width Property Unit of Measure Default Setting Is there a way to configure the default unit of measure for the width / height properties used to size cells / rows? If I add a table and configure the width of the columns to a value specified in "pt" rather than "cm" I have to change them all as I specify the width (I am using pt to get over the inexplicable inability of SSRS to correctly align columns when exported to Excel). Is there a way I can change from cm to pt as the default value for all measures in a report? A: Imperial or metric, as I understand, is simply based on the windows regional setting. Further customization of the default past that isn't currently possible. I've seen one work around that modifies the report template which can potentially make your life easier but this approach has limitations as well. Looking through Microsoft connect I don't see this posted yet as a feature request. It seems to me that this would be an excellent suggestion.
{ "pile_set_name": "StackExchange" }
Q: What's the simplest way to deploy a Grails-generated WAR file? I've been having persistent problems (for several weeks) getting Tomcat to deploy a WAR file. I'm looking for a simple server. It does not need to have a lot of functionality-it just needs to be simple to set up. In particular I'm looking for a program that I can just drop a WAR file into and have the enclosed web application launch. A: You might want to give jetty runner a try. It basically just uses an embedded jetty instance to run your war file. http://blogs.webtide.com/janb/entry/jetty_runner It is available on Maven and it is in fact how heroku apps built with grails are ran. http://devcenter.heroku.com/articles/deploy-a-java-web-application-that-launches-with-jetty-runner A: If your application does not start on tomcat, it almost certainly means it won't start on any servlet container - containers implement a spec, and are very similar in many aspects. What you should do is go and hunt each problem one by one, until the application starts. The problem is the app, not the container.
{ "pile_set_name": "StackExchange" }
Q: is it possible to have getline() function accept wistream& Just for clarification, I'm referring to the global getline() function in the string class. What I want to do is to have something like this: int main() { wifstream in(L"textfile.txt"); someFunc(in); return 0; } void someFunc(const wistream& read) { wstring buff; while(getline(read, buff)) { //do some processing here } } but I'm getting a: Error 2 error C2664: 'std::getline' : cannot convert parameter 1 from 'const std::wistream' to 'std::basic_istream<_Elem,_Traits> &' In order to fix it, I need to remove the const from const wistream& read. I understand why this is happening but is it possible to configure getline() to accept a wistream instead without any conversions or should I just ignore it and remove the const? A: It does accept a wistream, but getline() demands a non-const argument because it modifies the stream. Try changing it to: ... void someFunc(wistream& read) ... A: Reading characters from the stream modifies the stream. You can't mark the stream const and expect that to work correctly.
{ "pile_set_name": "StackExchange" }
Q: What accounts for the dots in the names of these functions I'm debugging why my Boost.Python module won't load in Ubuntu. Interestingly, the problem comes before my module is actually loaded. A simple, foo C++ module confirms this. The stack trace shows calls to boost::python::* which are absent in our larger lib. Thus, I know that the seg fault occurs before my module is even attempted. The below stacktrace is for the failing library which gets a segfault. My question is, what are the dots in the function names? Not all functions have them. For example, frame #62 0x0000000000547692 in PyErr_PrintEx.part.3.42666 (). I can grep through the Python sources and find PyErr_PrintEx, but I don't find the rest. What is that? #0 0x0000000002344596 in ?? () No symbol table info available. #1 0x00007f5f02d72258 in std::string::_S_construct<char const*> (__beg= 0x7f5efb565f46 "amd64", __end=0x7f5efb565f4b "", __a=...) at /usr/include/c++/4.6/bits/basic_string.tcc:134 __dnew = 116 __r = 0x7 #2 0x00007f5efdf505e3 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 No symbol table info available. #3 0x00007f5efb4ebdfe in pkgInitConfig(Configuration&) () from /usr/lib/x86_64-linux-gnu/libapt-pkg.so.4.12 No symbol table info available. #4 0x00007f5efb7aa395 in ?? () from /usr/lib/python2.7/dist-packages/apt_pkg.so No symbol table info available. #5 0x000000000056d4a4 in PyEval_EvalFrameEx () No locals. #6 0x00000000005747c0 in PyEval_EvalCodeEx () No locals. #7 0x0000000000568e58 in PyImport_ExecCodeModuleEx () No locals. #8 0x000000000042bf11 in load_source_module.39049 () No locals. #9 0x0000000000566f80 in load_package.39142 () No locals. #10 0x000000000042c90b in import_submodule.39103 () No locals. #11 0x000000000046895d in load_next.39108 () No locals. #12 0x000000000042d164 in import_module_level.isra.3.39129 () No locals. #13 0x00000000005167db in builtin___import__.32784 () No locals. #14 0x000000000043a8b6 in PyObject_Call () No locals. #15 0x000000000043b626 in PyEval_CallObjectWithKeywords () No locals. #16 0x000000000056f95b in PyEval_EvalFrameEx () No locals. #17 0x00000000005747c0 in PyEval_EvalCodeEx () No locals. #18 0x0000000000568e58 in PyImport_ExecCodeModuleEx () No locals. #19 0x000000000042bf11 in load_source_module.39049 () No locals. #20 0x000000000042c90b in import_submodule.39103 () No locals. #21 0x00000000004688d3 in load_next.39108 () No locals. #22 0x000000000042d326 in import_module_level.isra.3.39129 () No locals. #23 0x00000000005167db in builtin___import__.32784 () No locals. #24 0x000000000043a8b6 in PyObject_Call () No locals. #25 0x000000000043b626 in PyEval_CallObjectWithKeywords () No locals. #26 0x000000000056f95b in PyEval_EvalFrameEx () No locals. #27 0x00000000005747c0 in PyEval_EvalCodeEx () No locals. #28 0x0000000000568e58 in PyImport_ExecCodeModuleEx () No locals. #29 0x000000000042bf11 in load_source_module.39049 () No locals. #30 0x000000000042c90b in import_submodule.39103 () No locals. #31 0x00000000004688d3 in load_next.39108 () No locals. #32 0x000000000042d326 in import_module_level.isra.3.39129 () No locals. #33 0x00000000005167db in builtin___import__.32784 () No locals. #34 0x000000000043a8b6 in PyObject_Call () No locals. #35 0x000000000043b626 in PyEval_CallObjectWithKeywords () No locals. #36 0x000000000056f95b in PyEval_EvalFrameEx () No locals. #37 0x00000000005747c0 in PyEval_EvalCodeEx () No locals. #38 0x0000000000568e58 in PyImport_ExecCodeModuleEx () No locals. #39 0x000000000042bf11 in load_source_module.39049 () No locals. #40 0x000000000042c90b in import_submodule.39103 () No locals. #41 0x00000000004688d3 in load_next.39108 () No locals. #42 0x000000000042d326 in import_module_level.isra.3.39129 () No locals. #43 0x00000000005167db in builtin___import__.32784 () No locals. #44 0x000000000043a8b6 in PyObject_Call () No locals. #45 0x000000000043b626 in PyEval_CallObjectWithKeywords () No locals. #46 0x000000000056f95b in PyEval_EvalFrameEx () No locals. #47 0x00000000005747c0 in PyEval_EvalCodeEx () No locals. #48 0x0000000000568e58 in PyImport_ExecCodeModuleEx () No locals. #49 0x000000000042bf11 in load_source_module.39049 () No locals. #50 0x0000000000566f80 in load_package.39142 () No locals. #51 0x000000000042c90b in import_submodule.39103 () No locals. #52 0x00000000004688d3 in load_next.39108 () No locals. #53 0x000000000042d164 in import_module_level.isra.3.39129 () No locals. #54 0x00000000005167db in builtin___import__.32784 () No locals. #55 0x000000000043a8b6 in PyObject_Call () No locals. #56 0x000000000043b626 in PyEval_CallObjectWithKeywords () No locals. #57 0x000000000056f95b in PyEval_EvalFrameEx () No locals. #58 0x00000000005747c0 in PyEval_EvalCodeEx () No locals. #59 0x00000000005697b0 in function_call () No locals. #60 0x000000000043a8b6 in PyObject_Call () No locals. #61 0x000000000043b626 in PyEval_CallObjectWithKeywords () No locals. #62 0x0000000000547692 in PyErr_PrintEx.part.3.42666 () No locals. #63 0x000000000056ae1f in PyRun_InteractiveOneFlags () No locals. #64 0x000000000056b155 in PyRun_InteractiveLoopFlags () No locals. #65 0x000000000056bedc in Py_Main () No locals. #66 0x00007f5f04ae576d in __libc_start_main (main=0x41bae0 <main>, argc=1, ubp_av=0x7fff11b14a38, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fff11b14a28) at libc-start.c:226 result = <optimized out> unwind_buf = {cancel_jmp_buf = {{jmp_buf = {0, 8540347331300905646, 4307688, 140733490219568, 0, 0, -8540148959998029138, -8630196532358589778}, mask_was_saved = 0}}, priv = {pad = { 0x0, 0x0, 0x57d430, 0x7fff11b14a38}, data = {prev = 0x0, cleanup = 0x0, canceltype = 5755952}}} not_first_call = <optimized out> #67 0x000000000041bb11 in _start () No locals. A: The .part forms come from GCC optimization. GCC will sometimes split a function into multiple parts to enable better inlining of one part. For example, a function might have a test that leads to a fast case and a slow case. In this situation GCC may choose to put the test and the fast case into a small inlineable function, and then put the slow case in a .part function. This way the fast path can be inlined into callers.
{ "pile_set_name": "StackExchange" }
Q: Boostrapvalidator not fired simple form I am trying to validate my form, the form is having simple elements: but however, the boostrap validator is not called. https://jsfiddle.net/dtjmsy/24hzp7mk/16/ $('#form_hr').bootstrapValidator({ i don' t know where the problem is coming from, can you help me out Cheers A: You need a click event to fire the validate I guess, try this add to the end of your js $(document).ready(function()... : $('#btnsave').click(function() { $('#form_hr').bootstrapValidator('validate'); }); Also if you want to validate field, you need to use their name attribute (ex: name="hr_birthdate") like: <input id="hr_birthdate" name="hr_birthdate" type="text" class="form-control datepicker" placeholder="Please select your birthdate" style="width:100%;" value="" /> Try this one for those update: https://jsfiddle.net/dalinhuang/s3fdej7L/
{ "pile_set_name": "StackExchange" }
Q: Integrating OAuth 2.0 with CodeIgniter https://github.com/alexbilbie/CodeIgniter-OAuth-2.0-Server I have found this on GitHub however the steps to implement don't really help with installing the OAuth code into CodeIgniter and haven't found any really good articles on how to do this Has anyone already done this that can offer me help setting this up? A: Hé Hoang, The oAuth library isn't really self explanatory. This is how I got it working: Basics Read the oAuth 2.0 draft 23 just enough to get a basic idea of oAuth, the roles and flows. Then follow the instructions for installing the controller and libraries from alexbilbie in your CodeIgniter install Install the tables and add an application and some roles (think off a Facebook App and the roles you can request permissions for) Make sure you made your validate_user function in the oAuth_server.php file, at the bottom somewhere Do a request Now you want to perform an Authorization Request as a client. These few easy steps are documented in this section. Edit: Philsturgeon's oAuth 2.0 authorization library could be used to automate this. Described here is the manual way. For the library, this means going to: /index.php/oauth?client_id=IN_YOUR_APPLICATION&redirect_uri=IN_YOUR_APPLICATION&response_type=code&scope=YOUR_ROLE Fill in the variabels with the data you've putten in the database. Debug some of the error's it might give.. If all goes well you dit the following: Sign in -> Authorize application -> See you redirect_uri page with ?code=XXXXXXX You'll want that XXXXXXX code Then on the redirect_uri make a post to /index.php/oauth/access_token With these variabels (you know them all now) client_id (in application table) client_secret (in application table) redirect_uri (in application table: where you want to go to save the access_token) code (the XXXXXX) grant_type (must be 'authorization_code') You know this after reading that section! That post returns a JSON string containing the access_token (or an error). YEAH! What's next Save the access_token in you actual application and use it in requests. On your resource server (probably an API and the same CodeIgniter project as the Authorization server I just explained) you need to validate the access_token before returning results. This works like this: $this->load->library('oauth_resource_server'); if (!$this->oauth_resource_server->has_scope(array('account.basic'))) { // Error logic here - "access token does not have correct permission" show_error('An access token is required to request this resource.'); } else { //GO RETURN RESULTS } Hope this gets you up and running! PS: You need to build some admin area to manage applications, sessions and roles yourself though. Eric A: I used another spark library that is really good to use with codeigniter. here is the good tutorial on how to install this with spark and use it. Oauth tutorial for codeigniter
{ "pile_set_name": "StackExchange" }
Q: Approximations for the partial sums of exponential series Though the question here (Partial sums of exponential series - Stack Exchange) is similar, it is more specialized and I rather need a general approximation for an arbitrary partial sum. Essentially, I am trying to approximate the probability mass function of a particular random variable and I ended up with a Poisson random variable's CDF in the mix. Hence, for my purpose, I need to figure out a reasonable approximation of the sum: $\displaystyle\sum_{k = 0}^{r} \frac{\lambda^k}{k!}$ OR the tail, i.e. $\displaystyle\sum_{k = r}^{\infty} \frac{\lambda^k}{k!}$ Does someone know some approximations for this? Also, if there exist conditions for those approximations to be valid, I'd like to know them as well. Thanks in advance! Addendum: There appears to be a closed form expression for such a partial sum: $\displaystyle\sum_{k = 0}^{r} \frac{\lambda^k}{k!} = e^\lambda \frac{\Gamma(r + 1, \lambda)}{\Gamma(r + 1)}$, where $\Gamma(a, x)$ is defined as: $\displaystyle \Gamma(a, x) = \int_x^\infty t^{a - 1} e^{-t} \,dt$ and $\displaystyle \Gamma(a) = \Gamma(a, 0)$. Is there a simple closed form approximation for the Gamma function? At the end of the day, somehow or the other, I either end up with a summation sign or an integral. I just want to be able to pin down this partial sum as a numeric quantity, that is reasonably approximate. A: Use Taylor's series with remainder. We know that $$ e^\lambda = \sum_{k=0}^r \frac{\lambda^k}{k!} + \frac{e^{c\lambda}\lambda^{r+1}}{(r+1)!}, $$ for some $c \in [0,1]$. Therefore $$ \frac{\lambda^{r+1}}{(r+1)!} \leq e^\lambda - \sum_{k=0}^r \frac{\lambda^k}{k!} \leq e^\lambda \frac{\lambda^{r+1}}{(r+1)!}. $$ You can also get these estimates using more elementary means: $$ \sum_{k=r+1}^\infty \frac{\lambda^k}{k!} = \frac{\lambda^{r+1}}{(r+1)!} \left[ 1 + \frac{\lambda}{r+2} + \frac{\lambda^2}{(r+2)(r+3)} + \cdots \right] < \frac{\lambda^{r+1}}{(r+1)!} \sum_{t=0}^\infty \frac{\lambda^t}{t!} = \frac{\lambda^{r+1}}{(r+1)!} e^\lambda. $$ We can get a different upper bound by comparison to a geometric series, when $\lambda < r+2$: $$ \sum_{k=r+1}^\infty \frac{\lambda^k}{k!} \leq \frac{\lambda^{r+1}}{(r+1)!} \sum_{t=0}^\infty \left(\frac{\lambda}{r+2}\right)^t = \frac{\lambda^{r+1}}{(r+1)!} \frac{r+2}{r+2-\lambda}. $$
{ "pile_set_name": "StackExchange" }
Q: How to return a value See my code and please see what is my problem $('#StartPiCam').click(function(){ $.ajax({ url: "StartPiCam", type: "GET", data: "value=1", //dataType: "json", //success: onDataReceived }); $.ajax({ url: "PiCam_Brightness", type: "GET", data: "Brightness={$('#Brightness').val()}", //dataType: "json", //success: onDataReceived }); }); <INPUT ID="Brightness" TYPE=TEXT NAME="Brightness" VALUE="50" SIZE=12 MAXLENGTH=3 NOFINSIDE="~! ~!" > it returns 0 but I expect returning the value of the input "Brightness" A: Changed the data format This would work according to me. $('#StartPiCam').click(function(){ $.ajax({ url: "StartPiCam", type: "GET", data: {value: '1'}, //dataType: "json", //success: onDataReceived }); $.ajax({ url: "PiCam_Brightness", type: "GET", data: {Brightness: $('#Brightness').val()}", //dataType: "json", //success: onDataReceived }); });
{ "pile_set_name": "StackExchange" }
Q: Go: Anonymous Function Here is the code I've been trying to understand: package main import ( "fmt" ) func squares() func() int { var x int return func() int { x = x + 2 return x * x } } func main() { f := squares() fmt.Println(f()) fmt.Println(f()) fmt.Println(f()) fmt.Println(squares()()) fmt.Println(squares()()) fmt.Println(squares()()) } The result we got: 4 16 36 4 4 4 My question is: Why does the value of x in fmt.Println(squares()()) stay unchanged? A: Short version You are building a new closure each time you call squares. This is exactly as if you built a new Counter object in an object-oriented language: new Counter().increment(); // 4 new Counter().increment(); // 4 ...as opposed to: c = new Counter(); c.increment(); // 4 c.increment(); // 16 Longer version In your function, var x int declares a local variable x: func squares() func() int { var x int return func() int { x = x + 2 return x * x } } As for any function, local variables are visible only inside the function. If you call a function in different contexts, each call has a separate set of memory storage addressable by your local symbols (here x). What happens when you return a function is that any binding currently visible in the scope of your code is kept alongside your function, which is then called a closure. Closures can hold a state, like objects do. Thus your closure can refer to the local variables that were visible when it was created, even when you escape the block where local variables were introduced (thankfully, the GC is here to keep track of the memory associated with those variables). When you define f, you create a fresh closure. Each time you call it you modify the same place referenced by the internal x variable. But if you create fresh closures and call them once each, then you won't see the same side-effects, because each x names a different place in memory.
{ "pile_set_name": "StackExchange" }
Q: Which is a better implementation of a stack data structure (based on an array)? This is a version I made: #include <stdio.h> #include <stdbool.h> #define MAX_STACK_SIZE 255 typedef struct { int array[MAX_STACK_SIZE]; unsigned int count; unsigned int max; } Stack; void initialize(Stack*); void push(Stack*, int value); int* pop(Stack*); bool isEmpty(Stack*); bool isFull(Stack*); int main() { Stack s1; initialize(&s1); for(int i = 0; i < 7; i++) { push(&s1, i); } pop(&s1); push(&s1, 88); push(&s1, 6); int *top; while((top = pop(&s1)) != NULL) { printf("Popping %d from the top of the stack.\n", *top); } return 0; } void initialize(Stack *p) { p->count = 0; p->max = MAX_STACK_SIZE; } void push(Stack *p, int value) { if(!isFull(p)) { p->array[p->count] = value; p->count++; } } int* pop(Stack *p) { if (!isEmpty(p)) { p->count--; return p->array + p->count; } return NULL; } bool isEmpty(Stack *p) { return p->count == 0; } bool isFull(Stack *p) { return p->count == p->max; } This is a version of how it was done from the source I'm learning from: #include <stdio.h> #define MAX_STACK_SIZE 255 #define true 1 #define false 0 #define bool unsigned short int struct stack { int *topOfStack; int *pointer; int count; int max; int theStack[MAX_STACK_SIZE]; }; void initStack(struct stack *stackStruct) { stackStruct->topOfStack = stackStruct->theStack; stackStruct->pointer = stackStruct->theStack; stackStruct->max = MAX_STACK_SIZE; stackStruct->count = 0; } bool pushStack(struct stack *stackStruct, int inputValue) { if(stackStruct->count < stackStruct->max) { *stackStruct->pointer = inputValue; stackStruct->count++; stackStruct->pointer++; return true; } else return false; } int* popStack(struct stack *stackStruct) { if(stackStruct->count > 0) { stackStruct->pointer--; stackStruct->count--; return stackStruct->pointer; } return NULL; } I think there's not so much of a difference between theb, but I just wanted to be sure. In their version, they've used 2 additional pointers in their Stack struct and I removed them because I thought it was not necessary because we could use the array address + count to get the pointer address in their example. I think they used it for convenience reasons. More differences are that I included <stdbool.h> instead of using macros (not really important). On top of that, I've implemented isEmpty() and isFull() methods just for convenience, but don't take it into account when comparing the two implementations since I'm sure they could do the same. I just chose to show the 2 main functions that could be used on a stack. Other than that, since it's an array-based implementation of a stack, I think it was possible to not include the max field in the struct since we define in a macro the stack maximum size, but I added it as well to my implementation for the heck of it. Is there any differences between our implementations? Since I chose to do my own implementation I just want to make sure I that I did implemented it correctly and efficiently. A: push() and pop() have an asymmetry that should be reconciled. push() does not indicate any thing special when the stack is full and a push is attempted. It silently does not do the push. Yet when an pop of an emty stack occurs, a NULL is returned (versus a pointer to int) allowing the calling routine to take evasive action. A symmetric solution would both do something special - or not - on full/empty. A function to inspect the top of stack, without popping, could be added. This IMO would be useful. Additional routines to report current stack depth or stack space left are something to consider. Using unsigned int is OK, especially if the fixed array size is known to always be less than UINT_MAX. I favor size_t for array indexing as it has better portability for large arrays. A way to deal with popping or inspecting an empty stack is, as part of initialize(), to pass an int as the bottom-of-stack. This value does not actually ever get "popped off". The names of the functions are too generic ("initialize") and could well collide with other code. Suggest something like Stack_initialize(), and Stack_push(). The OO part of me wants to see a copy and destructor function too. The destructor could simple do count = max = 0;
{ "pile_set_name": "StackExchange" }
Q: Sketch f(x,y)=(21/4)x^2y over the region x^2 <= y <= 1 Can someone share a technique using MATLAB to plot the surface f(x,y)=(21/4)x^2y over the region x^2 <= y <= 1? Also, if anyone is aware of some tutorials or links that would help with this type of problem, could you please share them? Thanks. Here is another approach: %% close all x=linspace(-1,1,40); g1=x.^2; g2=ones(1,40); y=[]; n=20; for k=0:n y=[y;g1+(g2-g1)*k/n]; end x=x(ones(1,n+1),:); z=21/4*x.^2.*y; meshz(x,y,z) axis tight xlabel('x-axis') ylabel('y-axis') view(136,42) And the result: And finally, you can map the region (-1,1)x(0,1) in the uv-plane into the region bounded by $y=x^2 and y=1 in the xy-plane with the parametrization: f(u,v) = (u\sqrt{v},v) Capture from: https://math.stackexchange.com/questions/823168/transform-rectangular-region-to-region-bounded-by-y-1-and-y-x2 This code produces the same image shown above: close all [u,v]=meshgrid(linspace(-1,1,40),linspace(0,1,20)); x=u.*sqrt(v); y=v; z=21/4*x.^2.*y; meshz(x,y,z) axis tight xlabel('x-axis') ylabel('y-axis') view(136,42) A: First off, let's look at your valid region of values. This is telling us that y >= x^2 and also y <= 1. This means that your y values need to be on the positive plane bounded by the parabola x^2 and they also must be less than or equal to 1. In other words, your y values must be bound within the area dictated from y = x^2 to y = 1. Pictorially, your y values are bounded within this shape: As such, your x values must also be bound between -1 and 1. Therefore, your actual boundaries are: -1 <= x <= 1 and 0 <= y <= 1. However, this only locates our boundaries for x and y but it doesn't handle where the plot has valid values. We'll tackle that later. Now that we have that established, you can use ezsurf to plot surface plots in MATLAB that are dictated by a 2D equation. You call ezsurf like so: ezsurf(FUN, [XMIN,XMAX,YMIN,YMAX]); FUN is a function or a string that contains the equation you want, and XMIN,XMAX,YMIN,YMAX contain the lowest and highest x and y values you want to plot. Plotting without these values assumes a span from -2*pi to 2*pi in both dimensions. As such, let's create a new function that will handle when we have valid values, and when we don't. Use this code, and save it to a new file called myfun.m. Make sure you save this to your current Working Directory. function z = myfun(x,y) z = (21/4)*x.^2.*y; z(~(x.^2 <= y & y <= 1)) = nan; end This will allow you to take a series of x and y values and output values that are dictated by the 2D equation that you have given us. Any values that don't satisfy the condition of x^2 <= y <= 1, you set them to NaN. ezsurf will not plot NaN values. Now, call ezsurf like so: ezsurf(@myfun, [-1,1,0,1]); You thus get: This will spawn a new figure for you, and there are some tools at the top that will allow you interact with your 3D plot. For instance, you can use the rotation tool that's at the top bar beside the hand to rotate your figure around and see what this looks like. Click on this tool, then left click your mouse and hold the left mouse button anywhere within the surface plot. You can drag around, changing the azimuth and the latitude to get the perspective that you want. Edit: June 4th, 2014 Noting your comments, we can decrease the jagged edges by increasing the number of points in the plot. As such, you can append a final parameter to ezsurf which is N, the number of points to add in each dimension. Increasing the number of points will decrease the width in between each point and so the plot will look smoother. The default value of N is 60 in both dimensions. Let's try increasing the amount of points in each dimension to 100. ezsurf(@myfun, [-1,1,0,1], 100); Your plot will look like: Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Binding multivalued column's data into combo box via vba ms access I have a table as follows Where the BranchIds column is a multivalued column referering the ids of the branches table. Some how i need to bind the id and its related value in a combo box residing in another access forms as follows The permission table contains the data of which user is allowed to access which branch. I am unable to bind the branches from the perimssion table to the combo box in my another form. The code i am trying. Got from MSDN after a length search.. Sub BindBranches() Me.comboBranchIds.RowSourceType = "Value List" Dim db As Database Dim rs As Recordset Dim childRS As Recordset Set db = CurrentDb() ' Open a Recordset for the Tasks table. Set rs = db.OpenRecordset("SELECT BranchIds FROM Permissions WHERE UserId = " & Forms!NavigationForm!txtSession.Value) rs.MoveFirst Do Until rs.EOF ' Print the name of the task to the Immediate window. 'Debug.Print rs!TaskName.Value ' Open a Recordset for the multivalued field. Set childRS = rs!BranchIds.Value ' Exit the loop if the multivalued field contains no records. Do Until childRS.EOF childRS.MoveFirst ' Loop through the records in the child recordset. Do Until childRS.EOF ' Print the owner(s) of the task to the Immediate ' window. 'Debug.Print Chr(0), childRS!Value.Value Me.comboBranchIds.AddItem Item:=childRS!Value.Value 'Me.comboBranchIds.RowSource = "SELECT BranchName FROM Branches WHERE ID = " + childRS!Value.Value childRS.MoveNext Loop Loop rs.MoveNext Loop End Sub A: A MultiValue field has little to do with a value list. Just use the RowSource property of the MultiValue field, like: SELECT [TableName].[FieldName] FROM [TableName] ORDER BY [Id]; as the RowSource property for your combobox. Having a filter: SELECT [TableName].[FieldName] FROM [TableName] WHERE UserId = [Forms]![NavigationForm]![txtSession] ORDER BY [Id]; or modify the SQL by code to, say: SELECT [TableName].[FieldName] FROM [TableName] WHERE UserId = 466 ORDER BY [Id]; Applying a revised SQL will automatically requery the combobox.
{ "pile_set_name": "StackExchange" }
Q: Proper way to use @Transactional on a service I have a service, which uses multiple DAOs to do a unit of work like following. The DAOs fetch the data/save by creating a session and commit. In that case, why do i need to have transactional on the service when the dao is managing the session by itself? If something goes wrong in the second DAO, the data in the first DAO is already commited, how do I get around this situation? @Transactional public boolean testService(SomeObject obj){ userDao.save(obj.getUser()); // this dao gets the session from sessino factory and commits there itself. addressDao.save(obj.getAddress()); // something fails here, and the above line has already commited the data, so the data is not Atomic. return true; } A: Usually you don't put @Transactional in your DAO layer but in your service layer. So I suggest you remove @Transactional from you DAOs and keep the one in your service. In that case, if something goes wrong in any of your DAO everything will be rollback. But It's up to you where you want the transaction to start and to finish.
{ "pile_set_name": "StackExchange" }
Q: Print negated words that follows "no,not,never" in a sentence in Python How do I print all negated word that follows "no","not", "never" so on. The sentence is SENTENCE="It was never going to work.I'm not happy" Desired output going,happy (Which follows never and not) Any help ! A: You may not need ntlk for that. I'd split the string (using regex to split according to non-alphanums (or you have an issue with work.I'm part), and build a list comprehension which looks for the previous word belonging to the "negative" words. import re SENTENCE="It was never going to work.I'm not happy" all_words = re.split("\W+",SENTENCE) words = [w for i,w in enumerate(all_words) if i and (all_words[i-1] in ["not","never","no"])] print(words) result: ['going', 'happy']
{ "pile_set_name": "StackExchange" }
Q: Audio won't play in iOS Cordova Phonegap app I am creating a cross platform Cordova Phonegap soundboard app. Everything works fine on the android version but on the iOS version the sound refuses to play. I use SoundJS and PreloadJS to load and play the audio. I used the Phonegap remote debugging server and found out that iOS recognizes the audio as something called "application/octet stream" (see pictures). Everything is fine on Android Android But I get this on iOS iOS I load the audio like this: var sound3= "sound3"; createjs.Sound.registerSound("audio/anybody.mp3", sound3); $(function(){ $( "#sound3" ).bind( "tap", tapHandler ) function tapHandler( event ){ sound3.play(); } }); Can somebody help me out? A: I had a similar issue on one of my Cordova projects. First possible reason: This appears because of different browsers(web views) can play just some specific types. You need to have sound in different formats, such as mp3 or ogg and before playing sound you need to detect maintained format. Look at this documentation Audio canPlayType and make checks before playing Second possible reason : File system issues. iOS resources path is not equal to Android resources path and before sound initialization you need to build a platform-specific path to your local resources And also try to play native browser audio instead of using createjs, like this: var sound3 = document.createElement('audio'); sound3.src = "audio/anybody.mp3"; function tapHandler( event ){ sound3.play(); } $(function(){ $( "#sound3" ).bind( "tap", tapHandler ) });
{ "pile_set_name": "StackExchange" }
Q: How valid is lying to players about the rolls they are making in The Dresden Files? In last weeks Dresden Files game, the players followed the bad guy using a tracking spell, and found him in the projects at an apartment that they knew little about. Seeing his car, they decided to set it aflame to get him out of the apartment (and to identify it). The wizard's spell was a bit too ambitious, and ended up turning it into a roman candle (how I love compels), but the actual plan was successful, as the bad guy came running out to see about his car, and the wizard was barely able to get out of sight before he exited the apartment. As the bad guy was dealing with his vehicle, the group snuck into the vacated apartment. They found that there was still someone there, lounging on the sofa, obviously having partaken of some 'herbal entertainment'. As they entered, I had them make an alertness roll, ostensibly to see something in the apartment- but it was actually an empathy roll, to determine if they saw through the person's deceit. He was high, but was still quite lucid, and was the actual threat. My question is, how valid is deceiving the players about what they are rolling for in order to maintain a layer of the unknown in the game? (Just for completeness, I'll state that the players are still unaware that the person that they fought was just a messenger/dealer/mercenary and that the doped up stoner was playing them...) UPDATE: Though the question could apply to multiple circumstances, the accepted answer brings up a FATE specific point, so I changed the tags and update the question appropriately. A: I would say this is bad practice. You've just had the players roll alertness when they should be rolling empathy. Say one of your characters has Empathy as a Superb skill. They get a huge bonus on the roll. Say they also have only an Average Alertness. You've just denied them a +4 on that roll and they don't even know it! (If they find out they will be rightly angry.) If you want to test a skill without the players knowing you can always roll for them in secret. That way they have no idea what you are checking against merely that you are checking for something. However in a system like FATE where players can spend FATE points to modify rolls, etc I wouldn't even do that. I'd have them roll empathy, you don't necessarily have to explain the roll but that lets them leverage their stunts, powers, and aspects as per regular play. If the players figure out what's going on but fail the rolls then their characters are still in the dark. If the players have their characters act on player knowledge you can gently remind them that their character is blissfully unaware of the problem. It can make some interesting tension in the game the same way you don't want a person to open that door in a horror movie! Roleplaying is partly about being able to separate player knowledge and character knowledge. A: Most answers here fail to address the player vs. character duality and the power vested in the player in FATE. FATE is quite a different system, and age old RPG tradition simply doesn't work with it. The GM is not the ultimate authority(He's even called a referee, not a master), all he does is play the rest of the world, sharing the responsibility of authority with everyone at the table. I'd say, players should be aware that their characters are deceived. In FATE, deceit can be modeled as a maneuver by the deceiver to place an aspect on the deceived. Once a character has the aspect Unaware of the real threat on them, the player should play the character as such. The aspect can be tagged to gain a bonus against the character, or compelled to force the character into a course of action/inaction. Heck, the player can even invoke the aspect for a bonus when acting towards the false belief. A: Lying to them about what they're rolling is silly. It robs the players of their agency. If they're not interested in assessing the situation, they shouldn't be rolling for an assess. If they don't care if they're being lied to, then they shouldn't roll empathy.
{ "pile_set_name": "StackExchange" }
Q: Вывод текущего месяца, задваиваются цифры на php Всем добрый вечер! Нужно вывести месяц, выходные отметить красным, текущую дату обвести. При выводе удваиваются цифры. Подскажите, в чем причина? Заранее спасибо. <style> .normal:hover { background-color: black; color: white; } .weekend:hover { background-color: red; color: white; } </style> <?php echo "<table><tbody><tr>"; for ($i = 1; $i <= 31; $i++) { echo '<td class="normal" style="color:black" normal:hover">'.$i."</td>"; if ($i == 7 || $i == 14 || $i == 21 || $i == 28) { echo '<td class="weekend" style="color:red">'.($i-1)."</td>"; echo '<td class="weekend" style="color:red">'.$i."</td>"; echo "</tr>"; } if ($i == date(j)) { echo '<td style="border:1px solid blue">'.$i."</td>"; } } echo "</tbody></table>"; ?> A: Как можно делать календарь и не использовать DateTime? <style> .month { width: 350px; display: block; } .month .day { display: inline-block; width: 50px; border: #0000ff 1px solid; padding: 5px; color: #1a4580; } .month .day.today { color: white !important; background-color: green !important; font-weight: bold; } .month .day.invis { border: none; } .month .day.weekend { color: red; border: red 1px solid; } </style> <div class="month"> <?php $dt = new \DateTimeImmutable(); $day = \DateTimeImmutable::createFromFormat('d.m.Y', '01.' . $dt->format('m.Y')); $dayOfWeek = 1; while ($dayOfWeek < $day->format('N')) { ?><div class="day invis <?=($day->format('N') > 5 ? 'weekend' : '');?>"></div><? $dayOfWeek++; } while ($day->format('m') == $dt->format('m')) { ?><div class="day <?=($day->format('N') > 5 ? 'weekend' : '');?><?=($day->format('d') == $dt->format('d') ? ' today' : '');?>"><?=$day->format('d');?></div><? $day = $day->add(new DateInterval('P1D')); } ?> </div>
{ "pile_set_name": "StackExchange" }
Q: how to hide kestrel console? I have a .net core app that I want to run in background, but I can't seem to get rid of the console window of Kestrel. Is there any way to hide it without running the app as a windows service? I've tried to remove any reference related to Logger, it didnt help. here is my Program.Main: var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hosting.json", optional: true) .Build(); var hostingUrl = config.GetValue<string>("HostingUrl"); if (string.IsNullOrEmpty(hostingUrl)) { var xmlString = File.ReadAllText(Consts.WebHostBaseFolder + "\\web.config"); var confDoc = XDocument.Parse(xmlString); hostingUrl = confDoc.Element("configuration").Element("appSettings")?.Elements("add")?.FirstOrDefault(e => e.Attribute("key").Value == "HostingUrl")?.Attribute("value")?.Value ?? ""; } var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Consts.WebHostBaseFolder) .UseStartup<Startup>() .UseUrls(hostingUrl) .Build(); host.Run(); Thanks A: the solution was using editbin.exe as described here https://github.com/AvaloniaUI/Avalonia/wiki/Hide-console-window-for-self-contained-.NET-Core-application editbin.exe /subsystem:windows yourapp.exe
{ "pile_set_name": "StackExchange" }
Q: ajax post return the html I have this ajax function (refer below) $.ajax({ url: "processor.php", type:"POST", data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" } , success:function(e){ if(($.trim(e) == "success")){ alert("success"); }else{ alert(e); } },error:function(){ alert("critical error"); } }); assume that I already have the linked script of jquery and the content of those variables that has been declared on the data argument inside ajax function. Now I have a processor.php (refer below) //this is the processor php echo "success"; so base from above references, the ajax function submit a post request to processor.php and then the processor.php will respond "success" string as declared with the "echo success" but what happen is it doesn't get the success response instead the whole html tags on the current page is pop up (alert), why?? any ideas, clues, recommendation, suggestion would be greatly appreciated. Thank you. PS: i know the response is not success but why it popup (alert) the whole html tags in the current page? A: I've been experienced that before, check your folder and file structure and if you're running server side script (such as php) or communicating with database, check your virtual host configuration.
{ "pile_set_name": "StackExchange" }
Q: Tosca - Java Exception while running Swing Application (JTree) I am learning tosca and currently we are trying to run a regression test suite for a legacy Java Swing application. My Test suite contains 4 modules (in JTree) and it is getting failed while clicking a node. The Error I received on the module is, at.tosca.javaengine.common.exceptions.ControlException: node or node-path not found! Detailed information contained in 'JavaEngineException.txt above message is displayed in Executionlist JavaEngineException.txt 22-11-2017 - 17:56:37: IExecWrapperInterface_connectToControl at.tosca.javaengine.common.exceptions.ControlNotFoundException: Unable to find control Index=3;ClassName(s)=[javax.swing.JTable];. at.tosca.javaengine.server.tree.ComponentSearch.getComponent(ComponentSearch.java:218) ->at.tosca.javaengine.server.AbstractJavaEngineCore.findComponent(AbstractJavaEngineCore.java:1129) ->at.tosca.javaengine.server.AbstractJavaEngineCore.connectToControlInternal(AbstractJavaEngineCore.java:936) ->at.tosca.javaengine.server.AbstractJavaEngineCore.connectToControlInternal(AbstractJavaEngineCore.java:922) ->at.tosca.javaengine.server.AbstractJavaEngineCore.connectToControl(AbstractJavaEngineCore.java:313) ->at.tosca.javaengine.server.JavaEngineCore.access$101(JavaEngineCore.java:25) ->at.tosca.javaengine.server.JavaEngineCore$2.runInternal(JavaEngineCore.java:69) ->at.tosca.javaengine.server.control.WorkerThread.run(WorkerThread.java:69) ->java.lang.Thread.run(Unknown Source) ->JNIServer::CallVoidMethod ->CJNIServer::CallVoidMethod 22-11-2017 - 17:58:58: IExecWrapperInterface_setValue at.tosca.javaengine.common.exceptions.ControlException: node or node-path not found! at.tosca.javaengine.server.control.swing.GenericTreeControl.setValueLegacy(GenericTreeControl.java:339) ->at.tosca.javaengine.server.control.swing.GenericTreeControl.setValue(GenericTreeControl.java:88) ->at.tosca.javaengine.server.AbstractJavaEngineCore.setValueInternal(AbstractJavaEngineCore.java:1195) ->at.tosca.javaengine.server.AbstractJavaEngineCore.setValue(AbstractJavaEngineCore.java:686) ->at.tosca.javaengine.server.JavaEngineCore.access$401(JavaEngineCore.java:25) ->at.tosca.javaengine.server.JavaEngineCore$5.runInternal(JavaEngineCore.java:114) ->at.tosca.javaengine.server.control.WorkerThread.run(WorkerThread.java:69) ->java.lang.Thread.run(Unknown Source) ->JNIServer::CallVoidMethod ->CJNIServer::CallVoidMethod NOTE : The same Test suite is working in some other machine and not here. Both are same operating System. A: The problem was TOSCA is faster than our application :) Meaning: The frame was not loaded at the time when TOSCA was trying to scan the next page causing the error, the specific node was not found. Solution: I added a TBoxWait with extra seconds, after that this is working fine.
{ "pile_set_name": "StackExchange" }
Q: LaPlace Transform of a step function Consider the function $f(t)=\begin{cases} 0 \;\;\;\;\;\;\;\;\;\;\;t<\pi \\t-\pi \;\;\;\;\; \pi\leq t \leq2\pi \\ 0 \;\;\;\;\;\;\;\;\;\;\; t\leq 2\pi \end{cases}$ Find the laplace transform of this function. What I did was I wrote it in terms of the step function $f(t)=u_{\pi}(t)[t-\pi]+u_{2\pi}(t)[\pi-t]$ So therefore I set up a integral of $\int_{\pi}^{2\pi} e^{-st}(t-\pi) +\int_{2\pi}^{\infty}e^{-st}(\pi-t)$ The result I end up with is $\dfrac{-2\pi e^{-2\pi s}}{s}-\dfrac{2e^{-2\pi s}}{s^2}+\dfrac{e^{-\pi s}}{s^2}$ However the book ends up with a different answer which I get when I only consider $\int_{\pi}^{2\pi} e^{-st}(t-\pi)$, but not the other. Why are they considering 1 integral when there is in fact 2 that need to be evaluated. Or is the way I defined my step function wrong somewhere. A: The upper boundary of your 1st integral should be $\infty$ instead of $2\pi$. Effectively the part above $2\pi$ in your first integral cancels out with the 2nd integral, resulting in a single integral.
{ "pile_set_name": "StackExchange" }
Q: How to have opacity on my texture in directx 9? Been trying hard to find a solution to this, but the results are pretty bad. Basically I want to draw a texture (it's made up of 2 triangles so it's a quad), and make them have alpha values (0-255, but 0-1 will do too). This is so that I can have that fade in/out effect when I wish. A: Found my answer: Link to Source DWORD AlphaValue; AlphaValue = D3DCOLOR_ARGB(100,255,255,255); mpDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); mpDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); mpDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); mpDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); mpDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); mpDevice->SetTextureStageState(0, D3DTSS_CONSTANT, AlphaValue); mpDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CONSTANT); mpDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); mpDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); pMesh->Draw();
{ "pile_set_name": "StackExchange" }
Q: GREP numeric range I have log file in following format 14:15 14:16 14:17 14:30 14:31 14:41 I want to grep based on 15 minute time interval. So in one case I want to grep time b/w 14:0-14:15 in another case I want to grep time b/w 14:15 14:30 Is there a way to do that in grep ? A: $ awk -v start=14:15 -v end=14:30 'start<=$1 && $1<=end' log.txt 14:15 14:16 14:17 14:30
{ "pile_set_name": "StackExchange" }
Q: IIIF: Get list of ids for all pages in book given one page in book I'm trying to download all page images from a book, and those images are hosted on a IIIF server. Here's the page: https://iiif.bodleian.ox.ac.uk/iiif/image/c444f7e2-ca30-48ae-87b5-54f93d6ed046/full/full/0/default.jpg (I got the id for that page from a GUI page) I thought I could get the metadata for that page with the /info.json route: https://iiif.bodleian.ox.ac.uk/iiif/image/c444f7e2-ca30-48ae-87b5-54f93d6ed046/info.json But this doesn't include all pages in the book. Does anyone know how One can obtain all pages from a book using the IIIF spec/API? Any help would be appreciated! A: Hmm, googling for https://iiif.bodleian.ox.ac.uk/iiif/mirador/c444f7e2-ca30-48ae-87b5-54f93d6ed046 today I saw two results: this post and https://iiif.bodleian.ox.ac.uk/iiif/mirador/c444f7e2-ca30-48ae-87b5-54f93d6ed046. The latter contains all pages in the book, so I suppose the lesson is to search to see if the given IIIF server has a mirador viewer set up, and if so, to ping that... Also, the manifest route contains all links expressed cleanly: https://iiif.bodleian.ox.ac.uk/iiif/manifest/db2fade4-61ee-4a11-a894-19361c551eed.json
{ "pile_set_name": "StackExchange" }
Q: How to detach a process from terminal in unix? When I start a process in background in a terminal and some how if terminal gets closed then we can not interact that process any more. I am not sure but I think process also get killed. Can any one please tell me how can I detach that process from my terminal. So even if I close terminal then I can interact with same process in new terminal ? I am new to unix so your extra information will help me. A: The command you're looking for is disown. disown <processid> This is as close as you can get to a nohup. It detaches the process from the current login and allows it to continue running. Thanks David Korn! http://www2.research.att.com/~gsf/man/man1/disown.html and I just found reptyr which lets you reparent a disowned process. https://github.com/nelhage/reptyr It's already in the packages for ubuntu. BUT if you haven't started the process yet and you're planning on doing this in the future then the way to go is screen and tmux. I prefer screen. A: You might also consider the screen command. It has the "restore my session" functionality. Admittedly I have never used it, and forgot about it. Starting the process as a daemon, or with nohup might not do everything you want, in terms of re-capturing stdout/stdin. There's a bunch of examples on the web. On google try, "unix screen command" and "unix screen tutorial": http://www.thegeekstuff.com/2010/07/screen-command-examples/ GNU Screen: an introduction and beginner's tutorial A: First google result for "UNIX demonizing a process": See the daemon(3) manpage for a short overview. The main thing of daemonizing is going into the background without quiting or holding anything up. A list of things a process can do to achieve this: fork() setsid() close/redirect stdin/stdout/stderr to /dev/null, and/or ignore SIGHUP/SIGPIPE. chdir() to /. If started as a root process, you also want to do the things you need to be root for first, and then drop privileges. That is, change effective user to the "daemon" user or "nobody" with setuid()/setgid(). If you can't drop all privileges and need root access sometimes, use seteuid() to temporary drop it when not needed. If you're forking a daemon then also setup child handlers and, if calling exec, set the close on exec flags on all file descriptors your children won't need. And here's a HOWTO on creating Unix daemons: http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2000: search through out database Some how some records in my table are getting updated with value of xyz in a certain column. Out of hundred of stored procedures, functions, triggers, how can I determine which code is doing this action. Is there a way to search through the database some how through each and every script of the code? Please help. A: One approach is to check syscomments Contains entries for each view, rule, default, trigger, CHECK constraint, DEFAULT constraint, and stored procedure within the database. The text column contains the original SQL definition statements.. e.g. select text from syscomments If you are having trouble finding that literal string, the values could be coming from a table, or they could be being concatenated within a routine. Try this Select text from syscomments where CharIndex('x', text) > 0 and CharIndex('y', text) > 0 and CharIndex('z', text) > 0 That might help you either find the right routine, or further indicate that the values are coming from a table.
{ "pile_set_name": "StackExchange" }
Q: Does `git commit` commit changes that were not added I'm trying to learn git using the 'Pro Git' book by Scott Chacon. When explaining how to Stage modified files (page 18), i understand with git add the files are scheduled for commit and then commited with git commit. It mentions that a commit is done, only the changes that were added will be actually be commited, and if i change a file again, i'd have to add it againg before commit so that all changes are comitted. The text says: It turns out that Git stages a file exactly as it is when you run the git add command.If you commit now, the version of the file as it was when you last ran the git add command is how it will go into the commit, not the version of the file as it looks in your working directory when you run git commit. If you modify a file after you run git add , you have to run git add again to stage the latest version of the file. However, i'm seeing a different behaviour when trying it myself: $ git status #start clean #On branch master nothing to commit (working directory clean) $ echo "hello" >> README.TXT git-question> git add README.TXT #added change to README $ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: README.TXT # $ echo "good bye" >> README.TXT #change README after adding $ git status #now 'hello' is added to be committed but not 'good bye' # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: README.TXT # # Changes not staged for commit: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: README.TXT # $ git commit -m "only hello" README.TXT #commit, i would expect just 'hello' gets commited [master 86e65eb] only hello 1 file changed, 2 insertions(+) $ git status #QUESTION: How come there's nothing to commit?! # On branch master nothing to commit (working directory clean) So the question is: Shouldn't git commit just commit the changes that were added with git add? And if so, why does it commit the second change even if i didn't add it? A: git commit will commit what is currently in the index and therefore what you explicitly added. However, in your example, you are doing git commit README.TXT which will commit the files you specify, that is the current file README.TXT. Just do git commit -m "only hello" to commit the index.
{ "pile_set_name": "StackExchange" }
Q: Does $A=\{x\in\mathbb{Q}: x>0\}$ have any isolated points? Let $A=\{x\in\mathbb{Q}: x>0\}$ and $B=\{x\in\mathbb{R}: x>0\}$. I think that it is easy to understand and to prove that the set $B$ does not contain any isolated points, but can we say the same about set $A$? Are the point's in $A$ all isolated? A: If $x<y \in A$ then $\frac{x+y}{2} \in A$ and $x<\frac{x+y}{2}<y$.Since $A$ contains at least two points, no point in $A$ can be an isolated point.
{ "pile_set_name": "StackExchange" }
Q: Can you give an example why the active player wants to have priority in Beginning of Combat first? I've read this article published on blogs.magicjudges.org explaining the combat shortcut which is about (contrary to the normal proceeding) the Not Active Player (NAP) receiving priority prior to the Active Player (AP) in the Beginning of Combat step (BoC). This is also stated in the Magic Tournament Rules: If the active player passes priority with an empty stack during their first main phase, the non-activeplayer is assumed to be acting in beginning of combat unless they are affecting whether a beginning of combat ability triggers.Then, after those actions resolve or no actions took place, the active player receives priority at the beginning of combat. Beginning of combat triggered abilities (even ones that target) may be announced at this time. At the end of the article the author mentions that normally this is not a problem since most of the time the AP does not want to act first anyway. However, one scenario in which the AP wants to be the first one to receive priorioty in the BoC step is mentioned: AP Acting First in Combat The new structure makes it look like the active player can’t be the first person to act in the beginning of combat step. That’s not true, but it does reflect the fact that the active player needing to act first is unlikely. The only scenario I’m aware of is holding a split second spell while your opponent is floating mana, which is not something that’s going to come up every day! In that situation, the protocol is the same as ever – you ask your opponent if they want to do something with that mana in the main phase. If they do, you’re still in main phase, since they used mana they couldn’t use in beginning of combat, nullifying the default. Otherwise, there is a way to do it, but it does give the opponent some information. While in your main phase, simply say “I do this thing in Beginning of Combat”. Done! Of course, the non-active player has the ability to interrupt and do something in your main phase. That’s not really any different than it was under the previous shortcut. However, I can't reconstruct an example for such a scenario from the information given in these two paragraphs. The following information is given as stated in the paragraphs: NAP has mana floating in the first main phase AP has a split second spell Question: Can you give an example for this scenario in which in order to reach his or hear goal, AP needs to be the first one to to receive priority in BoC to then cast the split second spell? To illustrate the difficulties I have with this, here is an example which doesn't work: AP is in his main phase, controls a Grizzly Bears enchanted with a Rancor. He has a Sudden Spoiling in his hand and enough mana to cast it. NAP has 2 life, controls an Endbringer and has one mana floating. AP wants to have priority in BoC to then cast Sudden Spoiling. He does not want to cast Sudden Spoiling in the main phase because NAP has floating mana he or she can use to respond. If everything goes well, AP then can attack with his bear (4/2, trample) and win the game (NAP now has a 0/2 creature). This example doesn't work because of several aspects: Why does AP need to have priority in BoC to cast Sudden Spoiling before NAP receives priority? Why does AP not let NAP have priority first in BoC, NAP then passes priority, then AP uses his priority to cast Sudden Spoiling? Why doesn't AP cast Sudden Spoiling in his main phase? Sure, NAP has mana floating, but he can't use it to activate Endbringer's cant-attack-ability in response anyway because Sudden Spoiling has split second. A: I think the two different pieces here are in some sense independent. The opponent's floating mana makes you want to act in the beginning of combat step instead of the main phase, and holding a split second spell makes you want to act first in the beginning of combat step instead of waiting for your opponent to act. Holding up mana here isn't necessarily about responding to the split second spell; it's more generally about having more options for actions to take, perhaps after the spell resolves. If you force the mana to empty from their mana pool, you cut off those options. So, here is a scenario in which it matters that you specifically act first during the beginning of combat step: The active player has some mana available and Extirpate in hand, and two attackers with at least two toughness each. The non-active player has one floating red mana, two islands, Electrolyze in hand, and Feeling of Dread in their graveyard. The non-active player is better off casting Feeling of Dread, but they don't want to cast it during their main phase because then the active player could follow up with another creature, possibly with haste. If the active player plays Extirpate during their main phase, the non-active player can use their floating mana to cast Electrolyze. If the active player waits until the non-active player acts in the beginning of combat step, the Feeling of Dread is no longer in the graveyard for the Extirpate to target. They get the best result if they act first in the beginning of combat step.
{ "pile_set_name": "StackExchange" }
Q: Calculating area of sphere with constraint on zenith Let $\mathbb S_R$ be the sphere of radius $R$ centered about the origin. Consider $$A_R= \left\{ (x,y,z)\in \mathbb S_R \mid x^2+y^2+(z-R)^2\leq 1 \right\}.$$ I want to calculate the area of this region of the sphere with radius $R$ about the origin. I already calculated the area of the region of $\mathbb S_R$ of vectors with zenith $\leq \alpha$ is given by $2\pi R^2(1-\cos \alpha)$. For $A_R$, here's my idea. I want to find the zenith $\alpha$ which satisfies $R\sin \alpha=\sin \alpha+R$, since this is the zenith of points of both $\mathbb S_R$ and the unit sphere translated up $R$ units at points which are of the same height. Then, I just want to integrate the zenith $0\leq \phi\leq \alpha$. Solving gives $\phi=\arcsin \frac R{R-1}$ and things get a little messy. On the other hand, another student posted a solution which makes sense. He just writes $\alpha$ should satisfy $2R^2-2R^2\cos\alpha=1$ and then obtains the area of $A_R$ is $\pi$, independently of the radius. Why is my method wrong? Picture A: The problem seems to be what you mean by "the zenith of points of both $\mathbb S_R$ and the unit sphere translated up $R$ units at points which are of the same height." The quantity $R \sin \alpha$ is the distance from the $z$ axis of points whose spherical coordinates are $(R, \theta, \alpha)$ for any $\theta,$ that is, the points on the sphere $\mathbb S_R$ that are at a zenith angle of $\alpha$ relative to the center of that sphere. So far, this makes sense. The quantity $\sin \alpha$ is the distance from the $z$ axis of points on the unit sphere about the origin at a zenith angle of $\alpha.$ This does not change when you translate that sphere upward $R$ units, so it's unclear why you would add $R.$ In fact, since $0 < \sin\alpha \leq 1$ whenver $0 < \alpha < \pi,$ for any such $\alpha$ we would find that $R \sin\alpha \leq R < R + \sin\alpha,$ so it is impossible to have $R \sin\alpha = R + \sin\alpha.$ And that equation is just as impossible for $\alpha = 0$ or $\alpha = \pi$ as long as $R > 0.$ In short, the equation you proposed just does not make sense. Now there may be some sense in equating the heights ($z$ coordinates) of points at the intersection of $\mathbb S_R$ and the unit sphere around $(0,0,R).$ For that, we use the cosine of the azimuth angle relative to each sphere, and we note that the azimuth angle of these points relative to the sphere around $(0,0,R)$ is greater than their azimuth angle relative to $\mathbb S_R.$ There is a relationship between the two angles, but it's not what your equation says. As for the claim that $2R^2-2R^2\cos\alpha=1,$ which the other student presumably did not explain, let $P$ be a point where the two spheres intersect. Then the points $(0,0),$ $(0,R),$ and $P$ form an isoceles triangle with two legs of length $R$ (each a radius of $\mathbb S_R$) and a base of $1$ (the segment from $(0,R)$ to $P,$ which is a radius of the unit sphere around $(0,R).$) If we drop a perpendicular from either $P$ or $(0,R)$ to the opposite leg, we divide the isoceles triangle into two right triangles, one with hypotenuse $R$ and angle $\alpha$ and one with hypotenuse $1$ and angle $\frac\alpha2.$ If we drop a perpendicular from $(0,0)$ to the base of the isoceles triangle, we get two congruent right triangles with hypotenuse $R$ and angle $\frac\alpha2,$ with leg $\frac12$ opposite the angle $\frac\alpha2.$ In either case we end up having to deal with a right triangle with angle $\frac\alpha2.$ Let's try working with the second pair of right triangles. The construction tells us that $R \sin\frac\alpha2 = \frac12.$ Square both sides and multiply by $2$: $$2R^2 \sin^2\frac\alpha2 = 2\left(\frac14\right) = \frac12.$$ Use the trigonometry identity $2 \sin^2\frac\alpha2 = 1 - \cos\alpha$ (which you can get from either the half-angle sine formula or the double-angle cosine formula) to substitute $1 -\cos\alpha$ for $2 \sin^2\frac\alpha2$: $$R^2(1 - \cos\alpha) = \frac12.$$ You can then distribute the $R^2$ over $1-\cos\alpha$ and multiply both sides by $2$ to get the other student's formula if you want, although I think the formula above is more convenient for just plugging into your known area formula.
{ "pile_set_name": "StackExchange" }
Q: How does Sodium Valproate cause neural plasticity I have been reading a fascinating paper: Valproate reopens critical-period learning of absolute pitch 18 individuals were given Sodium Valproate (VPA) for a fortnight during which they trained on a pitch-training game. Results suggest that VPA reopens the plasticity window that normally closes by adolescence. However, the paper seems to suggest that the exact mechanism of action is unknown. Valproic acid is believed to have multiple pharmacological actions, including acute blockade of GABA transaminase to enhance inhibitory function in epileptic seizures and enduring effects on gene transcription as an histone deacetlyase (HDAC) inhibitor (Monti et al., 2009). Of relevance here is the epigenetic actions of this drug, as enhancing inhibition does not reactivate brain plasticity in adulthood (Fagiolini and Hensch, 2000), but reopening chromatin structure does (Putignano et al., 2007). While systemic drug application is a rather coarse treatment, the effects may differ dramatically by individual cell type (TK Hensch and P Carninci, unpublished observations). VPA treatment mimics Nogo receptor deletion to reopen plasticity for acoustic preference in mice (Yang et al., 2012), suggesting a common pathway through the regulation of myelin-related signaling which normally closes critical period plasticity (McGee et al., 2005). Future work will address the cellular actions of VPA treatment in the process of reactivating critical periods. Future MRI studies will also be needed to establish whether HDAC inhibition by VPA induces hyperconnectivity of myelinated, long-range connections concurrent with renewed AP ability (Loui et al., 2011). So it is saying that the standard use of VPA is to increase GABA levels (which keeps firing rate down -- it is used as an antiepileptic), however it also acts as an HDAC inhibitor, which means it causes unwrapping of chromatin and consequently increased mRNA transcription, maybe even transcription of genes that would normally be entirely deactivated in an adult. So my guess is that some protein is getting produced that messages neurons to generate new axon/dendrite growth and/or new synaptic connections. Can anyone clarify how VPA might accomplish plasticity? EDIT (one month later): I have more detail, but I still can't quite make the connection. Here goes: Neurites get wrapped by myelin/oligodendrocyte, which produces and exudes some of the chemical messagers {Nogo, OMgp, MAG}. The membrane surface of the neurite contains nogo 66 receptors (NgR-s) that get triggered by these messagers and inform the neuron to inhibit axon-growth. Somehow the 'HDAC inhibition' property of VPA is unwinding DNA enough to alter transcription rates of certain proteins, and one of these must be disabling the NgR. But how is this happening? A: As far as I can see this paper is being a little misleading, by saying "VPA mimics Nogo-66 receptor deletion". The action of VPA doesn't seem to be related to this receptor. It seems that blocking this receptor and applying VPA both increase plasticity, but it is like taking a car or taking a train -- entirely different modes of transport that achieve the same effect. VPA seems to facilitate LTP through increased availability of relevant proteins. That is unconnected with growing new neural structure. The principal problem with growing new structure is, as hinted at the end of the question, that the adolescent/adult brain secretes a chemical that gets picked up by Nogo 66 receptor, which signals to collapse the axon growth cone. It's why adult humans can't recover from spinal injuries. The axons won't reconnect. It so happens that a small molecule Nogo Antagonist has recently been developed by Professor Strittmatter. He was kind to reply to my query, and I learned that this molecule is currently in the early stages of FDA approval. It's a very exciting discovery! I would caution anyone against taking VPA -- I have been encountering chest pains since experimenting with it (even though I dropped the experiment after a week due to pain). It looks as though this pain is inflammation of the stomach lining and a common reaction to VPA (VPA is an acid!). If someone is determined to take VPA, they should at least investigate taking it together with Omeprazole, which discourages the stomach from producing excess acid. I am disappointed that I now need to take omeprazole quazi-regularly, it appears that my brief VPA experiment has caused some long-term upset in my chemical balance. Also of note is that (again discovered by Strittmatter) Ibuprofen has been found to also interrupt the signalling pathway that leads to axon growth collapse. But it requires a high dosage, and ibuprofen also causes a similar imbalance.
{ "pile_set_name": "StackExchange" }
Q: DataGrid In Java Struts Web Application After scouring the web I have edited my question from the one below to what it is now. Ok I seem to understand that I don't need all the capabilities of excel right now. I think i am satisfied having a data grid to display data. Basically i am working on Struts 2 and I wat my jsp page to have an excel like feel and hence looks like even a datagrid is sufficient. I came across This Technology I am not sure whether I must go ahead and use it. Any other suggestions, alternatives are welcome The older version of the question "I have a java web application running on windows currently. I may host it in future in a Linux Server. My application allows people to upload data. I want to display the data they have uploaded in an excel file and render it in a portion of my webpage. How do I go about this ?" A: Basically you would need to read the excel files, get the data in some kind of java objects, and then show it back to user as a normal HTML page with tables etc.. If you want to show the excel files in such a way that your users are also able to edit these then you need to look into javascript / ajax to make a UI as per your needs. An easy and open source way of reading the uploaded excel files in java is via Apache POI. It is capable of reading .xls files as well as the newer OOXML .xlsx files. http://poi.apache.org/spreadsheet/ They have very helpful examples which can get you started within 10 minutes.. http://poi.apache.org/spreadsheet/quick-guide.html If you can allow data to go to another site, then you can use ZOHO. Their online Excel Editing is reasonably good and you don't really have to do anything much.
{ "pile_set_name": "StackExchange" }
Q: How do I get to the "Fowl Lair" In a separate forum I was reading, a poster described an easter egg area called "The Fowl Lair". I could imagine that this is the replacement for the Cow Level from Diablo II, but I hope that is not the case. How do I get to this area? Are there any monsters or treasure to be had, or any other benefit to going there? A: To get to the Fowl Lair you need to use the Ancient Device in Desolate Sands. It is one of the 10 possible outcomes of using the Ancient Device. So take note that not only is the spawn of the device random but there's only 10% of getting the Fowl Lair. Where are all the random dungeons? This contains a community wiki of random locations and which zones they are in. It was revised to add Fowl Lair based on this forum thread: http://us.battle.net/d3/en/forum/topic/5149619068 The plateau on the map (obviously random location, but that's the shape) The Ancient Device The entrance to the Fowl Lair after succesfully spawning it using the device (took A LOT of tries) Inside the Fowl Lair
{ "pile_set_name": "StackExchange" }
Q: How do I ensure a sequence has a certain length? I want to check that an IEnumerable contains exactly one element. This snippet does work: bool hasOneElement = seq.Count() == 1 However it's not very efficient, as Count() will enumerate the entire list. Obviously, knowing a list is empty or contains more than 1 element means it's not empty. Is there an extension method that has this short-circuiting behaviour? A: This should do it: public static bool ContainsExactlyOneItem<T>(this IEnumerable<T> source) { using (IEnumerator<T> iterator = source.GetEnumerator()) { // Check we've got at least one item if (!iterator.MoveNext()) { return false; } // Check we've got no more return !iterator.MoveNext(); } } You could elide this further, but I don't suggest you do so: public static bool ContainsExactlyOneItem<T>(this IEnumerable<T> source) { using (IEnumerator<T> iterator = source.GetEnumerator()) { return iterator.MoveNext() && !iterator.MoveNext(); } } It's the sort of trick which is funky, but probably shouldn't be used in production code. It's just not clear enough. The fact that the side-effect in the LHS of the && operator is required for the RHS to work appropriately is just nasty... while a lot of fun ;) EDIT: I've just seen that you came up with exactly the same thing but for an arbitrary length. Your final return statement is wrong though - it should be return !en.MoveNext(). Here's a complete method with a nicer name (IMO), argument checking and optimization for ICollection/ICollection<T>: public static bool CountEquals<T>(this IEnumerable<T> source, int count) { if (source == null) { throw new ArgumentNullException("source"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "count must not be negative"); } // We don't rely on the optimizations in LINQ to Objects here, as // they have changed between versions. ICollection<T> genericCollection = source as ICollection<T>; if (genericCollection != null) { return genericCollection.Count == count; } ICollection nonGenericCollection = source as ICollection; if (nonGenericCollection != null) { return nonGenericCollection.Count == count; } // Okay, we're finally ready to do the actual work... using (IEnumerator<T> iterator = source.GetEnumerator()) { for (int i = 0; i < count; i++) { if (!iterator.MoveNext()) { return false; } } // Check we've got no more return !iterator.MoveNext(); } } EDIT: And now for functional fans, a recursive form of CountEquals (please don't use this, it's only here for giggles): public static bool CountEquals<T>(this IEnumerable<T> source, int count) { if (source == null) { throw new ArgumentNullException("source"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "count must not be negative"); } using (IEnumerator<T> iterator = source.GetEnumerator()) { return IteratorCountEquals(iterator, count); } } private static bool IteratorCountEquals<T>(IEnumerator<T> iterator, int count) { return count == 0 ? !iterator.MoveNext() : iterator.MoveNext() && IteratorCountEquals(iterator, count - 1); } EDIT: Note that for something like LINQ to SQL, you should use the simple Count() approach - because that'll allow it to be done at the database instead of after fetching actual results. A: No, but you can write one yourself: public static bool HasExactly<T>(this IEnumerable<T> source, int count) { if(source == null) throw new ArgumentNullException("source"); if(count < 0) return false; return source.Take(count + 1).Count() == count; } EDIT: Changed from atleast to exactly after clarification. For a more general and efficient solution (which uses only 1 enumerator and checks if the sequence implements ICollection or ICollection<T> in which case enumeration is not necessary), you might want to take a look at my answer here, which lets you specify whether you are looking forExact,AtLeast, orAtMost tests. A: seq.Skip(1).Any() will tell you if the list has zero or one elements. I think the edit you made is about the most efficient way to check the length is n. But there's a logic fault, items less than length long will return true. See what I've done to the second return statement. public static bool LengthEquals<T>(this IEnumerable<T> en, int length) { using (var er = en.GetEnumerator()) { for (int i = 0; i < length; i++) { if (!er.MoveNext()) return false; } return !er.MoveNext(); } }
{ "pile_set_name": "StackExchange" }
Q: catch integrity constraint error in symfony and doctrine I have two tables which are: Category: |id | cat_name | | 1 | nameone | | 2 | nametwo | | 3 | namethree | News: | id | id_cat | title | | 1 | 1 | title1 | | 2 | 2 | title2 | | 3 | 3 | title3 | | 4 | 3 | title4 | | 5 | 3 | title5 | i use doctrine:generate-module backend category Category and i have a list Category with executeEdit, Update etc. If i delete Category id 3 - namethree then I get the following error SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails . How can I make sure that if I delete Category 3 then all News for Category 3 are moved to Category 2 for example without an error? How can catch this? A: You have to configure your table schema for News to handle foreign key changes with ON DELETE: Either "set to null", or "set to default", or "set to specific value", or "delete". Not sure if you can do this variably, though, but if you think about it that'd be insane: You have referential integrity precisely because you want your relations to be strictly enforced. Randomly changing them if you delete a category row would go completely counter to that. Much better to handle this correctly yourself by first UPDATEing the to-be-modified rows. UPDATE News SET id_cat = 2 WHERE id_cat = 3; DELETE FROM Category WHERE id = 3; (I don't know the appropriate Symfony/Doctrine method to affect this.) Your available options depend on your database. You can always say ON DELETE CASCADE to delete all dependent rows; other options may or may not be available to you.
{ "pile_set_name": "StackExchange" }
Q: How to Java doc an invariant for a class? I'm wanting to know where exactly the comment should go and what keyword I should use as I cant really seem to find an example online, should I for example do this? /** * @invariant invariant example */ public class Example { } A: There are a few possibilites @Contract annotations Some examples @Contract("_, null -> null") - method returns null if its second argument is null. @Contract("_, null -> null; _, !null -> !null") - method returns null if its second argument is null, and not-null otherwise. @Contract("true -> fail") - a typical assertFalse() method which throws an exception if true is passed to it. See https://www.jetbrains.com/help/idea/2016.2/contract-annotations.html for more details. You could use them without IntelliJ IDEA. IDEA just has smart support for those annotations. It will check your method code if specified invariants are really met. Textual description This method does not cover all cases. For more complex dependencies between fields you need to describe invariant using english words. For example, https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#put(K,%20V) If the map previously contained a mapping for the key, the old value is replaced by the specified value. Exceptions Also, exceptions can be used to describe and enforce invariant. For above-mentioned Map.put method we have following exceptions for invalid arguments (arguments that would break class invariant) @throws UnsupportedOperationException if the put operation is not supported by this map @throws ClassCastException if the class of the specified key or value prevents it from being stored in this map @throws NullPointerException if the specified key or value is null and this map does not permit null keys or values @throws IllegalArgumentException if some property of the specified key or value prevents it from being stored in this map
{ "pile_set_name": "StackExchange" }
Q: perform Action<> in main thread I'm writing an app, that performs very long requests at background. After each request I need to send result to main form. So, here is a code: Form1.cs private async void StartButton_Click(object sender, EventArgs e) { await Logic.GenerateStackAsync(stackSettings, delegate(FullOrder transaction) { lastOrderId.Text = transaction.OrderId; } ); MessageBox.Show("Completed!"); } Logic.cs: public static bool GenerateStack(StackSettings stackSettings, Action<FullOrder> onOrderCreated = null) { for(var i = 0; i < 10; i++) { // long, long request, replaced with: System.Threading.Thread.Sleep(10000); if (onOrderCreated != null) { onOrderCreated.Invoke(order); // tried to change it with onOrderCreated(order), no results. } } return true; } public static Task<bool> GenerateStackAsync(StackSettings stackSettings, Action<FullOrder> onOrderCreated) { return TaskEx.Run(() => GenerateStack(stackSettings, onOrderCreated)); } It throws an exception: "Control 'lastOrderId' accessed from a thread other than the thread it was created on.", which can be fixed by adding CheckForIllegalCrossThreadCalls = false;, but I think that this is a bad experience. How make it right? Thank you in advance. P.S. Sorry for bad English. A: I would say that you need to use Control.Invoke to solve that problem: See http://msdn.microsoft.com/library/system.windows.forms.control.invoke(v=vs.110).aspx
{ "pile_set_name": "StackExchange" }
Q: Auto threshold in ImageJ/FIJI with Python I'm trying to write python scripts in ImageJ and I'm having problems with autothresholding. It won't let me use the IJ.setAutoThreshold("Default dark"). An example bit of code is below (with a few things left out for clarity): from ij import IJ, ImagePlus from java.lang import Runtime, Runnable import os for i in filepaths: #filepaths being the files I'm opening IJ.open(i) IJ.run("Split Channels") #this is splitting a two channel image imp = IJ.getImage() imp.close() #this is closing the channel I don't want IJ.setAutoThreshold("Default dark") #this is trying to set a threshold Setting the auto threshold here gives AttributeError: type object 'ij.IJ' has no attribute 'setAutoTrheshold' How can I access ImageJ's threshold function? Cheers! A: Have a look at the javadoc: IJ has a method taking two arguments setAutoThreshold(ImagePlus imp, String method) so in your case IJ.setAutoThreshold(imp, "Default dark") should work.
{ "pile_set_name": "StackExchange" }
Q: Right way to create a background job in an elixir phoenix app def create(conn, %{"data" => %{"attributes" => user_params}}) do changeset = User.changeset(%User{}, user_params) case Repo.insert(changeset) do {:ok, user} -> UserMailer.send_welcome_email(user) conn |> put_status(:created) |> render("show.json", model: user) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(MyApp.ChangesetView, "error.json", changeset: changeset) end end In this controller action, UserMailer.send_welcome_email is synchronous, and the request waits. I wanted to make it asynchronous, so spawned a process like this instead spawn_link(fn -> UserMailer.send_welcome_email(user) end) The request doesn't not wait until the mail has been sent. Though it works, is it the right way to do ? Are there any chances that these process become orphan or they just die after immediately executing? Should we create a Supervisor instead? Should we use a library like https://github.com/akira/exq instead? (I feel even if spawn_link fails, and logs it in our phoenix logs, it would do) A: Starting a process using spawn_link/1 will cause a bidirectional link, so whichever of the spawning process and the newly spawned process that happens to die first will kill the other one (unless it's trapping exits, which it probably shouldn't be). That's great in some cases, and not so great in others; if it takes a long time to send that e-mail, for example, the Phoenix request might finish first, and risk killing off the spawned process. Due to the linking, however, there shouldn't be any risk of the processes getting orphaned. A better approach is definitely to create a Supervisor (or using Task.Supervisor), and you could roll your own background job setup rather easily. However, it might be worth looking at something like exq that you mentioned, or Toniq for example, that could possibly have everything you need already; especially things like retries in case of failure, and presistence. There are also some other interesting options in the Awesome Elixir list if you want to try out a few different alternatives.
{ "pile_set_name": "StackExchange" }
Q: How to calculate Fourier transform of this function? the function is given by $$f(t)=\dfrac{1}{e^{at}-1}$$ Now, i know from the definition i've to evaluate this integral $$\begin{align}\mathcal{F}[f(t)]&=\int_{0}^{\infty}e^{-j \omega t}\left(\dfrac{1}{e^{at}-1}\right)\,dt \\&=\sum_{n=1}^{\infty}\int_{0}^{\infty}e^{-t(j\omega+an)}\,dt \\&=\sum_{n=1}^{\infty}\dfrac{1}{j\omega+an}\end{align}$$ Is it the right way to approach ? A: As far as I can tell, the integral diverges, but here's how one can attack the problem using known Fourier Transform pairs and Fourier Transform theorems. I assume $a > 0$, $H(t)$ is the Heavyside unit step function, and I'll use the substitution $\omega = 2\pi s$ to use the Fourier Transform form with which I'm most comfortable. $$I = \int_{0}^{\infty} e^{-2\pi ist}\left(\dfrac{1}{e^{at}-1}\right)dt$$ $$= \dfrac{1}{2} \int_{0}^{\infty} \dfrac{1}{e^{\frac{a}{2}t}}\cdot\dfrac{2}{e^{\frac{a}{2}t}-e^{-\frac{a}{2}t}}\cdot e^{-2\pi i st}dt$$ $$= \dfrac{1}{2} \int_{-\infty}^{\infty} H\left(\frac{a}{2}t\right) e^{-\frac{a}{2}t}\text{cosech}\left(\frac{a}{2}t\right)e^{-2\pi ist}dt$$ $$= \dfrac{1}{2} \mathscr{F}\left\{H\left(\frac{a}{2}t\right) e^{-\frac{a}{2}t}\right\}*\mathscr{F}\left\{\text{cosech}\left(\frac{a}{2}t\right)\right\}$$ Looking up the transform pairs in The Fourier Transform and Its Applications, by Ronald N. Bracewell, amd applying some Fourier Transform theorems found in that same text, we have $$= \dfrac{1}{2}\dfrac{2}{a}\left[\dfrac{1-i2\pi s \frac{2}{a}}{1+\left(2\pi s\frac{2}{a}\right)^2}\right]*-i\dfrac{2\pi}{a}\tanh\left(\pi s \frac{2\pi}{a}\right)$$ Which after a bit of algebra and substituting $2\pi s = \omega$ yields $$= -\left(\dfrac{\pi}{a}\right)^2\left(\dfrac{1}{\dfrac{\pi}{a}\omega -i\dfrac{\pi}{2}}\right) * \tanh\left(\dfrac{\pi}{a}\omega \right)$$ With a little thought, it's easy (for me at least) to see that the above convolution diverges.
{ "pile_set_name": "StackExchange" }
Q: How to get Canonical ID from GCM I am trying to get a unique ID for my device so I can get push notifications from my server. As all turorials say : I register using GMC: GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String regid = gcm.register(PROJECT_NUMBER); // <---- duplicated if uninstalled/ reinstalled SendRegIdToServer(regId); Now, I send the regId my server and save on device. The problem comes when I uninstall and reinstall, since the local storage is lost, I ask GCM to register again and I get a new registration ID. Because of this, my server is having duplicates of the same device. I looked at SO butlot of questions are on GCMRegistrar, which is deprecated now. People say use Canonical ID, which is unique. But how do I get it ? I am using gcm.register and using that ID, which obviously is duplicating on the server. Appreciate any help. A: The Canonical id is returned in the response when you send a message from your server to google's gcm server. https://developer.android.com/google/gcm/http.html#response Interpreting a success response When a JSON request is successful (HTTP status code 200), the response body contains a JSON object with the following fields: Field Description multicast_id Unique ID (number) identifying the multicast message. success Number of messages that were processed without an error. failure Number of messages that could not be processed. canonical_ids Number of results that contain a canonical registration ID. See Advanced Topics for more discussion of this topic. results Array of objects representing the status of the messages processed. The objects are listed in the same order as the request (i.e., for each registration ID in the request, its result is listed in the same index in the response) and they can have these fields: message_id: String representing the message when it was successfully processed. registration_id: If set, means that GCM processed the message but it has another canonical registration ID for that device, so sender should replace the IDs on future requests (otherwise they might be rejected). This field is never set if there is an error in the request. error: String describing an error that occurred while processing the message for that recipient. The possible values are the same as documented in the above table, plus "Unavailable" (meaning GCM servers were busy and could not process the message for that particular recipient, so it could be retried). If the value of failure and canonical_ids is 0, it's not necessary to parse the remainder of the response. Update Below is some more info on Canonical IDs. Basically, if somehow the device reg id becomes out of sync with what Google thinks it should be, then when your server sends a request with the out-of-sync id, the gcm server will include in it's response , the correct id to be used in the future. Think about it, the way this works is; your server should have stored the reg id when the device registered with gcm. Your server sends a request to gcm with that id, gcm uses that id to send a message to your device. GCM can't the reg id on your device without telling the server about it. If it did your server would just keep sending the wrong reg id. Instead, gcm tell the server that the reg id it is using for a particular device is bad, your server can then send a message to the device to update its stored reg id to what it should be, and then the device can ack the change in REG IDs. The info below implies there is some time limit as too how long the "bad" id can still be used to send messages. I think the assumption is that it should be long enough for your server to change the device id (via a gcm message using the "bad" id) Canonical IDs On the server side, as long as the application is behaving well, everything should work normally. However, if a bug in the application triggers multiple registrations for the same device, it can be hard to reconcile state and you might end up with duplicate messages. GCM provides a facility called "canonical registration IDs" to easily recover from these situations. A canonical registration ID is defined to be the ID of the last registration requested by your application. This is the ID that the server should use when sending messages to the device. If later on you try to send a message using a different registration ID, GCM will process the request as usual, but it will include the canonical registration ID in the registration_id field of the response. Make sure to replace the registration ID stored in your server with this canonical ID, as eventually the ID you're using will stop working.
{ "pile_set_name": "StackExchange" }
Q: Poll about your proof of resolution of singularities and a request for advice The questions first: What is the proof of resolution of singularities that you know? Why am I asking?: There are a number of proofs of resolution of singularities of varieties over a field of characteristic zero, all with more or less similar flavor but different in technical details and in choices that the resolution algorithm allows us to make. When writing a proof that uses specific features of some of those details I can't stop being uneasy about assuming the reader read about the specific constructions elsewhere. I would like to know from MOers what proof you have seen and if you have a reason for the choice, if it was a choice, I would like to hear it too. Maybe asking about what you know is too invasive. I am just asking for the proof that you happened to find in your way, even you have only read a few lines of it. The purpose of the question: The conspicuous one. To get a sense, by a rough approximation and a small sample, of what proofs are more culturally known. Have a concrete feeling when sending a reader to find the details in other paper, either of feeling OK with it or of guilt. It is a question about fashion, which also has its role in mathematics... and knowing what the fashion is is useful. What details?: Although I had in mind a specific detail of the proofs I didn't mention it because it is not the only one that changes from proof to proof and because the result of the poll gives information about all of them. Examples are: the resolution invariant, the ways of making the local descriptions of the centers of blowings-up match to form a globally defined smooth subvariety, the ways of getting functoriality and the different meanings that functoriality can have... (edit) Forgot the "request for advise": If you have would like to give advise about how you have dealt with similar situations and describe your example that is welcomed. It is a community wiki question, so feel free to change what is said here if needed or if you want the poll to also give information about other questions that you would like to be answered. (or for correcting the English!) A: All right. Since you ask, the only treatment of resolution of singularities that I have even glanced at is Herwig Hauser's 2003 Bulletin article: http://www.ams.org/journals/bull/2003-40-03/S0273-0979-03-00982-0/S0273-0979-03-00982-0.pdf I can't remember how much of it I ever read -- certainly less than half -- but I do remember enjoying the article when it came out, getting something out of it, and finding the pictures attractive and better-than-usually integrated into the text. (I am not a very visual thinker; when someone shows a fancy color portrait in their talk and claims it is a cross section of a K3 surface -- or whatever -- I wonder whether I am being put on.) Because the article is freely available online, it would seem to make a good reference, provided of course that it contains the information you want to cite. A: Several years ago I looked carefully at several of these. The first that I looked carefully is: http://front.math.ucdavis.edu/0401.5401 by Wlodarczyk. This article has the advantage that it is self-contained and complete and relatively short. It lacks discussion of examples in higher dimensions and motivation that other papers have, as it is quite to the point. I also read http://front.math.ucdavis.edu/0206.5244 by Bravo, Encinas and Villamayor which has a lot more discussion (it's about 100 pages instead of about 30). There is also Koll\'ar's quite recent book which I have only skimmed, and I've read large parts of Bierstone and Milman's paper. There have been a number of simplifications and improvements over the past decade (and a little more) so the more modern accounts are certainly more streamlined (and give better results in some directions). I should point out that many of the more modern proofs incorporate ideas from each other, making the proof more and more streamlined. A: As a bit of an update on the subject in characteristic 0, there have been some more recent papers which try to vary the desingularization algorithm slightly to achieve a better resolution of singularities, for example algorithms which avoid simple normal crossings or semi-simple normal crossings or even "minimal" singularities. These proofs shed light on the original algorithm while showing how far we can push this approach. If you read through some of these articles, you will not only get a glimpse of the original algorithm, but you will see how the desingularization invariant can be used as a computational tool. Here are the more recent articles on the topic: http://arxiv.org/pdf/1206.5316.pdf http://arxiv.org/pdf/1109.3205.pdf http://arxiv.org/pdf/1311.7156.pdf http://arxiv.org/pdf/1107.5595.pdf http://arxiv.org/pdf/1107.5598.pdf I found the following two articles very enlightening when I was learning about the topic: http://arxiv.org/pdf/alg-geom/9709028.pdf http://arxiv.org/pdf/math/0702375.pdf The first goes into great detail about some of the subtle points of the algorithm, while the second gives a rather concise proof of resolution of singularities. Finally, the article below is quite distinct in that it is the first time (as far as I know) that the complexity of the desingularization algorithm has been studied - that is, how many steps in the algorithm occur before it terminates? Can we find an upper bound? You can read more about that here: http://arxiv.org/pdf/1206.3090.pdf
{ "pile_set_name": "StackExchange" }
Q: How do I retain an Android alertdialog sometime I have an AlertDialog in the activity I used, as: AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.setTitle("Unanswered Questions"); ad.setMessage("You have not answered all the questions."); ad.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.wait(5000); dosometing(); } }); ad.show(); I want click OK, it does not disappear. I click OK,and do dosometing(),then it disappear. I meet question, when i click OK,the dialog disappear. I know I can use activity and theme deal with this problem. if I can use the AlertDialog, Thank you. A: what is it that you are waiting on before removing your dialog? If it is some sort of processing task, put it all in its own method that returns a boolean and call that method just before you call dialog.cancel(). Like so: ... public void onClick(DialogInterface dialog, int id) { boolean closeNow = dosometing(); if (closeNow) { dialog.cancel(); } } ... that should work. The program should wait for dosomething() to return before continuing. If not try: ... public void onClick(DialogInterface dialog, int id) { recursiveMethod(dialog, id) } ... private void recursiveMethod(DialogInterface dialog, int id) { boolean closeNow = dosometing(); if (closeNow) { dialog.cancel(); } else { recursiveMethod(dialog, id); } } Edit: I'd love to know if the second one works. It might not be able to cancel the dialog, but I've never tried doing recursion like that in java before. If you give it a shot, let me know if it throws up an error. Edit #2, that will actually spawn a bunch of calls to doSomething(). . . not the ideal situation.
{ "pile_set_name": "StackExchange" }
Q: How to create a Google Reader? I need to create a web tool like Google Reader for my college project. I have 2 question about it: 1) How Google Reader track the read and unread posts ? 2) Google Reader save every post in the db or load the feeds at the moment ? A: assign a hash to a single feed post (ie. date+url+??? = hash to identify a single post) loads them on the fly would be my guess, maybe caches a limited number per user.
{ "pile_set_name": "StackExchange" }
Q: php Content-type: text/css not working I have a style.css: <link href="/file.css" rel="stylesheet" type="text/css" property='stylesheet'/> #menu{ background:red; //file.css content } and after that a php: <link rel='stylesheet' type='text/css' href='/color.php' /> //color.php content: header("Content-type: text/css", true); include_once("mysqli.php"); session_start(); $userid=$_SESSION['id']; $stmt = $mysqli_link->prepare("SELECT site FROM cores where user=? limit 1"); $stmt->bind_param('i', $userid); $stmt->execute(); $stmt->bind_result($color); $stmt->fetch(); $stmt->close(); if($color=="blue"){ $m="blue"; } else if($color=="green"){ $m="green"; } echo" #menu{ background-color:$m; } "; If I open the color.php it prints well the colors. but in the page it is not overwritten the style.css #menu red color. What is wrong? any help? thank you friends! A: Try to change the order of your first lines like this : session_start(); include_once("mysqli.php"); header("Content-type: text/css"); The Content-type can be overrided by the script you are including (mysqli.php). Also, a "session_start" should be ALWAYS the first thing you do in a php script that uses sessions. (The reason why I put session_start() in first position)
{ "pile_set_name": "StackExchange" }
Q: How to convert Int To String in C# without using library functions? What is the most effective code to convert int to string without using a native convert function. public static void Main(string[] args) { string y = Convert(990); Console.WriteLine(y); Console.ReadLine(); } public static string Convert(int x) { char[] Str = new char[20]; int i = 0; while (x != 0) { Str[i++] = x % 10 + '0'; x = x / 10; } return Str.ToString();// How do I handle this without the native function? } The above doesnt seem to work. Please advise. A: Here's a solution without a String constructor or a .ToString() call. This one handles negative numbers. It's a bit too 'clever' for my taste, but it's an academic exercise anyway... void Main() { Console.WriteLine(Convert(-5432)); } String Convert(int i) { return String.Join("",Digits(i).Reverse()); } IEnumerable<char> Digits(int i) { bool neg = false; if(i==0) {yield return '0'; yield break;} if(i<0) { i = -i; neg = true;} while (i!=0) { char digit = (char)(i % 10 + '0'); i = i / 10; yield return digit; } if(neg) yield return '-'; yield break; }
{ "pile_set_name": "StackExchange" }
Q: Photomosaic non-georefferenced images using open-source software I have a directory of images that were captured by drone. The images have GPS info in the EXIF tags but are not georefferenced and do not have world files. I would like to merge these photos into a single mosaic file that I can then georefference in a GIS. Are there any open-source application that will create the mosaic or am I stuck purchasing an expensive application like Agisoft Photoscan? I want to create the mosaic automatically and not piece it together one image at a time with something like Photoshop. A: You have Open Drone Map to georeference photos and create Orthomosaic. You can do in you machine with Open drone Map desktop or ODMWeb. ODM Desktop works in linux, so if you have a different OS you need to use a virtual machine, Docker or Vagrant. This software works similar than PhotoScan, but the results aren't so good as PS and you can manage at the same level. But it's free and it'll generate: 3d model Point cloud (.obj or .las file) DSM Orthomosaic To improve the output, you can make an orthorectification with georeferencer plug-in in QGIS (also free)
{ "pile_set_name": "StackExchange" }
Q: Replace text in the Title In a string displayed by <?php the_title(); ?> I have to replace all & characters with and. Here is the code I've tried without success: <?php $wptitle = the_title(); $wptitle = str_replace('&', 'and', $wptitle);?><?php echo $wptitle; ?> The full code to be replaced: <h2><a href="<?php if(get_post_meta($post->ID, 'links_link_custom', true)): ?><?php echo get_post_meta($post->ID, 'links_link_custom', true) ?><?php else: ?><?php the_permalink(); ?><?php endif; ?>"><?php the_title(); ?></a></h2> A: First things first, lets clean up your code: <?php $wptitle = the_title(); $wptitle = str_replace('&', 'and', $wptitle);?><?php echo $wptitle; ?> Lets remove the PHP tag spam and put things in nice clean lines: <?php $wptitle = the_title(); $wptitle = str_replace('&', 'and', $wptitle); echo $wptitle; ?> Now if we look at the problem, the_title, that function outputs the title and doesn't return anything. This means $wptitle is empty, so your string replace does nothing. You need to tell it to return it or it won't know, computers aren't the same as people, they need to be told explicitly what to do with no assumptions. However, a quick google for the_title brings up the codex as the first entry, along with a related function get_the_title which would solve your problem. Reading the documentation says that these are the arguments this function takes: <?php the_title( $before, $after, $echo ); ?> So you can change $wptitle = the_title(); to this: $wptitle = the_title( '','',false ); Or this: $wptitle = get_the_title(); There is also a much better method that you can use involving filters: add_filter( 'the_title', 'drabello_swap_ampersands' ); function drabello_swap_ampersands( $old_title ) { $new_title = // do the replacement.. return $new_title; }
{ "pile_set_name": "StackExchange" }
Q: Android Studio 3.2 canary build is not rendering Navigation tag Android studio 3.2 canary 14 is not rendering the navigation tag. It just shows the waiting for a build to finish. navigation_graph <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <fragment android:id="@+id/fragment_nav_host" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:navGraph="@navigation/navigation_graph" /> </navigation> A: You need to turn on experimental feature "enable navigation editor" under menu> android studio>preferences>experimental clean and rebuild project
{ "pile_set_name": "StackExchange" }
Q: Error when trying to select menu with Selenium-Python My Selenium IDE recording on Chrome that opens a URL and then do click on a dropdown menu that seems to generate some code dinamically shows 3 actions, Open, Click, and Mouse Over commands. It works and the id, cpath, css_selector stored by Selenium IDE are shown below. { "id": "5f885ad3-990a-4989-9382-2572b2", "version": "2.0", "name": "Test", "url": "https://example.com", "tests": [{ "id": "00fe2ec5-3529-44ef-9367-b5a7fbf", "name": "Test", "commands": [{ "id": "c174b4f2-3a55-4f41-954c-22a8e04", "comment": "", "command": "open", "target": "https://example.com", "targets": [], "value": "" }, { "id": "763f8999-7973-48fb-864a-fb3965369021", "comment": "", "command": "click", "target": "css=.blue > .fa", "targets": [ ["css=.blue > .fa", "css:finder"], ["xpath=//li[@id='MyMenu']/div/button/span[2]", "xpath:idRelative"], ["xpath=//li[3]/div/button/span[2]", "xpath:position"] ], "value": "" }, { "id": "3c91c590-94a2-44b8-8d17-bb04d3", "comment": "", "command": "mouseOver", "target": "id=myid", "targets": [ ["id=myid", "id"], ["css=#myid", "css:finder"], ["xpath=//span[@id='myid']", "xpath:attributes"], ["xpath=//li[@id='MyMenu']/div/button/span", "xpath:idRelative"], ["xpath=//li[3]/div/button/span", "xpath:position"], ["xpath=//span[contains(.,'ABC Banner')]", "xpath:innerText"] ], "value": "" }] }], } I've tried the following code in order to reproduce the open menu action but doesn't work from selenium import webdriver from time import gmtime, strftime from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome("C:\crd\chromedriver.exe") driver.get ("https://example.com") wait = WebDriverWait(driver, 30) abc = wait.until(EC.element_to_be_clickable((By.XPATH, "//*..."))) actionChains = ActionChains(driver) actionChains.double_click(abc).perform() driver.find_element_by_xpath("//*[@id='....']").click() driver.find_element_by_css_selector(".blue > .fa").click() ##### Before actionChains1 actionChains1 = ActionChains(driver) ### Added new actionChains1 element = driver.find_element_by_id("myid") actionChains1.move_to_element(element).perform(); I get this error of no such element like the element is not visible, but actually is visible and website has already loaded completely: DevTools listening on ws://127.0.0.1:53407/devtools/browser/e4e2207c-bdd6-4754-867c-7b488 Traceback (most recent call last): File "Script.py", line 49, in <module> element=driver.find_element_by_id("myid") File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element 'value': value})['value'] File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"myid"} (Session info: chrome=74.0.3729.131) (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 6.1.7601 SP1 x86_64) How to fix this issue? Thanks in advance. UPDATE Thanks to @supputuri help my issue was fixed. The problem was the page where I was working is a second one that is opened after a login page, then when the new tab was opened, the driver was seeing the first page and the element I was trying to click didn't exist in that page and due to that it was not found. The line that fixed the issue was adding a switch of window to new page driver.switch_to.window(driver.window_handles[1]) A: you are missing the below step. After navigating to the url and before mouse over. driver.get ("https://example.com") driver.switch_to.window(driver.window_handles[1]) wait = WebDriverWait(driver, 30) abc = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,, ".blue > .fa"))) abc.click() actionChains = ActionChains(driver) element = driver.find_element_by_id("myid") actionChains.move_to_element(element).perform();
{ "pile_set_name": "StackExchange" }
Q: Checkbox event and holding array - how to handle in code? I have the following code in my phonegap app: function onDeviceReady() { var listOfSports = new Array(["Aikido"],["Air Sports"],["American Football"],["Angling"],["Archery"],["Yoga"]); $.each(listOfSports, function (i) { console.log(i); var li = $('<li><input class="checkbox" type="checkbox"' + 'id="' + listOfSports[i] + '"' + 'label="' + listOfSports[i] + '">' + listOfSports[i] + '</li>') .appendTo("ul.listViewContainer"); }); $("#listViewContainer").listview(); $("#listViewContainer").listview("refresh"); } How can I get the value of checked items and add the value to an array when checked or remove when unchecked? A: Something like this. This will store all the checkbox ID in an array. var arr = []; function onDeviceReady() { var listOfSports = new Array(["Aikido"],["Air Sports"],["American Football"],["Angling"],["Archery"],["Yoga"]); $.each(listOfSports, function (i) { console.log(i); var li = $('<li><input class="checkbox" type="checkbox"' + 'id="' + listOfSports[i] + '"' + 'label="' + listOfSports[i] + '">' + listOfSports[i] + '</li>') .appendTo("ul.listViewContainer"); }); $("#listViewContainer").listview(); $("#listViewContainer").listview("refresh"); $(".checkbox").click(function () { if ($(this)[0].checked) { arr.push($(this).attr("id")); } else { arr = $.grep(arr, function( a ) { return a != $(this).attr("id"); }); } }); } Edit : Just a little mistake. Here a fiddle : http://jsfiddle.net/wyfr8/207/ else { var check = $(this); arr = $.grep(arr, function( a ) { return a != $(check).attr("id"); }); }
{ "pile_set_name": "StackExchange" }
Q: Removing a index.php from codeginiter url using htaccess not working on server .htaccess code: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/$1 [L] also change in config file: $config['index_page'] = ' '; $config['uri_protocol'] = "REQUEST_URI"; mod_rewrite is also enabled. although this code doesn't work. A: Change this In 'config.php` $config['base_url'] = ''; $config['index_page'] = '' $config['uri_protocol'] = 'AUTO'; .htaccess <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> and accessing URL should with base_url() function. ex <form action="<?php echo base_url()?>Controller_name/Method_name" Note: To use base_url() you have to enable it on autoload.php $autoload['helper'] = array('url');
{ "pile_set_name": "StackExchange" }
Q: React: Do children always rerender when the parent component rerenders? It is to my knowledge that if a parent component rerenders, then all its children will rerender UNLESS they implement shouldComponentUpdate(). I made an example where this doesn't seem to be the true. I have 3 components: <DynamicParent/>, <StaticParent/> and <Child/>. The <Parent/> components are responsible for rendering the <Child/> but do so in different ways. <StaticParent/>'s render function statically declares the <Child/> before runtime, like so: <StaticParent> <Child /> </StaticParent> While the <DynamicParent/> handles receiving and rendering the <Child/> dynamically at runtime, like so: <DynamicParent> { this.props.children } </DynamicParent> Both <DynamicParent/> and <StaticParent/> have onClick listeners to change their state and rerender when clicked. I noticed that when clicking <StaticParent/> both it and the <Child/> are rerendered. But when I click <DynamicParent/>, then only the parent and NOT <Child/> are rerendered. <Child/> is a functional component without shouldComponentUpdate() so I don't understand why it doesn't rerender. Can someone explain why this is to be the case? I can't find anything in the docs related to this use case. A: I'll post your actual code for context: class Application extends React.Component { render() { return ( <div> {/* Clicking this component only logs the parents render function */} <DynamicParent> <Child /> </DynamicParent> {/* Clicking this component logs both the parents and child render functions */} <StaticParent /> </div> ); } } class DynamicParent extends React.Component { state = { x: false }; render() { console.log("DynamicParent"); return ( <div onClick={() => this.setState({ x: !this.state.x })}> {this.props.children} </div> ); } } class StaticParent extends React.Component { state = { x: false }; render() { console.log("StaticParent"); return ( <div onClick={() => this.setState({ x: !this.state.x })}> <Child /> </div> ); } } function Child(props) { console.log("child"); return <div>Child Texts</div>; } When you write this code in your Application render: <StaticParent /> What's rendered is this: <div onClick={() => this.setState({ x: !this.state.x })}> <Child /> </div> And in reality, what happens (roughly) is this: function StaticParent(props) { return React.createElement( "div", { onClick: () => this.setState({ x: !this.state.x }) }, React.createElement(Child, null) ); } React.createElement(StaticParent, null); When you render your DynamicParent like this: <DynamicParent> <Child /> </DynamicParent> This is what actually happens (again, roughly speaking) function DynamicParent(props) { return React.createElement( "div", { onClick: () => this.setState({ x: !this.state.x }), children: props.children } ); } React.createElement( DynamicParent, { children: React.createElement(Child, null) }, ); And this is the Child in both cases: function Child(props) { return React.createElement("div", props, "Child Text"); } What does this mean? Well, in your StaticParent component you're calling React.createElement(Child, null) every time the render method of StaticParent is called. In the DynamicParent case, the Child gets created once and passed as a prop. And since React.createElement is a pure function, then it's probably memoized somewhere for performance. What would make Child's render run again in the DynamicParent case is a change in Child's props. If the parent's state was used as a prop to the Child, for example, that would trigger a re-render in both cases. I really hope Dan Abramov doesn't show up on the comments to trash this answer, it was a pain to write (but entertaining) A: It's mainly cause of you have 2 different "children". this.props.children <Child/> They're not the same thing, first one is a prop passed down from Application -> DynamicParent, while the second one is a Component rendered in StaticParent, they have separate rendering/life cycles. Your included example class Application extends React.Component { render() { return ( <div> {/* Clicking this component only logs the parents render function */} <DynamicParent> <Child /> </DynamicParent> {/* Clicking this component logs both the parents and child render functions */} <StaticParent /> </div> ); } } Is literally the same as: class Application extends React.Component { render() { // If you want <Child/> to re-render here // you need to `setState` for this Application component. const childEl = <Child />; return ( <div> {/* Clicking this component only logs the parents render function */} <DynamicParent> {childEl} </DynamicParent> {/* Clicking this component logs both the parents and child render functions */} <StaticParent /> </div> ); } }
{ "pile_set_name": "StackExchange" }
Q: Solved: What's the equivalent of Aspose.Pdf.Kit.PdfPrivilege in the "merged" version of Aspose (6.x) I am migrating a project how to replace this class. Aspose documentation says that the Aspose.Pdf.kit namespace has migrated to Aspose.Pdf.Facades, but there is not Aspose.Pdf.Facades.PdfPrivilege Any clues ? A: Permissing setting has changed and is now supposed to be done with this class: Aspose.Pdf.Facades.DocumentPrivilege
{ "pile_set_name": "StackExchange" }
Q: How to change which modules are auto-applied in Darktable? When I open a raw file in Darktable sharpening and a base curve are automatically applied. How do I alter this? I would like to add lens correction. A: Automatic presets would do that, see the section "Module presets" in Darktable's user manual. Note that you need Darktable version > 1.4 for this to work sensibly with lens correction. In earlier versions the lens correction did not adapt correctly to the image parameters. Relevant section from the manual: A module has an expander bar . Clicking on the name of the module expands the module's GUI with all parameters. In its default setting darktable will only expand one GUI at a time. If you click the expander bar of another module, the previous GUI gets collapsed. If you want to see more than one GUI expanded, you may expand further modules with shift-click – all previously expanded GUIs remain opened. The expander bar behavior on click and shift-click, respectively, is controlled by a preference setting in gui options (see Section 8.1, “GUI options”). Expanding a module does not activate it. You need to click the icon to turn a module on or off. Icon accesses the module's available presets or creates a new preset from your current settings (see Section 3.2.3, “Module presets”).
{ "pile_set_name": "StackExchange" }
Q: SSIS and JSON Flat Files Whats the best way to get JSON flat files into SQL Server using SSIS? Currently I've tried parsing the data in a script component, but with amount of JSON files I'm parsing (around 120 at a time) it takes upward of 15 minutes to get the data in. I also don't consider this very practical. Is there a way to combine the powers of SSIS and the OPENJSON command in SQL server? I'm running SQL server 2016 so I'm trying to leverage that command in the hopes that it works faster. Also, I have no problem getting the JSON data in without losing format. Looks like this: Is there a way for me to leverage that and get JSON format into a more Normalized format. A: Actually figured this out. I bring the files in one at a time, with all the JSON text in a single row. From there I can use the OPENJSON command in SQL Server 2016.
{ "pile_set_name": "StackExchange" }
Q: Was there doctrinal difference between Lollards and Waldenses? Lollards and Waldenses are two historical movements that spread out of Catholic church, in England and France, respectively. I know they had similar views such as opposing the corruption of the wealthy church, advocating lay service, focusing on the scripture instead of ritual traditions and translating scripture so people could study the Gospel in their native language. Were these two movements separated by anything but time and geography? Was there any significant difference in doctrine, belief or politics between Waldenses and the Lollards? A: According to each of their own "statements of Faith" they actually do contradict each other in big issues. before I lay it out, however, here are my citations: Waldensian beliefs Lollard beliefs The first issue on which they contradict each other is purgatory. Waldensians say there is no purgatory. They say people will go either two ways “(the) good to glory, wicked to torment” which leaves room for purgatory, but then later in their statement they say “For you shall be damned without remedy.” No purgatorial redemption. They Lollards say that yes, there is purgatory. “(acts)...will have needful purgation or worse.” The next issue is celibacy. the Waldensians say "That he might likewise keep firm the marriage tie, that noble accord and contract." In the issue of celibacy, the Lollards say yes, do participate in celibacy. And the last difference I will talk about is Confession (to priests). Waldensians say "Then he desires the Priest to confess him: But according to the Scriptures he has delayed too long, for that commands us To repent while we have time, and not to put it off till the last." They then go on expound on this topic. The Lollards, however, say confession is necessary to the salvation of man. Lollards and Waldensians contradict each other in purgatory, celibacy, and confession. Some say that one's view of purgatory and confession will, either positively or negatively, affect their eternal destiny. A: Brief Googling shows that Lollards were followers of John Wycliffe while the Waldensian church followed the teachings of the merchant Waldo of Lyons. The term Lollard seemed like more of a derogatory label (much like the term Christian) where the Waldensian church identified itself as such. How the followers of these two doctrines look today also seems to have veered in principle and preference, but not so much in doctrine. Both were pre-reformation and both eventually joined Protestantism. And even though "significant" is subjective, based on current resources* they don't show any significant doctrinal differences. The differences between the two would be no larger than differences you might see in modern day Baptists and Lutherans and Episcopalians. Even the catalysts for their movements seemed to be rooted in the same anti-papacy, anti-greed sentiments and principles: The Waldensian Church is rooted in the preaching of Valdesius, a merchant in Lyon, France, who lived during the same period of the late Middle Ages as Francis of Assisi. Like Francis, Valdesius believed in the value of the evangelical poverty of the early church. source During the earlier part of his public career Wyclif had come forward as an ally of the anti-clerical and anti-papal nobility, and especially of John of Gaunt. He had asserted the right of temporal lords to take the goods of an undeserving clergy and, as a necessary consequence, he had attacked the power of excommunication. source *current resources provided in links in this answer, and Google.
{ "pile_set_name": "StackExchange" }
Q: Trying to draw an ellipse in a WPF window, but it is not visible I am trying to create my own graph user control, I have one already working on win forms and I am trying to move it into WPF world. I am starting with learning how to do drawing, so first thing I was trying to draw a black ellipse that fills an entire window, just to learn how coordinates works in WPF. So here is the code, when I run the application, nothing is displayed, any idea what am I missing? public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); drawingContext.DrawEllipse(Brushes.Black, new Pen(Brushes.Black, 1), new Point(Width / 2, Height / 2), Width / 2, Height / 2); } } A: WPF is very different from WinForms. You do not have something like a Paint event handler where you constantly need to repaint invalidated areas. The easist way to draw an ellipse that fills the whole window area in WPF is this XAML: <Window ...> <Grid> <Ellipse Stroke="Black" Fill="Black"/> </Grid> </Window> but of course there are a lot of other ways to achieve the same result. If you need to do more complex things, WPF offers a large variety of classes that support graphics and multimedia. I'd suggest starting to read the Graphics section of the online documentation on MSDN. To come back to your specific problem, there are several things to mention. First, you would have seen the result of your OnRender override if you had set the Window's Background property to Transparent and had drawn the ellipse in a color other than Black. Then you would have realized that the drawn ellipse is larger than the window's client area. This is because the values of the Width and Height properties include the Window border. Even then, using the Width and Height properties for getting the actual width and height of a UI element in WPF is not the proper way, because these properties return double.NaN unless they were explicitly set (except in the Window class). Instead, you would usually use the ActualWidth and ActualHeight properties, as in this UserControl (which perhaps does exactly what you intended): public partial class DrawingControl : UserControl { public DrawingControl() { InitializeComponent(); } protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); drawingContext.DrawEllipse(Brushes.Black, new Pen(Brushes.Black, 1), new Point(ActualWidth / 2, ActualHeight / 2), ActualWidth / 2, ActualHeight / 2); } }
{ "pile_set_name": "StackExchange" }
Q: With response JSON.parse my error is this: Uncaught SyntaxError: Unexpected token H in JSON at position 0 I am trying to make a calendar in laravel 5.3, but I have this error in the console with a json response, in json and javascript I am new, the calendar is an example and I am trying to adapt a laravel. Where this error arises it is in this part: $('#calendar').fullCalendar({ events: JSON.parse(json_events), //events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}], utc: true, header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, droppable: true, slotDuration: '00:30:00', eventReceive: function(event){ var title = event.title; var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS"); $.ajax({ url: '{{url('calendarController')}}', data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone, type: 'GET', dataType: 'json', success: function(response){ event.id = response.eventid; $('#calendar').fullCalendar('updateEvent',event); }, error: function(e){ console.log(e.responseText); } }); $('#calendar').fullCalendar('updateEvent',event); console.log(event); }, eventDrop: function(event, delta, revertFunc) { var title = event.title; var start = event.start.format(); var end = (event.end == null) ? start : event.end.format(); $.ajax({ url: '{{url('calendarController')}}', data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id, type: 'GET', dataType: 'json', success: function(response){ if(response.status != 'success') revertFunc(); }, error: function(e){ revertFunc(); alert('Error processing your request: '+e.responseText); } }); }, eventClick: function(event, jsEvent, view) { console.log(event.id); var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} }); if (title){ event.title = title; console.log('type=changetitle&title='+title+'&eventid='+event.id); $.ajax({ url: '{{url('calendarController')}}', data: 'type=changetitle&title='+title+'&eventid='+event.id, type: 'GET', dataType: 'json', success: function(response){ if(response.status == 'success') $('#calendar').fullCalendar('updateEvent',event); }, error: function(e){ alert('Error processing your request: '+e.responseText); } }); } }, eventResize: function(event, delta, revertFunc) { console.log(event); var title = event.title; var end = event.end.format(); var start = event.start.format(); $.ajax({ url: '{{url('calendarController')}}', data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id, type: 'GET', dataType: 'json', success: function(response){ if(response.status != 'success') revertFunc(); }, error: function(e){ revertFunc(); alert('Error processing your request: '+e.responseText); } }); }, eventDragStop: function (event, jsEvent, ui, view) { if (isElemOverDiv()) { var con = confirm('Are you sure to delete this event permanently?'); if(con == true) { $.ajax({ url: '{{url('calendarController')}}', data: 'type=remove&eventid='+event.id, type: 'GET', dataType: 'json', success: function(response){ console.log(response); if(response.status == 'success'){ $('#calendar').fullCalendar('removeEvents'); getFreshEvents(); } }, error: function(e){ alert('Error processing your request: '+e.responseText); } }); } } } }); If someone could give me a serious response a lot of help, I'm new to the world of javascript A: Check your Developer Console/Network tab to see the actual response. Then copy it and validate it. I'm quite sure the server response is not what you think it is.
{ "pile_set_name": "StackExchange" }
Q: Naming 1, 2, 3, ... millennial celebrations I know that after 100 years there are centennial celebrations, after 200 years bicentennial, tricentennial, etc., Similarly, are there terms for 2000, 3000, etc., years of celebration? A: Sure. Picking up where you left off, we have: 250 years - Sestercentennial 300 years - Tercentennial 400 years - Quadricentennial 500 years - Quincentennial 600 years - Sexcentennial 700 years - Septcentennial 800 years - Octocentennial 900 years - Nonacentennial 1000 years - Millennial 2000 years - Bimillennial Anything beyond bimillenial is probably very uncommon at best, but you could likely follow the above naming convention and be understood. See more odd usages here. A: Yes, there are, and they follow the same naming convention: bimillennial, trimillennial, etc.
{ "pile_set_name": "StackExchange" }
Q: Code unable to handle big loops Setup: Starting with the number 32, the sum of squares is 13 because 3x3 + 2x2 = 13. The sum of squares for 13 is 10 because 1x1 + 3x3 = 10. The sum of squares for 10 is 1, so 32 is a happy number. sample input The input will be a single positive integer. Several examples are given here. 32 4565 42 5555 Sample Output The program must print a sentence indicating if the input number is happy or unhappy, then exit. 32 is a happy number 4565 is an unhappy number 42 is an unhappy number 5555 is a happy number Actual problem: whenever i input huge numbers such as 5555. i get an error such as: File "C:/Users/username/Desktop/bob.py", line 43, in sos sos() File "C:/Users/username/Desktop/bob.py", line 26, in sos for x in range(repeat): RuntimeError: maximum recursion depth exceeded in comparison **code: ** ans = input() y = 5000 #this is so that the data does not loop forever repeat = len(ans) def sos(): global y global repeat1 global ans for x in range(repeat): List = list(str(ans)) repeat1 = len(List) repeat2 = len(List) ans1 = int(List[int(repeat2)-int(repeat1)]) * int(List[int(repeat2)-int(repeat1)]) #print("ans1", ans1) ans2 = int(List[int(repeat2)-(int(repeat1)-1)]) *int(List[int(repeat2)-int(repeat1-1)]) #print("ans2", ans2) ans = ans1 + ans2 y -= 1 if x == 1: print(this, "is a happy number") else: if y <=0: print(this, "is not a happy number") else: sos() sos() Question: What can i do to prevent this error? request: please try to edit my code instead of creating your own. it help me learn what i did wrong and fix it in the future if needed. A: A number is either a happy number if the recursive sum of squares ends up in 1, or is not if it recurses endlessly (see the wikipedia definition). An easy way to implement such a behavior is to track the intermediate sums you calculate on the way: def is_happy(num): return is_happy_recursive(num, []) def is_happy_recursive(num, seq): sum_squares = sum([int(d)**2 for d in str(num)]) if sum_squares == 1: return True elif sum_squares in seq: return False else: seq.append(sum_squares) return is_happy_recursive(sum_squares, seq)
{ "pile_set_name": "StackExchange" }
Q: Rate of growth colony of ants The rate of growth of a colony of ants is proportional to the square root of the size of the population...... Show that if $P$ is the size of the population and $t$ is the time in days then $\dfrac{dP}{dt} = k\sqrt{P}$, where $k$ is a constant. When $t=0$, $P=100$ and when $t=5$, $P=625$. Find an expression for $P$ as a function of $t$ and the size of the population when $t=10$. I have integrated the equation, but I can't seem to find a single value for $k$. A: By definition, $\frac{dP}{dt}=k\sqrt{P}$. Then we have, $$\frac{dP}{\sqrt{P}}=kt\rightarrow2\sqrt{P}=kt+c\rightarrow P=\frac{(kt+c)^2}{4}.$$ Using the first initial condition, we have, $$100=\frac{c^2}{4}\rightarrow c=20.$$ We can use this $c$ to solve for $k$ then using the second initial condition, after which you can simply plug in the value of $t$ at which you want $P$.
{ "pile_set_name": "StackExchange" }
Q: Using Kerberos authentication for SQL Server 2008 I am trying to configure my SQL Server to use Kerberos authentication. My setup is like this - My setup is like this- I have 2 virtual PCs in a Windows XP Pro SP3 host. Both VPCs are Windows Server 2003 R2. One VPC acts as the DC, DNS Server, DHCP server, has Active Directory installed and the SQL Server default instance is also running on this VPC. The second VPC is the domain member and it acts as the SQL Server client machine. I configured the SPN on the SQL Server service account to get the Kerberos working. On the client VPC it seems like it is using Kerberos authentication (as desired)- C:\Documents and Settings\administrator.SHAREPOINTSVC>sqlcmd -S vm-winsrvr2003 1> select auth_scheme from sys.dm_exec_connections where session_id=@@spid 2> go auth_scheme ---------------------------------------- KERBEROS (1 rows affected) 1> but on the server computer (where the SQL Server instance is actually running) it looks like it is still using NTLM authentication- . This is not a remote instance, the sql server is local to this machine. C:\Documents and Settings\Administrator>sqlcmd 1> select auth_scheme from sys.dm_exec_connections where session_id=@@spid 2> go auth_scheme ---------------------------------------- NTLM (1 rows affected) 1> What can i do so that it uses Kerberos on the server computer as well ? (or is this something that I should not expect) A: I don't think Kerberos is used locally, on a service on the same machine NTLM is used. On any other machine on the same Realm (Domain) Kerberos will be used, except on the same machine of the service. I think that if you do a program that connects with SQL and on the connection string you use Integrated Security=SSPI you might be able to onnect using kerberos (maybe), however I repeat that I don't think Kerberos is used locally.
{ "pile_set_name": "StackExchange" }
Q: How to identify counterfeit Analog Device products? Recently I bought two AD9850 DDSs from a friend ( I think he had bought them from his home country).They worked just for minutes! After hours challenging with them, I thought problem is because of my PCB layout and re-designed it. Finally I found out that the device had been a fake one ( my friend said he had bought them with a price much less than the company price!). Now I want to buy them again but I am afraid of the same scenario. Is there any sign that I can distinguish a fake product from its package? A: Your best bet is to always buy from an authorized seller or distributor. You're taking a risk with anyone else. There are ways to detect whether the device is counterfeit, but this depends on how good of a fake did they counterfeiters made. In some cases the packaging will be different in color (a different shade of white) or will be missing details in the markings, but in general there is not a single way to tell. If it looks too good to be true, it probably is.
{ "pile_set_name": "StackExchange" }
Q: Generate different combinations of arrays using positive integers as elements Given a certain integer n and a different integer k (both positive) I want to generate all the possible different arrays of size k containing integers in the interval [0..n]. For example with n = 2 and k = 2 I want to generate an array of arrays that contains [0,0], [0,1], [1,0], [0,2], [1,1], [2,0], [1,2], [2,1], [2,2]. So the result should be result = [[0,0], [0,1], [1,0], [0,2], [1,1], [2,0], [1,2], [2,1], [2,2]] The order of the elements doesn't matter. A: Use Array#repeated_permutation: (0..2).to_a.repeated_permutation(2).to_a # => [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
{ "pile_set_name": "StackExchange" }
Q: SQL single table with two columns I have a single table: Checking, with two columns: ID, Memo ID is the primary key. I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT I can do the following to get the distinct values from Memo: SELECT DISTINCT(memo) FROM checking How do I return those Memo values and their values from the ID column? I've run in circles trying inner and outer joins but I'm failing. Thanks for your help Sample data: ID Memo 1 a 2 c 3 e 4 g 5 a 6 c The desired return: 1,a 2,c 3,e 4,g 5 and 6 would not be included because they have duplicate memo values. Thanks again for your help. A: SELECT min(id), memo FROM checking group by memo A: If I understand you correctly you want the first (?) primary key value corresponding to each unique memo value found? (I'm assuming this because you can't logically have both unique memos and Id values because there is necessarily multiple ID values for each duplicated memo value...) If the assumption is correct this will work: SELECT m.memo, (SELECT TOP 1 x.id FROM checking x WHERE x.memo = m.memo ORDER BY x.id) as ID FROM checking m GROUP BY m.memo
{ "pile_set_name": "StackExchange" }
Q: Error when installing bookmark+ package in emacs I'm trying to install bookmarks and I get the error. When I tried byte-compiling the files it also failed. Is there a current git for bookmarks+. Error below: Invalid function: bmkp-menu-bar-make-toggle Here is the full trace: Debugger entered--Lisp error: (invalid-function bmkp-menu-bar-make-toggle) bmkp-menu-bar-make-toggle(t t "Highlight Jump using Crosshairs" "Crosshairs highlighting is %s" "Temporarily highlight visited bookmarks using crosshairs") byte-code("\306\307\310 B#\210\306 \311\312\n\211\313\314\315%#\210\306 \316\312\211\317\320\321%#\210\306 \322\312\f\211\323\324\325%#\210\306 \326\312 \211\327\330\331%#\210\306 \332\312\211\333\334\335%#\207" [menu-bar-bookmark-map bmkp-options-menu bmkp-crosshairs-flag bmkp-bmenu-state-file bookmark-save-flag bmkp-save-new-location-flag define-key [options] "Toggle Option" [bmkp-crosshairs-flag] bmkp-menu-bar-make-toggle "Highlight Jump using Crosshairs" "Crosshairs highlighting is %s" "Temporarily highlight visited bookmarks using crosshairs" [bmkp-toggle-saving-menu-list-state] "Autosave *Bookmark List* Display State" "Autosaving of `*Bookmark List*' display state is %s" "Autosave `*Bookmark List*' state (aka \"menu list\") when you quit it" [bmkp-toggle-saving-bookmark-file] "Autosave Bookmark File" "Autosaving of bookmarks is %s" "Automatically save a bookmark after setting or changing it" [bmkp-save-new-location-flag] "Autosave after Relocating" "Autosaving relocated bookmarks is %s" "Automatically save a bookmark after automatically relocating it" [bmkp-prompt-for-tags-flag] "Prompt for Tags when Setting" "Prompting for tags when setting a bookmark is %s" "Prompt for tags when setting a bookmark interactively" bmkp-prompt-for-tags-flag] 9) require(bookmark+-key) eval-buffer(#<buffer *load*<2>> nil "/home/bigtyme/Dropbox/SyncedPrograms/emacs/loadPath/bookmarkplus/bookmark+.el" nil t) ; Reading at buffer position 5907 load-with-code-conversion("/home/bigtyme/Dropbox/SyncedPrograms/emacs/loadPath/bookmarkplus/bookmark+.el" "/home/bigtyme/Dropbox/SyncedPrograms/emacs/loadPath/bookmarkplus/bookmark+.el" nil t) require(bookmark+) eval-buffer(#<buffer *load*> nil "/home/bigtyme/.emacs" nil t) ; Reading at buffer position 1158 load-with-code-conversion("/home/bigtyme/.emacs" "/home/bigtyme/.emacs" t t) load("~/.emacs" t t) #[nil "\205\264 Sorted it out by just downloading the current git version. The version I downloaded from the wiki must have had a bug. Now I have no issues. A: First, do what chrm recommends: get the latest source files. Second, bmkp-menu-bar-make-toggle is a Lisp macro, defined in bookmark+-mac.el. As always, before byte-compiling any of the source files, be sure you load the source file the defines the macros that those files use. In this case, load bookmark+-mac.el (not *.elc) before byte-compiling any of the Bookmark+ files.
{ "pile_set_name": "StackExchange" }
Q: genes with highest RPKM/FPKM for a human RNA-seq experiment? Which genes/transcripts show up as having the highest RPKM/FPKM on a human RNA-seq experiment? Is it usually the same genes/transcripts? EDIT: mRNAs (e.g. poly-A RNA-seq preps) and not including small RNAs. A: As asked as it is, the answer is probably no. Indeed, the highest expressed RPKM/FPKMs will be different from one condition (or tissue) to another one for example. Then, you may also have technical artefacts due to the wet-lab part or to the normalisation. For example, mitochondrial genes are often reported in the top expressed genes. Now, if you want to compare your results to an outside source, I recommend checking the EBI gene expression Atlas* and more specifically the Baseline expression experiments. Pro-tips: You can filter the genes based on their nature (eg, mRNA) and/or their expression. You can also visualise the overall expression of a specific gene across several experiments. *Disclaimer: I am related to this project myself.
{ "pile_set_name": "StackExchange" }
Q: Python run_in_executor and forget? How can I set a blocking function to be run in a executor, in a way that the result doesn't matter, so the main thread shouldn't wait or be slowed by it. To be honest I'm not sure if this is even the right solution for it, all I want is to have some type of processing queue separated from the main process so that it doesn't block the server application from returning requests, as this type of web server runs one worker for many requests. Preferably I would like to keep away from solutions like Celery, but if that's the most optimal I would be willing to learn it. The context here is a async web server that generates pdf files with large images. app = Sanic() #App "global" worker executor = ProcessPoolExecutor(max_workers=5) app.route('/') async def getPdf(request): asyncio.create_task(renderPdfsInExecutor(request.json)) #This should be returned "instantly" regardless of pdf generation time return response.text('Pdf being generated, it will be sent to your email when done') async def renderPdfsInExecutor(json): asyncio.get_running_loop.run_in_executor(executor, syncRenderPdfs, json) def syncRenderPdfs(json) #Some PDF Library that downloads images synchronously pdfs = somePdfLibrary.generatePdfsFromJson(json) sendToDefaultMail(pdfs) The above code gives the error (Yes, it is running as admin) : PermissionError [WinError 5] Access denied Future exception was never retrieved Bonus question: Do I gain anything by running a asyncio loop inside the executor? So that if it is handling several PDF requests at once it will distribute the processing between them. If yes, how do I do it? A: Ok, so first of all there is a misunderstanding. This async def getPdf(request): asyncio.create_task(renderPdfsInExecutor(request.json)) ... async def renderPdfsInExecutor(json): asyncio.get_running_loop.run_in_executor(executor, syncRenderPdfs, json) is redundant. It is enough to do async def getPdf(request): asyncio.get_running_loop.run_in_executor(executor, syncRenderPdfs, request.json) ... or (since you don't want to await) even better async def getPdf(request): executor.submit(syncRenderPdfs, request.json) ... Now the problem you get is because syncRenderPdfs throws PermissionError. It is not handled so Python warns you "Hey, some background code threw an error. But the code is not owned by anyone so what the heck?". That's why you get Future exception was never retrieved. You have a problem with the pdf library itself, not with asyncio. Once you fix that inner problem it is also a good idea to be safe: def syncRenderPdfs(json) try: #Some PDF Library that downloads images synchronously pdfs = somePdfLibrary.generatePdfsFromJson(json) sendToDefaultMail(pdfs) except Exception: logger.exception('Something went wrong') # or whatever Your "permission denied" issue is a whole different thing and you should debug it and/or post a separate question for that. As for the final question: yes, executor will queue and evenly distribute tasks between workers. EDIT: As we've talked in comments the actual problem might be with the Windows environment you work on. Or more precisely with the ProcessPoolExecutor, i.e. spawning processes may change permissions. I advice using ThreadPoolExecutor, assuming it works fine on the platform.
{ "pile_set_name": "StackExchange" }
Q: Python Turtle how to create collision I am attempting to create pong using Turtle, however, I am having an issue with the collision system. I am using a basic pythagorean function for this, however, when the ball hits a bumber, it gets stuck at the bumper and starts shaking. I am not sure how to fix this problem. Here is the collision and bumper code. turtle.register_shape('bar.gif') lbump = turtle.Turtle() lbump.color('white') lbump.shape('bar.gif') lbump.penup() lbump.speed(0) lbump.setposition(-285,0) rbump = turtle.Turtle() rbump.color('white') rbump.shape('bar.gif') rbump.penup() rbump.speed(0) rbump.setposition(285,0) ball = turtle.Turtle() ball.color('white') ball.shape('circle') ball.penup() ball.speed(0) ball.setposition(0,0) ballspeedx = -5 ballspeedy = 0 #To test collison# def isCollision(t1, t2): distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2)) if distance < 30: return True else: return False def ball_move(): while True: global ballspeedy global ballspeedx x = ball.xcor() + ballspeedx y = ball.ycor() + ballspeedy if y > 285 or y < -285: ballspeedy *= -1 if x < -295 or x > 295: x = 0 y = 0 if isCollision(lbump, ball): ballspeedx *= -1 if isCollision(rbump, ball): ballspeedx *= -1 ball.setposition(x,y) A: The reason it's likely this: when a collision is detected (isCollision returns True) and the sign of the x velocity is switched, the ball does not have the time to gain enough distance from the bumper until the next iteration of the loop. Hence, next iteration isCollision is still detecting a collision and changes again the sign of the velocity. As a result, x velocity sign is switched each iteration from positive to negative and viceversa, and you see the shacking effect. If I'm right, this edit is the simplest way that come to my mind to solve the issue: if isCollision(lbump, ball): ballspeedx = abs(ballspeedx) if isCollision(rbump, ball): ballspeedx = -1 * abs(ballspeedx) Of course more elaborate solutions can be implemented.
{ "pile_set_name": "StackExchange" }
Q: Using CSS to put some DIVs over a picture (+explaining images) '.$row['titulo'].''.$contenido.time_since(strtotime($row['dt'])).' '); } ?> The styles are in a separate file and they are: .newsticker-jcarousellite { width:600px; } .newsticker-jcarousellite ul li{ list-style:none; display:block; padding-bottom:1px; margin-bottom:5px; } .newsticker-jcarousellite .thumbnail { float:left; width:50px; height:50px; } .newsticker-jcarousellite .info { float:right; width:535px; } .newsticker-jcarousellite .info span.cat { display: block; font-size:10px; color:#808080; } All generates this: But now, i need to add 3 litle div on the lower part of the profile picture all of them with a black (35% transparent) background where i can put some text, the result must look like this: Im very new at css, and i realy dont have any idea how to do this, thanks for any help! A: Complete code (untested): HTML/PHP: <div id="newsticker-demo"> <div class="newsticker-jcarousellite"> <ul> <?php echo('<li> <div class="thumbnail"><img src="'.$fotoperfil.'"> <div class="txt"> <span>t1</span> <span>t2</span> <span>t3</span> </div> </div> <div class="info"><a href="'.$linkpregunta.'">'.$row['titulo'].'</a><span class="cat">'.$contenido.time_since(strtotime($row['dt'])).'</span></div> <div class="clear"></div> </li>'); } ?></ul></div></div> CSS: .newsticker-jcarousellite { width:600px; } .newsticker-jcarousellite ul li{ list-style:none; display:block; padding-bottom:1px; margin-bottom:5px; } .newsticker-jcarousellite .thumbnail { float:left; width:50px; height:50px; position:relative /* <- new property */ } .newsticker-jcarousellite .info { float:right; width:535px; } .newsticker-jcarousellite .info span.cat { display: block; font-size:10px; color:#808080; } /* new */ .newsticker-jcarousellite .thumbnail .txt { position:absolute; left:0; right:0; bottom:0; background:#000; background:rgba(0,0,0,0.35); }
{ "pile_set_name": "StackExchange" }
Q: Why can't decomposition declarations be constexpr? Consider the following snippet to test the upcoming C++17 feature decomposition declarations (formerly known as structured bindings) #include <cassert> #include <utility> constexpr auto divmod(int n, int d) { return std::make_pair(n / d, n % d); // in g++7, also just std::pair{n/d, n%d} } int main() { constexpr auto [q, r] = divmod(10, 3); static_assert(q == 3 && r ==1); } This fails on both g++7-SVN and clang-4.0-SVN with the message: decomposition declaration cannot be declared 'constexpr' Dropping the constexpr definition and changing to a regular assert() works on both compilers. None of the WG21 papers on this feature mention the constexpr keyword, neither in the positive nor the negative. Question: why aren't decomposition declarations be allowed to be constexpr? (apart from "because the Standard says so"). A: Question: why aren't decomposition declarations be allowed to be constexpr? (apart from "because the Standard says so"). There is no other reason. The standard says in [dcl.dcl] p8: The decl-specifier-seq shall contain only the type-specifier auto (7.1.7.4) and cv-qualifiers. That means it can't be declared with constexpr. This was the subject of a National Body comment on the C++17 CD, see US-95 in P0488R0: Comment: There is no obvious reason why decomposition declarations cannot be declared as static, thread_local, or constexpr. Proposed change: Allow constexpr, static, and thread_local to the permitted set of decl-specifiers. Comments GB 16 and GB 17 are also related. These comment were rejected for C++17 after review by the Evolution Working Group at the Nov 2016 meeting. It was unclear what some storage classes would mean on a structured binding declaration, and exactly how to change the specification to allow constexpr (simply allowing it in the grammar wouldn't say what it means). A paper exploring the design space was requested. It should be possible to change this in future without breaking any code, but there wasn't time to do it for C++17.
{ "pile_set_name": "StackExchange" }
Q: Creating log files in SQL Server 2012 I'm sure this is probably SQL 101 but Google searches keep finding 'creating logins' entries. Let me give a quick overview. I have drifted into SQL reporting from general IT Support as a result of the need for more detailed reports than our systems can provide. My company runs leisure centres and we very helpfully use 3 different leisure management systems across 70+ sites. All 3 are SQL based but do the same job in very different ways. I have produced loads of reports in SSRS but the 2 or 3 I have done that access all systems are very, very time consuming and just one link down means the whole report is inaccessible. A request to send data to a third party for marketing purposed has forces us to finally look at centralising data from all of the systems to make reporting much easier. There will only essentially be 2 tables - 1 for membership details and one for activities. I have done the hard part of creating a view that produces the same information from each of the 3 systems and set up a central database to bring the data back to. I will have a stored procedure running on each system that will populate a table with records from the previous day. There will then be a job on the central server that will copy data from these tables and remove it once transferred. So far so (relatively) simple. The problem is that the central server will be trying to retrieve data from over 60 servers - all with their own network links. Some sites are remote with poor DSL connections so there will be times when some of the data can't be copied by the scheduled job. I am happy that a SQL agent job can have these as steps and one failed connection won't stop the whole process but my concern is that troubleshooting when something goes wrong will be tricky if I don't get some kind of logging in place. The stored procedures although complicated SQL wise are just update/insert record jobs. What would be helpful is that the update job writes to a log file somehow reporting that it affected 20 rows. And the insert job affected 100 rows. Basic stuff but I have no idea how I go about it. What would also be useful is some kind of warning when one of the steps fails. SQL Agent will help but I want to build as much resilience as possible in whilst I am at the 3 server stage before rolling out to the 60+ server stage. Any pointers in the right direction would be much appreciated. My SQL skills are self taught (With a lot of Stack Overflow help!) and although I have learnt a lot about producing complicated views and queries in the last couple of weeks, most of my SQL has just been queries for SSRS so this is all new to me. Many thanks. A: The output clause will get you what you want for logging. What it allows you to do is capture what your statement is doing. Below is an example of of how to perform an update and capture the changes in a logging table. As for error handling and resilience I would take a look into using SSIS to perform your ETL. SSIS gives you a much more robust feature set for error handling. -- Create Temp Tables CREATE TABLE #myLog ( id int, oldVal int, newVal int ); CREATE TABLE #myTable ( id int, val int ); -- Add Values to #myTable INSERT INTO #myTable VALUES (1, 1234), (2, 1234); -- Output Contents of #myTable SELECT * FROM #myTable; -- Update #myTable & Capture Changes UPDATE #myTable SET val = 12345 OUTPUT inserted.id, deleted.val, inserted.val INTO #myLog WHERE id = 2 -- Output Contents of #myTable and #myLog SELECT * FROM #myTable SELECT * FROM #myLog -- Drop Temp Tables DROP TABLE #myLog DROP TABLE #myTable
{ "pile_set_name": "StackExchange" }
Q: how to scroll embedded chromium in Delphi Hi is there any way to simulate the Delphi embedded chromium scroll position? or simulate SPACE key to scroll when pressing a TButton. A: What you can do is inject some javascript that will scroll to the bottom ChromiumComponent.Browser.MainFrame.ExecuteJavaScript( 'window.scrollTo(0,document.body.scrollHeight);' ); Works great for one way communication to the page you are on.
{ "pile_set_name": "StackExchange" }
Q: OpenCV color identification Hi I'm trying to built simple color identifying program. I have taken a image (yellow & pink) with and convert it in HSV color space. Then used threshold to identify yellow color region. I getting the output (black image). I want yellow region to be filled with while color and rest with black. IplImage *imgRead= cvLoadImage("yellow.jpeg",CV_LOAD_IMAGE_COLOR); if(!imgRead) { fprintf(stderr, "Error in reading image\n"); exit(1); } IplImage *imgHsv = cvCreateImage(cvGetSize(imgRead),8, 3); cvCvtColor(imgRead, imgHsv,CV_BGR2HSV); IplImage *imgThreshold = cvCreateImage(cvGetSize(imgRead),8, 1); cvInRangeS(imgHsv, cvScalar(25, 80, 80,80), cvScalar(34, 255, 255,255), imgThreshold); cvShowImage("image",imgThreshold); cvWaitKey(0); In above code I had calculated HSV value for yellow as 30. (In gimp hsv value for yellow color is 60). In cvInRangeS, except for hue value I'm not sure how to specify other values for cvScalar. What values I need to put? Am I missing anything? A: I think the problem you are having is due to the scaling of the HSV data to fit in 8-bits. Normally, as I'm sure you noticed from using GIMP that HSV scales are as follows: H -> [0, 360] S -> [0, 100] V -> [0, 100] But, OpenCV remaps these values as follows: (H / 2) -> [0, 180] (so that the H values can be stored in 8-bits) S -> [0, 255] V -> [0, 255] This is why your calculated Hue value is 30 instead of 60. So, to filter out all colors except for yellow your cvInRangeS call would look something like this: cvInRangeS(imgHsv, cvScalar(25, 245, 245, 0), cvScalar(35, 255, 255, 255), imgThreshold); The fourth channel is unused for HSV. This call would give you 10-counts of noise in your color detector threshold for each dimension. As mentioned by, SSteve your threshold should work, but you may need to expand your threshold boundaries to capture the yellow-ish color in your image. Hope that helps! A: I ran your code and it worked fine. Perhaps the yellow in your image isn't as yellow as you think. Edit: The other potential difference is that I'm using OpenCV 2.3. Which version are you using? Ok, one more edit: Have you tried looking at your yellow values? That would give you a definitive answer as to what values you should use in cvInRangeS. Add these two lines after the call to cvCvtColor: uchar* ptr = (uchar*)(imgHsv->imageData); printf("H: %d, S:%d, V:%d\n", ptr[0], ptr[1], ptr[2]); For my image, I got: H: 30, S:109, V:255 That's why your code worked for me.
{ "pile_set_name": "StackExchange" }
Q: Updating an existing Android app in Eclipse? I already created a free app using Eclipse and have it on Google Play. Now I am wanting to add some extra features into it and have it as a paid app. Now I am wondering if I have to create a whole new program or will changing the existing package name and export key suffice? Thanks A: Google Play does not allow you to change a free app to a paid app. The reasons behind it are beyond me. You have to upload a new app with a new package name onto Google Play. In eclipse right click on the project and select "Android Tools -> Rename Application Package". You don't have to create a new keystore to export the app, you can use the same you used for the previous one.
{ "pile_set_name": "StackExchange" }
Q: How to submit a PR against a now-broken upstream? I'm a Git(Hub) neophyte. I forked, changed and submitted a PR against a GitHub repo (R'). The PR has not been reviewed|accepted. Meanwhile I wanted to submit a separate (non-overlapping) PR and followed instructions here to create a 2nd copy of the remote repo in my GitHub account (R"). I wrote the code and committed the changes to it (R") but I'm unable to submit a PR using the GitHub UI. Am I screwed? Or is there a way I can add back the original origin so that I may submit the PR? I Googled around and tried: git remote add upstream https://github.com/GoogleCloudPlatform/cloud-builders-community.git But that made no difference. Any guidance would be appreciated! A: You shouldn't need to "fork" twice: from the local clone of your first fork, you can simply create another branch (from upstream/master), make a second patch in that branch, push that second branch make a second PR from said second branch on your GitHub fork.
{ "pile_set_name": "StackExchange" }
Q: Copy a basic_string to vector Please suggest an efficient way to copy bytes from a basic_string< char16_t> to vector< uint8_t>. I am not concerned with the encoding, and just want to copy the bytes to the bytearray. It will later be interpreted with the correct encoding downstream. Thanks. A: An option is to get the data pointer, cast it to your new type and assign it to your target vector: std::basic_string<char16_t> src; const uint8_t *begin = reinterpret_cast<uint8_t const*>(src.data()); const uint8_t *end = reinterpret_cast<uint8_t const*>(src.data() + src.size()); std::vector<uint8_t> dst(begin,end); This is one of the few cases where reinterpret_cast is a perfectly valid choice. From cppreference (highlights added by me): Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions. It is purely a compiler directive which instructs the compiler to treat the sequence of bits (object representation) of expression as if it had the type new_type.
{ "pile_set_name": "StackExchange" }
Q: Did China ever consider a phonetic writing system? I was surprised to learn the following about the Japanese and Korean languages: Japanese used a lot of Chinese characters in their language and had no phonetic system, until around the year 800 when they made their first kana. (They still use a lot of Chinese characters, but the point is they originally had no phonetic system, then made one.) Korean also used a lot of Chinese characters in their language and had no phonetic system until around the year 1443 when they made Hangul. (I'm not sure if they still use a lot of Chinese characters, but the point is the same as Japan.) So you can see how this brings up my question. Did China ever consider a phonetic writing system? In other words, are there any emperors, scholars, court eunuchs or other offices, or just wise men of some school like Confucianism or Daoism or something... who wrote down some thoughts on considering a phonetic writing system? Did any of them at least note what Japan and Korea did, and explicitly reject it? And most crucially, did they state their reasons for rejecting it? The time period I'm interested in is pre-modern China. In other words, ancient times to 1912. EDIT: The analyses are fascinating, but they're not what I'm asking. I'm just asking for examples of some written record of some Chinese person, writing down his thoughts on a phonetic system, why he considered it and why he rejected it... if such a record exists. I would really like to see what were his own thoughts. A: No, there is no known record of that kind of native linguistic script analysis in pre-modern China, although its quite possible it came up and was rejected, for reasons I'll outline below. The main issue here is that the mostly-logographic system China uses has historically been covering up for the fact that quite a few Chinese "dialects" are not mutually-intelligible (eg: Cantonese, Suzhounese, Sichuanese)1. IOW, they are really separate languages. On top of that, large swaths of the country are inhabited by people who even the Chinese will admit don't speak Chinese. You obviously can't write a single document for several completely different languages using a phonetic-based writing system, without having to translate everything you write into every one of the different languages. Not only is that a crazy amount of work, it would erect brand new cultural barriers between all the various languages. Its possible the entire popular concept of "China" as a culturally unified unit could fall apart. This is why they've been forced to stick to logographs. That being said, there was Nüshu. This was a fully phonetic syllabary, which means it only needed about 120 glyphs (with a further 500ish logographs borrowed from Hanzi). The story of Nüshu is probably the best example a historian could ask for of the problems posed by trying to promote a phonetic writing system in China. It was regional (as it would have to be, covering only one dialect). In this case, the dialect it covered was Tuhua, which is of course mutually unintelligible with any of the major Chinese dialects, and is spoken only in the border regions of three neighboring south China provinces. Obviously the script wouldn't be of much use outside those areas, as its "installed base" of Tuhua works wouldn't be intelligible outside those areas. The script was so low status compared to Hanzi that it was used almost exclusively by women and its history wasn't really recorded. But we know it is at least as old as the 13th Century, and probably no older than the 10th. Its usage seems to have fallen off drastically once women were allowed the level of education required to learn Hanzi. According to Wikipedia, the last proficient user died in 2004. There are several transcription systems used to translate Chinese into other existing writing systems, like the Latin and Cyrillic character systems. However those appear to be mostly used for the benefit of those who don't speak Chinese, or for those who don't have easy access to native Chinese keyboards, displays, and whatnot. 1 - This would be roughly equivalent to a single government conquering all of Europe and declaring that its (mostly Indo-European speaking) residents actually speak the "European" language, German is the official dialect, and English, Dutch, French, Spanish, Russian, etc. are all just regional dialects of European. A: Yes, but neither by the Chinese nor only for Chinese. Kublai Khan ordered the Tibetan Sakya trizin Phagpa to create a universal alphabet to be used by the languages of his empire. It's usually known after him as 'Phags-pa Script'. Because he wasn't interested in marking tones, Phagpa differentiated Chinese syllables by recourse to outdated pronunciations contained in earlier dictionaries. It got used in official documents but never displaced the separate local scripts. Phags-pa never had a reasonable hope of replacing Chinese characters in particular without a campaign of massive oppression against the empire's own clerical class, which Kublai and his tax collectors weren't remotely interested in. To the Chinese, characters were civilization itself... It's important to note that—apart from acting as China's version of Latin—any Chinese characters were revered as holy in and of themselves. They were considered inspired by Heaven, handed down from their great first ancestors, and a perfect encapsulation of the quintessence of Nature's myriad things. The majority of characters—the ones that aren't based on direct drawings of their subjects—usually encode information on both meaning and pronunciation and were thus still considered 'ideal', even when pronunciation could drift as far apart as 工 (gōng, originally kong) and 江 (jiāng, originally krong) or 率's two pronunciations of (s)rut turning into lǜ and shuài. Like Talmudic Jews ritually dealing with any paper containing the name of G-d, Chinese cities had special towers (惜字塔, xīzì tǎ) for specially destroying anything with writing upon it with the appropriate respect. That applied to shopping lists as well as sutras and the Confucian classics. The very concepts of civilization and peaceful civil life in Chinese are expressed in words dealing with literacy (i.e., in characters), not with agriculture: 文, 文明, 文化. The native name of most 'Confucian Temples' is actually 'Temples of the Written Word': 文庙. The highest of the 'Three Perfections'—calligraphy, poetry, and painting—was beautiful and idiosyncratic penmanship, and its influence overflowed into the others. Li Bai's most famous poem memorably captured the spill of moonlight across his bedroom floor in a sprinkle of 'moon' and 'light' characters across its lines; painting followed the technique and criticism of the calligraphers. Their work also formed one of the 'Four Arts' of the gentleman, alongside painting, go, and the zither. Three of the great Chinese inventions—greater than gunpowder or the compass within their own culture—were tech dealing with the written word: paper, block printing, and moveable type. The characters are also cultural artifacts as much as writing script. Some form the basis or important points in stories, jokes, riddles, &c. Some are tied to ideas about the Five Elements. Including the proper stroke number or character radical was reckoned essential to properly harmonizing a person's identity with the universe (read: stars) at the moment of their birth. ...and syllabaries, let alone alphabets, were infra dig... As T.E.D. pointed out, there was a semiphonetic 'Women's Script' used by the Han women of Jiangyong in the wilderness of southwestern Hunan. No one paid attention to it or cared until the late 20th century. The medieval Chinese didn't pay attention to their own syllabaries, let alone those of tribute and barbarian peoples. But the Koreans and Japanese themselves felt the same way. Within Korea, hangul was the province of 'illiterates' like women and the laboring classes; proper gentlemen used characters regardless of their awkwardness for their language. Decent Korean and Japanese diplomats would've avoided the topic, not shown it off. ...until modernity. Once the Shang Dynasty started using the characters as a religious script to divine the will of Heaven, alphabetic Chinese was probably a lost cause, even though the early forms of the language differentiated their words with terminal consonants and consonant clusters instead of using many homonyms distinguished by tone. The Mongolian overlords tried for a bit to see if they couldn't universalize and standardize everything (They couldn't), but the serious push among the Chinese themselves for change had to wait until after the Opium War, Taiping Rebellion, and industrializing Europe's gunboat diplomacy made the inadequacy of the old Confucian model plain. Nearly every European involved wanted the script replaced, and some Chinese intellectuals agreed. Dhi Fonetik Titcerz' Asociecon's IPA was becoming universalist by 1900 but its eventual symbols for Mandarin are a mess (incl. ɕ, ʈ, ʂ, ɥ, ɻ, & ʰ) and it was never considered. Instead, the Republic's early commission on standardizing Mandarin went their own way with zhuyin ('phonetics') based on simplified characters with similar sounds. By 1930, politics made them change the name from 'phonetic letters' to 'phonetic symbols', clarifying that they had no intention of using them as actual letters for Chinese. In the '20s and '30s, advocates plumped the Nationalists' 'Mandarin Romanization' (Guoyu Luomazi) and Soviets' 'New Latin Script' (Ladinghua Xin Wenzi) to replace characters but—despite the Soviet system working fine in CCP controlled areas of the north—the Communists eventually abandoned it in 1944 to increase their appeal among all classes through the rest of China. After the Communist revolution, when all things traditional were to be replaced with Revolutionary fervor, they tried again. They gave up again, given the many many many homophones following the transition from Middle to Modern Mandarin, annoyed masses, and the danger posed by regionalism. As we've talked about, Mao Zedong's original idea as pinyin was being developed in the '50s was for it to replace Chinese characters in toto and force the Mandarin dialect across the country. In the end, modern Chinese is just much clearer and more beautiful the way it's already written; he gave up by 1958. Pinyin is just used in transcribing names into other languages and for teaching kids the pronunciation of the characters. What happened instead was the Chinese script itself was simplified a few times and the vernacular was accepted as literary writing. Kids still have to deal with 'difficult characters' (繁体字, fántǐ zì) and 'the ancient way of writing' (古文, gǔwén) on tests, but they don't have to deal with either in daily life if they choose. Despite what early reformers feared, keeping the characters doesn't harm Chinese educational efforts at all; the kids aren't all as happy as the Finnish but they rank just as highly. That it helps keep foreigners from accessing and influencing Chinese culture is now probably considered more of a feature than a bug. A: TLDR: Phonetic scripts won't work because of how the Chinese languages are structured. So it never really came up before Europeans arrived. Language Issues: There are several ways to answer this question; before I get into the history, it is important to ask: Is it possible to represent Chinese in a phonetic script? According to my first Chinese language book, Beginner's Chinese by Yong Ho, Putonghua [i.e., Mandarin] has 21 consonants and 6 vowels, and most syllables are organized in a CV (Consonant-Vowel) format. Some examples of CV in English: be, he, me. Chinese has a handful of standalone V words, but they usually start with the glottal stop consonant like the one in uh-oh; there are also many CVC words, but the final consonant must be a nasal n or ng; finally, there are some VC words without an initial consonant. And that's it. English, on the other hand, has many, many different syllables: VC (up), CVC (big), CCVC (dread), CVCC (mask), CCV, CCCV, VCC, VCCC, CCVCC (brand), CVCCC, CCCvCC, CVCCCC (texts), etc.[1] So with only 21 constants and 6 vowels, there are only about 1000 possible sound combinations, and about 400 get used. Add in the 4 tones, there are 1600 sounds combinations. In English, there are more than 158,000.[1] The limited number of syllables means that there are a ton of words that would have an identical spelling. These are called homophones. While English has a bunch of homophones Chinese has so many that it would be impractical to use a phonetic script. History: However, this didn't stop people from trying. Chapter 2 of China's Soviet Dream (this book is awesome) speaks in great detail about language reform in the first decade of the PRC. China wanted to modernize, and many felt that with a character-based written language, literacy would not be possible. They looked, of course, for historical examples where Chinese people had achieved widespread literacy. There was only one, and it occurred in the Soviet Union. Apparently, in the 1920s, there were a bunch of migrant workers from Shandong living in Eastern Siberia. The Soviet Union invented a romanization scheme based on their Jiaoliao dialect called Latinxua Sin Wenz. It worked — these migrant workers learned to read the newspaper, allowing them to read SU propaganda. For a variety of reasons, these migrant workers returned to China in the early 1930s, and they brought Latinxua Sin Wenz with them. As explained in Part IV of John DeFrancis's Chinese Language, the script was adopted by many Communists in their areas of control and adapted to dialects all over China, including Hakka and Shanghainese. Lu Xun and Mao argued in its favor, and the Communists gave it equal legal status to characters in 1941. World War II and China's Civil War interrupted literacy efforts. The system required accepting a lot of ambiguity because of its lack of tones, but that wasn't insurmountable to native speakers. Instead, the probable reason that the PRC abandoned it sometime in late 1949 or early 1950 was the criticism that its advocates were "a cultural movement of traitors". Having taken over the country, the Communists stopped advocating a policy that would permit greater balkanization. The Party line became to simplify the characters instead and to develop a new latinized alphabet with tones to teach pronunciation. Latinxua Sin Wenz grew in to Hanyu Pinyin, which is in common usage throughout China today. However, it is rarely used for general reading; it is more of an instructive tool to facilitate the dominance of the Beijing Dialect, with the explicit goal of limiting China's linguistic diversity and centering power around Beijing and this the CCP. Hanyu Pinyin makes it easier for me to learn Chinese too! However, you specifically asked about attempts to use a phonetic script prior to 1911. To my knowledge, the first attempts were intended primarily to help Christian missionaries learn Chinese, with one scheme by Matteo Ricci dating to 1583. However, these schemes were developed by non-Chinese for a variety of reasons. The first phonetic script that I am aware of, developed by a Chinese person, was in 1892. This scheme, however, was merely an extension of the missionaries' attempts and was definitely part of a modernization/literacy scheme. [1] Ho, Yong. Beginner's Chinese. Hippocrene Books, 2005. [2] Li, Yan. China's Soviet Dream: Propaganda, Culture, and Popular Imagination. Routledge, 2017. [3] DeFrancis, John. The Chinese Language: Fact and Fantasy. Univ. of Hawaii Press, 1984.
{ "pile_set_name": "StackExchange" }
Q: How to exclude dependencies from maven assembly plugin : jar-with-dependencies? Maven's assembly plugin enables the creation of a big jar including all dependencies with descriptorRef jar-with-dependencies. How can one exclude some of these dependencies? It seems like it does not have such a configuration? Is there another solution? A: Add the <scope>provided</scope> to the dependencies you don't want included in the jar-with-dependencies, e.g. <dependency> <groupId>storm</groupId> <artifactId>storm</artifactId> <version>0.6.1-SNAPSHOT</version> <scope>provided</scope> </dependency> A: You should use the excludes option available in dependencySet. Follow below.: Example in your pom.xml: ... <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.3</version> <configuration> <finalName>../final/${project.artifactId}</finalName> <archive> <manifest> <addClasspath>false</addClasspath> <mainClass>com.entrerprise.App</mainClass> </manifest> </archive> <descriptors> <descriptor>src/main/resources/jar-with-deps-with-exclude.xml</descriptor> </descriptors> <appendAssemblyId>false</appendAssemblyId> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> ... Now in your new file jar-with-deps-with-exclude.xml (where dependencySet lives): <?xml version="1.0" encoding="UTF-8"?> <assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd"> <id>jar-with-dependencies-and-exclude-classes</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <outputDirectory>/</outputDirectory> <useProjectArtifact>false</useProjectArtifact> <unpack>true</unpack> <scope>runtime</scope> <excludes> <exclude>junit:junit</exclude> <exclude>commons-cli:commons-cli</exclude> <exclude>org.apache.maven.wagon:wagon-ssh</exclude> </excludes> </dependencySet> </dependencySets> <fileSets> <fileSet> <outputDirectory>/</outputDirectory> <directory>${project.build.outputDirectory}</directory> </fileSet> </fileSets> </assembly> That's all. A: This example indicates one way to do this: <dependencySets> <dependencySet> .... <excludes> <exclude>commons-lang:commons-lang</exclude> <exclude>log4j:log4j</exclude> </excludes> </dependencySet> .... </dependencySets> Essentially we would use the excludes option available in dependencySet. See also: https://maven.apache.org/plugins/maven-assembly-plugin/assembly-component.html
{ "pile_set_name": "StackExchange" }
Q: Does digestion require hydrochloric acid? Would our digestion function any differently if we secreted something else, like sulfuric or nitric acid, instead? I'd assume an acidic environment may be required, but not sure if chloride is also required as well! Perhaps we just use it out of convenience—e.g., presumably blood serum $$\left[\ce{SO4^2-}\right] + \left[\ce{NO3-}\right] \ll \left[\ce{Cl-}\right]$$ and channeling polyatomic ions across the membrane may be significantly more difficult than doing the same for chloride as well! *Edit: In fact, Wikipedia states In the stomach, chief cells release pepsinogen. This zymogen is activated by hydrochloric acid (HCl), which is released from parietal cells in the stomach lining. The hormone gastrin and the vagus nerve trigger the release of both pepsinogen and HCl from the stomach lining when food is ingested. Hydrochloric acid creates an acidic environment, which allows pepsinogen to unfold and cleave itself in an autocatalytic fashion, thereby generating pepsin (the active form). Pepsin cleaves the 44 amino acids from pepsinogen to create more pepsin. So, while maybe something like $\ce{H2SO4}$ or $\ce{HNO3}$ could work too, hydrochloric acid is just more convenient to use? A: Parietal cells use ion pumps to expel protons and chlorine ions into the lumen, which create the necessary acidic environment to denature pepsinogen into pepsin. It is the low pH environment that reconfigures or denatures pepsinogen into pepsin. The acid used does not matter. For example, one experiment in classifying properties of pepsinogen used a 3.5 pH solution of 0.5 N sulfuric acid to activate pepsin. We evolved stomachs with parietal cells that use an energetically expensive process to maintain the acidic gradient necessary for digestion and protection from pathogens. It may be that biochemical pathways to generate other acids did not evolve, because it is either energetically cheaper for these cells to make HCl, compared with other pathways that would generate other acids of sufficient strength; or the relevant chemical components involved are more abundant than others in what we eat and drink, and thus easier to make in quantities needed for digestion and defense. Chloride ions also serve a role in maintaining intra- and extracellular fluid pressure and thus play a larger part as electrolytes in the normal function of the body — they are available and cells use them. But to answer your main question, an acidic environment activates pepsin, and it is not chemically necessary for this to be created by hydrochloric acid.
{ "pile_set_name": "StackExchange" }
Q: Присвоение элементам class с помощью js, работа с innerHTML и получение данных из адресной строки Если в адресной строке нет ничего после знака "?" - то должен присваиваться определенный class некоторым элементам и вноситься изменения в элемент с class="error", чего не происходит. В каком месте я ошибся? Вроде все правильно сделал. Код: Html: <body> <div class="error"></div> <p class="llogin" id="llogin">Ваш логин: <p></p><p> <p class="mail" id="mail">Ваш Mail: <p></p></p> <p class="phone" id="phone">Ваш телефон: <p></p></p> <form> <input placeholder="Изменить логин" class="login" name="login" id="login"> <input type="password" class="password" placeholder="Сменить пароль" name="password" id="password"> <input type="repass" class="repass" placeholder="Повторите пароль" name="repassword" id="repass"> <input placeholder="Изменить mail или телефон" class="binding" name="binding" id="binding"> </form> <button class="button" id="button">Изменить данные</button> </body> Js: var str = window.location.search.replace( '?', ''); var ver; if(str = ""){ document.querySelector("#llogin").className = "hidden"; document.querySelector("#mail").className = "hidden"; document.querySelector("#phone").className = "hidden"; document.querySelector("#password").className = "hidden"; document.querySelector("#repass").className = "hidden"; document.querySelector("#binding").className = "hidden"; document.querySelector("#button").className = "hidden"; document.querySelector(".error").innerHTML = "Произошла неизвестная ошибка"; }else{ A: var str = location.search.substring(1); https://some.url?then=some&query=string location.search.substring(1) = then=some&query=string if(str = ""){ // str присвоили ""
{ "pile_set_name": "StackExchange" }
Q: How to generate square thumbnail of an image? I want to create thumbnails of size 75x75 square from originals. The thumbnail will not look stretched in one dimension as it will not follow the aspect ratio. If have used Flickr, you will see they generate square thumbnails. I need the same thing. Any clue or help is appreciated. EDIT: I am on .NET 4.0 C# I am looking for programmatic way to generate thumbs. Batch capability needed if no dll available. A: This is from Codeproject: static System.Drawing.Image FixedSize(System.Drawing.Image imgPhoto, int Width, int Height) { int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)Width / (float)sourceWidth); nPercentH = ((float)Height / (float)sourceHeight); if (nPercentH < nPercentW) { nPercent = nPercentH; destX = System.Convert.ToInt16((Width - (sourceWidth * nPercent)) / 2); } else { nPercent = nPercentW; destY = System.Convert.ToInt16((Height - (sourceHeight * nPercent)) / 2); } int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.Clear(Color.White); grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; }
{ "pile_set_name": "StackExchange" }
Q: What exactly does "import *" import? In Python, what exactly does import * import? Does it import __init__.py found in the containing folder? For example, is it necessary to declare from project.model import __init__, or is from project.model import * sufficient? A: The "advantage" of from xyz import * as opposed to other forms of import is that it imports everything (well, almost... [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods...) from the imported module without prefixing them with the module's name. For example >>> from math import * >>>pi 3.141592653589793 >>>sin(pi/2) >>>1.0 This practice (of importing * into the current namespace) is however discouraged because it provides the opportunity for namespace collisions (say if you had a variable name pi prior to the import) may be inefficient, if the number of objects imported is big doesn't explicitly document the origin of the variable/method/class (it is nice to have this "self documentation" of the program for future visit into the code) Typically we therefore limit this import * practice to ad-hoc tests and the like. As pointed out by @Denilson-Sá-Maia, some libraries such as (e.g. pygame) have a sub-module where all the most commonly used constants and functions are defined and such sub-modules are effectively designed to be imported with import *. Other than with these special sub-modules, it is otherwise preferable to ...: explicitly import a few objects only >>>from math import pi >>>pi >>>3.141592653589793 >>> sin(pi/2) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sin' is not defined or import the module under its own namespace (or an alias thereof, in particular if this is a long name, and the program references its objects many times) >>>import math >>>math.pi >>>3.141592653589793 etc.. >>>import math as m #bad example math being so short and standard... >>>m.pi >>>3.141592653589793 etc.. See the Python documentation on this topic (a) Specifically, what gets imported with from xyz import * ? if xyz module defines an __all__ variable, it will import all the names defined in this sequence, otherwise it will import all names, except these which start with an underscore. Note Many libraries have sub-modules. For example the standard library urllib includes sub-modules like urllib.request, urllib.errors, urllib.response etc. A common point of confusion is that from urllib import * would import all these sub-modules. That is NOT the case: one needs to explicitly imports these separately with, say, from urllib.request import * etc. This incidentally is not specific to import *, plain import will not import sub-modules either (but of course, the * which is often a shorthand for "everything" may mislead people in thinking that all sub-modules and everything else would be imported). A: It import (into the current namespace) whatever names the module (or package) lists in its __all__ attribute -- missing such an attribute, all names that don't start with _. It's mostly intended as a handy shortcut for use only in interactive interpreter sessions: as other answers suggest, don't use it in a program. My recommendation, per Google's Python style guide, is to only ever import modules, not classes or functions (or other names) from within modules. Strictly following this makes for clarity and precision, and avoids subtle traps that may come when you import "stuff from within a module". Importing a package (or anything from inside it) intrinsically loads and executes the package's __init__.py -- that file defines the body of the package. However, it does not bind the name __init__ in your current namespace (so in this sense it doesn't import that name). A: Yes, it does. It imports everything (that is not a private variable, i.e.: variables whose names start with _ or __), and you should try not to use it according to "Properly importing modules in Python" to avoid polluting the local namespace. It is enough, but generally you should either do import project.model, which already imports __init__.py, per "Understanding python imports", but can get too wordy if you use it too much, or import project.model as pm or import project.model as model to save a few keystrokes later on when you use it. Follow Alex's advice in "What exactly does "import *" import?"
{ "pile_set_name": "StackExchange" }
Q: Understanding how Git LFS repository works for developers who don't have LFS extension installed As the title already says, I am interested in how would a git repository with LFS files behave for developers who don't have LFS git extension installed (cloning of affected files, committing of affected files, etc). Would it be even possible for them to clone such repository (or at least by LFS affected files)? This article explains LFS for git in a very nice way (for beginners). A: The technical spec is actually pretty understandable too : https://github.com/git-lfs/git-lfs/blob/master/docs/spec.md git lfs replaces the actual files with a text pointer tracked in the git repository : Example of a v1 text pointer: version https://git-lfs.github.com/spec/v1 oid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393 size 12345 (ending \n) Someone without the lfs extension would see these files instead of the expected content, but would otherwise be able to interact with the repository.
{ "pile_set_name": "StackExchange" }
Q: link_to action "show" to another controller ruby 1.9.2p290 rails 3.1.1 Basically I have two models: CHEFS and RECIPES. class Chef < ActiveRecord::Base has_many :recipes end class Recipe < ActiveRecord::Base belongs_to :chef end And the following routes: resources :recipes resources :chefs do # list of recipes from chef resources :recipes, :to => 'recipes#index_chef' end With this I have the urls (exactly what I want): /recipes - list of recipes /chefs/username/recipes - list of chef's recipes /chefs/ - list of chefs /chefs/username - chef's profile RecipesController: def index @chef = Chef.find_by_username(params[:chef_id]) @recipes = Recipe.where({ :status_id => 1 }).order("id desc").page(params[:page]).per(9) end def index_chef @chef = Chef.find_by_username(params[:chef_id]) @recipes = @chef.recipes.where(:status_id => 1).order("id desc").page(params[:page]).per(9) end My recipes index view: <%= link_to recipe.chef.username.capitalize, @chef %> In http://3001/chefs/username/recipes I have the correct link to Chef profile. But in http://3001/recipes I have the wrong link. What am I doing wrong? A: In http://3001/recipes (which is a weird url!), you don't have access to params[:chef_id]. So you won't have the @chef variable available to you in the view. It should be nil! To get around this, change your link_to to this <%= link_to recipe.chef.username.capitalize, recipe.chef %> You might want to eager load the chef to your @recipes records by loading that in your controller like this: @recipes = Recipe.where({ :status_id => 1 }).includes(:chef).order("id desc").page(params[:page]).per(9) Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: How to change the name of a variable in a for loop I would like to change the name of a variable within a for loop, using the loop index in the name of the variable. I've tried the following syntax: A= [1,2,3] for i = 1:3 global x{i} x{i}=A[i] end This isn't the right syntax, and googling has not led me to the correct syntax. I've also tried A= [1,2,3] for i = 1:3 global x$i x$i=A[i] end My hope is to create three variables, x1, x2, and x3 each containing the appropriate element of A. Maybe I don't even need to write a loop to do this--I'm open to completely different methods of accomplishing this as well. A: As others have said, it's a bit questionable whether one should do this, but if this is really what you want to do, here's how you can do it: A = [1, 2, 3] for i = 1:3 @eval $(Symbol("x$i")) = $(A[i]) end after which these global variables are assigned: julia> x1, x2, x3 (1, 2, 3) The inner expression is equivalent to writing this: eval(:($(Symbol("x$i")) = $(A[i]))) In other words, you construct and then eval an assignment expression where the left hand side is the symbol x$i and the right hand side is the value of A[i]. Note that you can only define global variables like this, not local ones because eval always operates in global scope. Other languages have "local eval", Julia does not because the very possibility of local eval in a language makes optimization much harder.
{ "pile_set_name": "StackExchange" }
Q: How to get and set / access and modify a global variable between components I'm new to Angular, currently using Angular 5 Cli with VS Code. I have 2x components (Comp1 & Comp2) that need to access the same variable which is ultimately a string. This variable is rendered in the 3rd Component's (Comp 3) View/HTML template. What's the best way to access this? Example files below: Comp3.html <a routerLink="/{{modeName | lowercase}}" class="mode"><span class="icon {{modeName | lowercase}}"></span><span>{{modeName}}</span></a> Comp3.ts import { Component } from '@angular/core'; import { LowerCasePipe } from '@angular/common'; @Component({ selector: 'pm-nav-button', templateUrl: './comp3.component.html' }) export class Comp3 { constructor() {} modeName: string; } Comp2.ts & Comp1.ts - (these are configured based on Angular Routing whichever view loads it'll set 'Grid' mode or 'List' mode) import { Component, OnInit } from '@angular/core'; import { LowerCasePipe } from '@angular/common'; import { Comp3 } from './comp3-component'; @Component({ selector: 'content-two', templateUrl: './comp3.component.html' }) export class Comp2 implements OnInit { constructor(private _comp3: Comp3) {} ngOnInit(): void { this._Comp3.modeName = 'Grid'; } } However, it all compiles fine with no errors, but I'm not seeing 'Grid' binded to the template's bindings (interpolation). I think I'm setting the the variable after the template has rendered, even though I'm setting it within ngOnInit. I want to be able to access, check and set this variable from other components. How do I do this? Thanks A: When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should use a shared service. You can try following code snippet. import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export class SharedService { private messageSource = new BehaviorSubject<string>("list"); currentMessage = this.messageSource.asObservable(); constructor() { } changeMessage(message: string) { this.messageSource.next(message) } } //Comp1 import { Component, OnInit } from '@angular/core'; import {SharedService} from '../shared.service'; @Component({ selector: 'app-comp1', templateUrl: './comp1.component.html', styleUrls: ['./comp1.component.css'] }) export class Comp1Component implements OnInit { message:string; constructor(private data: SharedService) { } ngOnInit() { this.data.currentMessage.subscribe(message => this.message = message) console.log(this.message); } } //Comp2 import { Component, OnInit } from '@angular/core'; import {SharedService} from '../shared.service'; @Component({ selector: 'app-comp2', templateUrl: './comp2.component.html', styleUrls: ['./comp2.component.css'] }) export class Comp2Component implements OnInit { message:string; constructor(private data: SharedService) { } ngOnInit() { this.data.currentMessage.subscribe(message => this.message = message) console.log(this.message); } }
{ "pile_set_name": "StackExchange" }
Q: Return one result from LINQ Query if you have a select LINQ query that should only return one result, do you have to have a foreach loop to get the result? Or is there a better way? A: // Will return a default value if no object is found in the DB db.Table.SingleOrDefault(x => x.something == someParameter); or // Will throw an exception if records are not found db.Table.Single(x => x.something == someParameter); Thanks to Mehrdad for the comment...both lines have been updated. If it's possible that your query could result in more than one record being returned, then (as mentioned in comments) Single() and SingleOrDefault() are the wrong methods to call. You would keep the same syntax, but call First() and FirstOrDefault() respectively. A: var myLinqObj = db.MyObjects.Take(1).SingleOrDefault(); A: You can use either First or Single. First returns the first row, whether there are multiple rows or just the one. Single expects only one row to be returned, and throws an exception if there are multiple rows. Single is therefore potentially a better choice if you expect to only have one row, so that you'll see the problem immediately and can troubleshoot it.
{ "pile_set_name": "StackExchange" }
Q: Plotting More than 2 Factors Suppose I ran a factor analysis & got 5 relevant factors. Now, I want to graphically represent the loading of these factors on the variables. Can anybody please tell me how to do it. I can do using 2 factors. But can't able to do when number of factors are more than 2. The 2 factor plotting is given in "Modern Applied Statistics with S", Fig 11.13. I want to create similar graph but with more than 2 factors. Please find the snap of the Fig mentioned above: X & y axes are the 2 factors. Regards, Ari A: Beware: not the answer you are looking for and might be incorrect also, this is my subjective thought. I think you run into the problem of sketching several dimensions on a two dimension screen/paper. I would say there is no sense in plotting more factors' or PCs' loadings, but if you really insist: display the first two (based on eigenvalues) or create only 2 factors. Or you could reduce dimension by other methods also (e.g. MDS). Displaying 3 factors' loadings in a 3 dimensional graph would be just hardly clear, not to think about more factors. UPDATE: I had a dream about trying to be more ontopic :) You could easily show projections of each pairs of factors as @joran pointed out like (I am not dealing with rotation here): f <- factanal(mtcars, factors=3) pairs(f$loadings) This way you could show even more factors and be able to tweak the plot also, e.g.: f <- factanal(mtcars, factors=5) pairs(f$loadings, col=1:ncol(mtcars), upper.panel=NULL, main="Factor loadings") par(xpd=TRUE) legend('topright', bty='n', pch='o', col=1:ncol(mtcars), attr(f$loadings, 'dimnames')[[1]], title="Variables") Of course you could also add rotation vectors also by customizing the lower triangle, or showing it in the upper one and attaching the legend on the right/below etc. Or just point the variables on a 3D scatterplot if you have no more than 3 factors: library(scatterplot3d) f <- factanal(mtcars, factors=3) scatterplot3d(as.data.frame(unclass(f$loadings)), main="3D factor loadings", color=1:ncol(mtcars), pch=20) Note: variable names should not be put on the plots as labels, but might go to a distinct legend in my humble opinion, specially with 3D plots.
{ "pile_set_name": "StackExchange" }
Q: Sleeping for an exact duration My understanding of the Sleep function is that it follows "at least semantics" i.e. sleep(5) will guarantee that the thread sleeps for 5 seconds, but it may remain blocked for more than 5 seconds depending on other factors. Is there a way to sleep for exactly a specified time period (without busy waiting). A: As others have said, you really need to use a real-time OS to try and achieve this. Precise software timing is quite tricky. However... although not perfect, you can get a LOT better results than "normal" by simply boosting the priority of the process that needs better timing. In Windows you can achieve this with the SetPriorityClass function. If you set the priority to the highest level (REALTIME_PRIORITY_CLASS: 0x00000100) you'll get much better timing results. Again - this will not be perfect like you are asking for, though. This is also likely possible on other platforms than Windows, but I've never had reason to do it so haven't tested it. EDIT: As per the comment by Andy T, if your app is multi-threaded you also need to watch out for the priority assigned to the threads. For Windows this is documented here. Some background... A while back I used SetPriorityClass to boost the priority on an application where I was doing real-time analysis of high-speed video and I could NOT miss a frame. Frames were arriving to the pc at a very regular (driven by external framegrabber HW) frequency of 300 frames per second (fps), which fired a HW interrupt on every frame which I then serviced. Since timing was very important, I collected a lot of stats on the interrupt timing (using QueryPerformanceCounter stuff) to see how bad the situation really was, and was appalled at the resulting distributions. I don't have the stats handy, but basically Windows was servicing the interrupt whenever it felt like it when run at normal priority. The histograms were very messy, with the stdev being wider than my ~3ms period. Frequently I would have gigantic gaps of 200 ms or greater in the interrupt servicing (recall that the interrupt fired roughly every 3 ms)!! ie: HW interrupts are FAR from exact! You're stuck with what the OS decides to do for you. However - when I discovered the REALTIME_PRIORITY_CLASS setting and benchmarked with that priority, it was significantly better and the service interval distribution was extremely tight. I could run 10 minutes of 300 fps and not miss a single frame. Measured interrupt servicing periods were pretty much exactly 1/300 s with a tight distribution. Also - try and minimize the other things the OS is doing to help improve the odds of your timing working better in the app where it matters. eg: no background video transcoding or disk de-fragging or anything while your trying to get precision timing with other code!! In summary: If you really need this, go with a real time OS If you can't use a real-time OS (impossible or impractical), boosting your process priority will likely improve your timing by a lot, as it did for me HW interrupts won't do it... the OS still needs to decide to service them! Make sure that you don't have a lot of other processes running that are competing for OS attention If timing is really important to you, do some testing. Although getting code to run exactly when you want it to is not very easy, measuring this deviation is quite easy. The high performance counters in PCs (what you get with QueryPerformanceCounter) are extremely good. Since it may be helpful (although a bit off topic), here's a small class I wrote a long time ago for using the high performance counters on a Windows machine. It may be useful for your testing: CHiResTimer.h #pragma once #include "stdafx.h" #include <windows.h> class CHiResTimer { private: LARGE_INTEGER frequency; LARGE_INTEGER startCounts; double ConvertCountsToSeconds(LONGLONG Counts); public: CHiResTimer(); // constructor void ResetTimer(void); double GetElapsedTime_s(void); }; CHiResTimer.cpp #include "stdafx.h" #include "CHiResTimer.h" double CHiResTimer::ConvertCountsToSeconds(LONGLONG Counts) { return ((double)Counts / (double)frequency.QuadPart) ; } CHiResTimer::CHiResTimer() { QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&startCounts); // starts the timer right away } void CHiResTimer::ResetTimer() { QueryPerformanceCounter(&startCounts); // reset the reference counter } double CHiResTimer::GetElapsedTime_s() { LARGE_INTEGER countsNow; QueryPerformanceCounter(&countsNow); return ConvertCountsToSeconds(countsNow.QuadPart - startCounts.QuadPart); } A: No. The reason it's "at least semantics" is because that after those 5 seconds some other thread may be busy. Every thread gets a time slice from the Operating System. The Operating System controls the order in which the threads are run. When you put a thread to sleep, the OS puts the thread in a waiting list, and when the timer is over the operating system "Wakes" the thread. This means that the thread is added back to the active threads list, but it isn't guaranteed that t will be added in first place. (What if 100 threads need to be awaken in that specific second ? Who will go first ?) A: While standard Linux is not a realtime operating system, the kernel developers pay close attention to how long a high priority process would remain starved while kernel locks are held. Thus, a stock Linux kernel is usually good enough for many soft-realtime applications. You can schedule your process as a realtime task with the sched_setscheduler(2) call, using either SCHED_FIFO or SCHED_RR. The two have slight differences in semantics, but it may be enough to know that a SCHED_RR task will eventually relinquish the processor to another task of the same priority due to time slices, while a SCHED_FIFO task will only relinquish the CPU to another task of the same priority due to blocking I/O or an explicit call to sched_yield(2). Be careful when using realtime scheduled tasks; as they always take priority over standard tasks, you can easily find yourself coding an infinite loop that never relinquishes the CPU and blocks admins from using ssh to kill the process. So it might not hurt to run an sshd at a higher realtime priority, at least until you're sure you've fixed the worst bugs. There are variants of Linux available that have been worked on to provide hard-realtime guarantees. RTLinux has commercial support; Xenomai and RTAI are competing implementations of realtime extensions for Linux, but I know nothing else about them.
{ "pile_set_name": "StackExchange" }
Q: Rubymine and running rspec "rspec-core is not part of the bundle" I am trying to run a rails app which was not created using rubymine. Its is a very different sort of app using rails engines loaded...When I try running tests, I get the following error message Testing started at 12:29 ... /Users/userbnamexxxx/.rbenv/versions/1.9.3-p327/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/rubygems_integration.rb:214:in `block in replace_gem': rspec-core is not part of the bundle. Add it to Gemfile. (Gem::LoadError) from /Users/userbnamexxxx/.rbenv/versions/1.9.3-p327/bin/rspec:22:in `<top (required)>' from -e:1:in `load' from -e:1:in `<main>' I edited the configuration and it does have bundle exec checkbox checked. Tests tuns fine in the console. I tried it another project which is a default bug standard rails app and its fine there... I am using rbenv for managing ruby versions.... Please help as I am really stuck and it would be nice to not use the terminal.... A: Add the gem rspec-core into your .Gemfile
{ "pile_set_name": "StackExchange" }
Q: same branch same quarter number calculation What I need to add is when employee title X switches to a different title (Y or Z) within the SAME branch, to modify their Total FTE for the time in the quarter that they were in that new title (Y or Z). So the logic is: For position X to Y IF [Position Start Date] is between [Q2 start date] AND [Q2 end date] and [Employee Title] of [Employee ID] was X and is now Y THEN [Total FTE calculated] = (((([Position Start Date] - [Quarter Start Date])/[Days in Quarter]) * [Total FTE]) + ((([Quarter End Date] - [Position Start Date])/[Days in Quarter]) * [Total FTE]) * 0.5) For position X to Z AND IF [Position Start Date] is between [Q2 start date] AND [Q2 end date] AND [Employee Title] of [Employee ID] was X and is now Z THEN [Total FTE calculated] = ([Position Start Date] - [Quarter Start Date])/[Days in Quarter]) * [Total FTE]) ELSE [Total FTE Calculated] = [Total FTE] * 1 END As you can see I'm missing knowledge of some of the SQL operators to do this properly. Any help you can provide would be greatly appreciated! Please and thank you! A: A rough sketch, date arithmetic differs a lot between different vendors of DBMS so I used your expressions. I've used the variable :new_emplyee_title for the new title. update Employees set [Total FTE calculated] = case when :new_emplyee_title = Y then [ expression for Y ] else [ expression for Z ] end where [Position Start Date] between [Q2 start date] AND [Q2 end date] and [Employee Title] = X and :new_emplyee_title in (Y,Z); If you DBMS support triggers, this would fit like hand in glove in an update trigger.
{ "pile_set_name": "StackExchange" }
Q: How do you pronounce the הוי״ה in hataras nedarim (annulment of vows) before Rosh HaShanah? In the siddurs I've seen, we ask for annulment for vows made "with the name הוי״ה ". That word is left unvowelized. How is it pronounced? A: Usually I hear it pronounced "havaya." I think we refer to the four-letter name (yud-kay-vov-kay) as "havaya" ("existence") because it has the same letters and same root. Has anyone heard otherwise?
{ "pile_set_name": "StackExchange" }
Q: On free Jazz and Ornette Coleman Why is Ornette Coleman considered one of the best musicians on the Jazz world? I have had the chance to listen to one of his albums, "The Shape of the Jazz to Come," and to be honest, I don't find it easy to follow. One friend, who loves Jazz, by the way, once told me that Ornette Coleman produces him nausea. Ive read somewhere that the final divorce between Jazz and the African American audience was, in big parts, due to the jazz that Coleman, Coltrane, Sun Ra, etc were making during the 60's. Is this an accurate statement? A: I think if you look beyond taste/personal preference it's easy to see that Coleman was an extremely skilled musician. I think it's easy in this day and age to undervalue how much of a impact The Shape of Jazz to Come had. He took the improvisation element of jazz to an extreme. Artists that take music to new levels tend to inspire others even if the music itself is not palatable to the general public. A rock example would be The Velvet Underground. If you find it difficult to listen to, I suggest Coltrane's Ascension which is far more out there and makes The Shape of Jazz to Come seem almost pop. As far as the divorce from African Americans, I am not sure how that is supported. I'd love to read the article you mentioned. Jazz was already suffering from the explosion of rock. Dave Brubeck's Time Out was one of the last significant jazz albums to do well on the charts, and that was in 1959. I think that jazz had divorced itself from all American culture by the 60's and would attempt to reclaim it with fusion, but it never saw the levels of popularity it had once enjoyed. I think what jazz artists began to do in the 60s was challenging for most people, and it became a niche genre, from which it has never truly recovered, even with outliers like Herbie Hancock's "Rockit". Also, we can't ignore that jazz was an older form of music and Baby Boomers wanted something their own and rock music provided that even when they borrowed elements from jazz, and in some ways took music just as far out as Coleman and Coltrane. Never underestimate the power of not listening to your parents' music. A: Jazz is a challenging form of music by nature. It's technically demanding, it uses exotic chords and rhythms, it's dissonant and improvisational. Even when covering familiar material, it departs from the canonical melodies and harmonizations. Perhaps for this reason, while there have always been more pop-oriented, crowd-pleasing versions of jazz, the forms that have garnered the most critical praise are the ones that are furthest from the mainstream, the ones that are most abstract, intellectual and modernist, the ones that are hardest for the casual listener to appreciate. For proof by contradiction, Kenny G is a talented and popular jazz musician who is extremely "easy to follow," but few (if any) jazz purists would count him among the "best musicians [in] the jazz world." There's a real sense that jazz is not meant to be "easy." In contrast, there's no disconnect between being a rock purist and celebrating a three-chord basic-as-dirt barn burner --simple, crowd-pleasing songs are the very heart of rock. While the rarefied nature of experimental jazz may not have helped its popularity in the black community, I personally find it less likely that black audiences were turned off by (black) musicians like Coleman and Coltrane, and more likely that they had already moved on to wholly different styles of music. Traditionally, the black American music audience drives musical innovation in America, embracing new genres and discarding old ones well in advance of the whiter mainstream.
{ "pile_set_name": "StackExchange" }