INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Programmatically clear cached background process I've developed a simple application that loads four mobile webviews side by side. On a fresh install the app fully opens and loads these pages in under 0.5 seconds. However if i minimize this app, for some reason its "cached background process" is over 200mbs! sometimes 250... Seems completely unnecessary as the app loads lightning fast on a fresh install How can I clear this cache when the app is minimized (onbackpressed etc) ![enter image description here](
You need not to worry about cached memory as system will reclaim it when required. however if still you want to do something about it you can call `finish()` in your `onStop()` method. also this is a great answer on this topic by CommonsWare. > "cached background processes" usually refers to processes that do not have a foreground activity and do not have a running service. These processes are kept in memory simply because we have enough memory to do so, and therefore, as you note, the user can switch back to these processes quickly. As Android starts to need more system RAM for yet other processes, the "cached background processes" tend to be the processes that get terminated to free up system RAM
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, android, caching, background process" }
Voice Recognition предлагает дополнительные слова Значит вопрос стоит вот как: у меня в программе используется заполнение полей голосом — нажимаем на кнопку и говорим, а дальше то, что сказал, появляется в `EditText`. Проблема в том, что мне Voice Recognition предлагает ещё дополнительные слова. Как мне сделать так, чтобы Voice Recognition не предлагал дополнительные слова, а только то, что я сказал? Делал распознавание по этому сайту.
Гугл производит ранжирование наиболее подходящих слов, поэтому выводит несколько результатов наиболее похожих на сказанное выражений. `intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5)` В данном случае выведет 5 результатов.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android, распознавание речи" }
How to call an object inside a function? How to call an object inside a function? Example: The `pencil` object is inside a function, and after closing it, I have to use pencil:removeEventListener ("touch", moveLapis) How do I do that? For when I call it normally, an error saying that the pencil is `nil`
You can't. Objects inside functions can only be called inside that scope, to be able to call it from outside, you would have to move your `pencil` object to outside the function, or add a reference outside the function to it. For example: local pencil local function myFunction() pencil = newPencil() end if pencil then pencil:removeEventListener ("touch", moveLapis) end Of course, you would have to check if pencil has a value or some kind of verification before calling the function, to avoid an error.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "lua" }
Symmetric properties of eigen vectors from symmetric properties of matrix In my physical problem I have a matrix: $\begin{bmatrix} 0 & -c_0 & -i b_1 & -c_1 \\\ a_0 & 0 & a_1 & ib_1 \\\ ib_1 & -c_1 & 0 & -c_0 \\\ a_1 & -i b_1 & a_0 & 0 \\\ \end{bmatrix}$ All symbols are reals, $i^2=-1$. The matrix has four eigenvalues satisfying $\lambda_1=-\lambda_2$ and $\lambda_3=-\lambda_4$, this can be shown symbolically. It is **seems** that eigenvectors, corresponding to eigenvalues with the same absolute values, have the following properties so: $V_1 = [v_1,v_2,v_3,v_4]$ and $V_2 = [-v_3,-v_4,-v_1,-v_2]$ (and the same for $V_3$ and $V_4$) in orthonormal basis. I tried to proof it with Mathematica without any luck. I made lots of numerical calculations with different values of parameters and my assumption was always valid. **Is it possible to prof it?** Moreover, it seems that this property is valid for matrices with higher dimensions.
Note that the negative signs in $V_2$ are not important. Now consider $$ J =\pmatrix{0&0&-1&0\\\0&0&0&1\\\\-1&0&0&0\\\0&1&0&0}$$ If you call the original matrix $A$ then you get $$ A V_1 = \lambda_1 V_1 \Leftrightarrow -J^{-1} A J \left(J^{-1}V_1\right) = -\lambda_1 J^{-1} V_1 $$ Your result follows from the observation that $$ A = -J^{-1} A J $$ Hence $-\lambda_1$ is an eigenvalue with eigenvector $J^{-1} V_1$. This answers your question. **Note:** In my original answer I had $J$ in the place of $J^{-1}$. For this matrix the two are the same, so the answer was technically correct. I just fixed in the interest of correctness.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "matrices, eigenvalues eigenvectors, symmetry" }
python: need to close file from mkstemp if I use fdopen? Which of the following is more correct? fi, path = tempfile.mkstemp() f = os.fdopen(fi, "w") f.write(res) f.close() os.close(fi) or: fi, path = tempfile.mkstemp() f = os.fdopen(fi, "w") f.write(res) f.close()
Check `f.fileno()`, it should be the same as `fi`. You should only ever close that file descriptor once, so the second is correct. On Unix, the first causes an error: >>> f.close() >>> os.close(fi) Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 9] Bad file descriptor
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 12, "tags": "python, file, file io, operating system" }
Objective-C: Is it bad practice to use dot notation inside of a message? I couldn't find a similar question so I decided to ask it (this may be more appropriately asked on Programmers, if so I apologize in advance). Is it bad practice to use dot notation along with a message call, like so: [self.view addSubView:otherView]; As opposed to: [[self view] addSubView:otherView]; I was just curious, it looked a tad bit strange but I don't see anything wrong with it. I'm still relatively new to Objective-C and am not familiar with any best practices of note yet.
There's nothing wrong with it. It's merely a stylistic question. Use whichever one you prefer. (The dot notation, by the way, has the **advantage** that the compiler throws an error if you're calling an undeclared property getter or setter with the dot notation, so you can potentially get rid of some strange run-time errors at compile time.)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "objective c, syntax" }
Regular Expression formal documention Is there any formal documentation of how to implement your own regular expression library? What formal documentation, if any, did the makers of the exisiting regular expression libriaries base their code on?
I have written (and abandoned) a javascript parser, including regular expression support. I based it on the ECMAscript definition, which according to itself uses Perl5 regular expressions. This is ECMA 262, I used the 3rd edition, from december 1999. (There is a newer one by now, I don't know if it is as complete in its definition of regular expressions.)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex" }
How to insert a translation into a subdocument nested in an array? With a schema like this, where the "items" field contains an array of subdocuments with nested translations : { "_id" : ObjectId("513740415b51ea0803000001"), "items" : [ { "id" : ObjectId("5137407f5b51ea100f000000"), "title" : { "en" : "Yes", "fr" : "Oui", "es" : "Si" } }, { "id" : ObjectId("5137407f5b51ea100f000003"), "title" : { "en" : "No" } } ], } How would you add a translation to a specific item id ?
You can use the `$` positional operator to update a specific array element of a doc. For example, to add `"de": "nein"`: db.test.update( {'items.id': ObjectId("5137407f5b51ea100f000003")}, {$set: {'items.$.title.de': 'nein'}}) The `$` in the `$set` object represents the index of the element in `items` that the query selection parameter matched.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mongodb" }
PointerEvents not detecting Wacom Tablet I'm attempting to use Pointer Events to detect graphics tablet input including pen pressure, but Chrome and Firefox don't seem to be reading the tablet device (Wacom Intuos 4) properly. All pointer events come back with the same pointerId and pointerType as my mouse, with the default pressure reading of 0.5. The code I'm using looks something like this: container.addEventListener("pointerdown", (event) => { console.log(event.pointerId); console.log(event.pointerType); console.log(event.pressure); }, true); This outputs "1", "mouse", and "0.5". This occurs for the "pointerdown", "pointermove", and "pointerup" events. I've tried this on both Windows and Linux with the appropriate drivers installed, and other applications detect pen pressure (Krita, for instance). Do Chrome and Firefox not support graphics tablets properly yet, or am I simply doing something wrong?
To answer your question: > Do Chrome and Firefox not support graphics tablets properly yet, or am I simply doing something wrong? No, you're not doing anything wrong. Most modern browsers support Pointer Events. I have found that (like everything else browser based) the degree of "support" can vary. This begs the quesiton, "how do we avoid the browser incompatibility nonsense?" For this particular case, I'd recommend Pressure.js. To see it in action (and test it with your device of choice), check out the Pressure.js examples.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "javascript, pointer events, wacom" }
Denseness of a preimage. Continous and surjective function Let $F:\mathbb{R^2} \to \mathbb{R}$ surjective and continuous on $\mathbb{R^2} $. Let $A\subset \mathbb{R}$, where $A$ is a dense set on $\mathbb{R}$. Is $F^{-1}(A)$ a dense set on $\mathbb{R^2}$ ?
Let $F(x,y)=xy$ if $x>0$ and $F(x,y)=0$ if $x \leq 0$. Let $A$ be any dense set in $\mathbb R$ which does not contain $0$, say non-zero rationals. Then $F^{-1}(A)$ does not intersect $\\{(x,y): x \leq 0\\}$ so it is not dense.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "calculus, real analysis" }
Do I always need to move Database queries from the UI thread to a separate thread? This question comes from an issue I am having, or really confusion on something. So its frowned upon to query databases on the UI thread. But my issue is, what if what appears on the screen relies on what the result is. Should you still run it in the background, or should you halt the screens output until you know the info you need from the database?
The way you should set it up is to use an `AsyncTask` to query the database, using the `doInBackground` method. Then use the `onPostExecute` method to update the UI. You can't update the UI on any other thread than the main thread. Hope that makes sense. If not, here are a couple articles that might help: < < Best of luck!
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "android, sqlite, background" }
$\cos(x)$ domain and range I'd like to refer the following answer: < @robjohn claims that: $$\cos(x):\left[\frac1{\sqrt2},\frac\pi4\right]\mapsto\left[\frac1{\sqrt2},\frac\pi4\right]$$ $\pi\over 4$ is $a_1$ but where does $1\over \sqrt(2)$ came from? **Update:** My actual question is: Given $a_1 = {\pi \over 4}$, $a_n = \cos(a_{n-1})$ Why does the range of this recurrence is $\left[\frac1{\sqrt2},\frac\pi4\right]$ Thanks.
$\dfrac{1}{\sqrt{2}}$ is $\cos\left(\dfrac{\pi}{4}\right)$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus, real analysis, functions, trigonometry" }
Creating a basic file server for video editing on a limited budget? I have a friend who fried an external 1TB HD (connected to a Mac) which was used to store video files that they were editing. Are there any specifications that would describe how to create a basic file server on a limited budget? My thought would be to use a old PC tower case and add in some sort of basic RAID controller with a series of harddrives.
If you're just worried about problems from wearing out your disk again, you can get a plain old external disk enclosure for around $50 that supports 2 mirrored disks (disks not included). This protects you against a single disk failure. * * * **Update to answer the comment:** * NewEgg * Tiger-Direct * Amazon * CDW The key thing you're looking for here is support for RAID 1. I couldn't image ever buying a single disk enclosure any more, unless you're really concerned about portability or have a separate real backup solution (RAID 1 is not a real backup). You can also search for a NAS (Network Attached Storage) device. These will come with disks and are likely easier to set up.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "video, raid, video editing, file server" }
Canon 5D mk IV how short of a battery life is expected? I had the 5D mk III and its battery life was incredible. I'd leave it around for a couple weeks between hikes or events and it would still have juice for yet another event. I'm talking casual events here, not professional - birthdays, hiking, museums etc. 800 shots per battery charge or so, almost regardless how long it's been since charge. I bought the 5D mk IV and with all its new features - GPS, touchscreen, WiFi... the battery is empty way faster than what I'm used to. A hike today with GPS on, WiFi off, 3 hours - the first battery was empty after ~230 shots taken intermittently in groups of 5-10. The GPS update rate was 5min and I was letting the camera auto-sleep after 1 min with the GPS remaining on. The cost of GPS is that I have to carry 3 batteries for shoots that took 1 on the 5D mk III. My question is: **Do you have any other basis for comparison, does this power consumption rate sound expected and acceptable**?
> Do you have any other basis for comparison, does this power consumption rate sound expected and acceptable? I see similar results on the 6D: GPS uses a lot of battery power. It also uses battery even when the camera is otherwise idle. Turning off both GPS and WiFi will give you significantly improved battery life. That doesn't mean that GPS isn't still a useful feature; you just have to decide for yourself when to use it. The same is true for cell phones: you can often get much better battery life by turning off the GPS feature.
stackexchange-photo
{ "answer_score": 8, "question_score": 3, "tags": "canon, canon 5d mark iii, battery drain" }
Convert to Arrow Function I'm learning Typescript. I want to convert this to an arrow function: function isRandomNumberEven(): boolean { return Math.round(Math.random() * 100) % 2 === 0; } I would convert it this way, but what do you do with the `boolean` return value? const isRandomNumberEven = () => { return Math.round(Math.random() * 100) % 2 === 0; }
TS will infer the return type automatically as boolean. but also if you want then do this way const isRandomNumberEven = ():boolean => { return Math.round(Math.random() * 100) % 2 === 0; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "typescript" }
Help identifying horror short story collection with werewolf story about a boy who becomes werewolf to avenge his slain puppies I read this collection in 1980 or 1981 (unsure how old it was at the time). I checked it out of a public library in the armpit town of Stead, Nevada. Anyway, in the story, some asshole's dogs chase down a boy who's cradling his two small puppies. I think the boy climbs a tree but the puppies fall from his jacket and are mauled by the dogs. Later, the boy somehow becomes a werewolf and sneaks out at night to kill the two dogs. But then the boy forgets why he became a werewolf in the first place and now he's just a werewolf. There was even an ILLUSTRATION, a creepy one, the head of wolf on the body of a full clothed boy. Like a dressed wolf walking around on two legs. Would love to figure out what book/story this is from.
_**Werewolf Boy**_ by Nic Andersson, originally published in _Monster Tales: Vampires, Werewolves and Things_ (1973). The story was asked about and identified on this page: > In the first short story, a boy is distraught when a nobleman’s hunting dogs savagely attack and kill his puppy. Seeking revenge, he goes to a witch or warlock (don’t remember the gender) who gives him what he wants: the ability to transform into a creature that can kill hunting dogs…a werewolf. The werewolf boy then succeeds in getting his revenge by killing the dogs. To his dismay, however, the sorcerer refuses to change him back into a normal boy until he obtains revenge for the sorcerer…by killing the nobleman. You can also view some illustrations from the book on this page. ![enter image description here](
stackexchange-scifi
{ "answer_score": 6, "question_score": 7, "tags": "story identification, werewolf, anthology book" }
Custom Tomcat Valve contained in web app WAR file I'm looking to implement a custom Valve and configuring it using META-INF/context.xml. At the moment though, when context.xml is parsed during deployment, Tomcat (6.0.32) dies with a ClassNotFoundException on my custom Valve implementation. I'm under the impression that I'm running into a class loading context issue and I'm not 100% sure I understand it. Is my class not found because it is located in the WEB-INF/classes file and the Context level class loader is unable to locate the class because of the hierarchy? Thanks in advance.
You can not load `Valve`s from inside the webapp class loader. If you look at < it shows the available class loaders. You must use one of the Bootstrap, System or Common classloaders because `Valve` definitions are processed BEFORE the individual webapp classloaders are created: the Context has to be processed before the webapp is available. Package your Valve in a jar by itself and copy it into the `$CATALINA_HOME/lib` folder and you should be all set.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 6, "tags": "tomcat6, classloader, catalina, context.xml, tomcat valve" }
Accessing Fragment objects from parent Activity I have an ActionBarActivity that has a ViewPager with two Fragments and tabs created with ActionBar from the support library. My ActionBarActivity has also two buttons: cancel and save. When the save button is pressed, I need to get data from both of my Fragments. How do I do this? This data is stored fetched from the layout and stored in local variables in the Fragments.
You should be able get access to your fragments by use of `FragmentManager` by id or tag. `getFragmentManager().findFragmentById()` or `getFragmentManager().findFragmentByTag()`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, android, android fragments, android activity" }
Unable to compare and manage timedelta objects I have following stub of code: timeA = datetime.strptime(dateTimeStringA, "%Y-%b-%d %H:%M:%S.%f %Z") least_time=timeA-timeA #Just to initialize the variable as timedelta object most_time=least_time timeB = datetime.strptime(dateTimeStringB, "%Y-%b-%d %H:%M:%S.%f %Z") timeBA = timeB-timeA ... print("timeBA",timeBA) #0:00:00.919640 print("least_time",least_time) #0:00:00 print("most_time",least_time) #0:00:00 if timeBA < least_time: least_time = timeBA if timeBA > most_time: most_time = timeBA print("timeBA",timeBA) #0:00:00.919640 print("least_time",least_time) #0:00:00 print("most_time",least_time) #0:00:00 Now in last I am printing three objects of same type, one is printed with microseconds, other two are not. And hence I am unable to see if my conditional assignments to these variables are working or not.
The microseconds are not printed when they are zero. So `0:00:00` means `0:00:00.000000`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x, python datetime" }
How to export/import Netbeans templates I am running Netbeans 7.0.1 under OS X and have created a number of templates using Tools > Templates. All my Templates are created under a new folder within the Templates folder list. I would now like to export the Templates and share them with other members of my team. How do I go about exporting them and then allowing my teammates to import them into their Netbean installs? Note: I've located the templates under my ~/.netbeans directory, but was hoping the IDE would facilitate import/export so folks don't have to go around copying folders in the file system.
I have just tested on my WinXP with Netbeans 7.0.1 and 7.1, so not 100% sure if it will work on OS X. Open your Netbeans 7.0.1 and go to `Tools -> Options` and in the new windows left lower corner `Export`. In this window expand `Editor` by clicking `+`. In the opened tree you only have to activate the checkbox in front of `Code Templates`, fill in a target file and there you are with your ready to import Templatesfile. Your team members can import them by clicking `Import` in `Tools -> Options`. Hope this will help you and your members. !enter image description here
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 9, "tags": "templates, netbeans, import, export" }
What does the variable $v$ in characteristic function of a random variable signify? The characteristic function of a random variable $X$ is given as: $$E(e^{jvX}) = \int _{-\infty} ^{\infty} e^{jvx} p(x) dx $$ This is interpreted as either mean of function $e^{jvx}$ or fourier transform of pdf $p(x)$. I know that $x$ represents random variable, but what does $v$ represents? What is its physical significance?
For a heuristic (or "physical") interpretation consider the following "real version" of the characteristic function instead: $$E_X(\omega):=\int_{-\infty}^\infty \cos(\omega x) p(x)\ dx\ .$$ Without the factor $\cos(\omega x)$ all values $x$ that the random variable $X$ can take are "equally important". Introducing this factor modulates this importance with frequency $\omega$. If it so happens that $X$ tends to prefer values which are spaced with period ${2\pi\over\omega_0}$ for some $\omega_0$ then this will show up in $|E_X(\omega_0)|$ becoming large. In this way $\omega$ (the $v$ in your question) can be considered as a "sensor setting" chosen to investigate whether the given PDF $p$ has some inbuilt periodicity at frequency $\omega$. The Fourier inversion theorem guarantees that the collection of all sensor readings $E_X(\omega)$ $(\omega\in{\mathbb R})$ is sufficient to reproduce $p$ as a function of $x$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability" }
Writing an equation in a specific form $y^2+a y+b=x^3+c x^2+d x$ I am trying to analyze the following equation: $$\alpha y^2+\beta y=\gamma x^3+\Delta x^2+\kappa x+\delta\tag1$$ Where all the coefficients $\alpha,\beta,\gamma,\Delta,\kappa,\delta$ are integers. $\beta,\Delta,\kappa,\delta$ can be equal to zero. And $\alpha,\gamma$ will be bigger or less than zero. > Now, how can I write equation $(1)$ into the following form: $$y^2+a y+b=x^3+c x^2+d x\tag2$$ Where all the coefficients $a,b,c,d$ all **have** to be integers.
Multiply the equation by $\alpha^3 \gamma^2$ \begin{eqnarray*} \alpha^4 \gamma^2 y^2+\alpha^3 \gamma^2 \beta y - \alpha^3 \gamma^2 \delta=\alpha^3 \gamma^3 x^3+\alpha^3 \gamma^2 \Delta x^2+ \alpha^3 \gamma^2 \kappa x. \end{eqnarray*} Now let $Y= \alpha^2 \gamma y$ and $X=\alpha \gamma x$ \begin{eqnarray*} Y^2+\alpha \gamma \beta Y - \alpha^3 \gamma^2 \delta=X^3+\alpha \Delta X^2+ \alpha^2 \gamma \kappa X. \end{eqnarray*}
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "number theory, elementary number theory, polynomials, real numbers, integers" }
Comparing two strings using memcmp in c Consider the following code: char str1[] = "Hello"; char str2[] = "Hello\0\0\0l\0o"; int x; x=memcmp(str1,str2,sizeof(str2)); printf("%d",x); When I run it, it shows the o/p as: 1 Can you explain the reason for this. I learned that each byte in both strings are compared and returns accordingly. But I am not clear about what happens at the end.
Your program invokes undefined behavior. `sizeof(str2)` is larger than `sizeof(str1)`. By using that as the last argument to `memcmp`, you are accessing memory that you are not supposed to. That is cause for undefined behavior. Hence, the output can be anything. It's pointless trying to make sense of it.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "c" }
Modify relationship association I'm working on a micro-social-network and I have two different account types, User can either be Profile or Page. class User < ActiveRecord::Base has_one :profile has_one :page end Now, when I want to show the User name, I do current_user.profile.name, but if the User is a "Page", I get an error, obviously. So I tried this private def current_user if session[:user_id] @current_user = User.find(session[:user_id]) if @current_user.account_type == 'profile' @current_user.profile = @current_user.page end end end But it's not working. Any help is appreciated greatly. Thanks a lot!
I am not really sure what you are asking, but you can add a method to `User` model to handle this: class User < ActiveRecord::Base has_one :profile has_one :page def name if self.account_type == 'profile' return self.profile.name return <whatever for page> end end **Edit:** For multiple fields, why not use a method for `User`: class User < ActiveRecord::Base # other code removed def get_info(method, *args) if self.account_type == 'profile' return self.profile.send(method, *args) end self.page.send(method, *args) end end So to use this, say we have `a = User.find(:id)` with any `id`. Then, you can do, assuming `a`'s `account_type` is `profile`: `a.get_info(:name) # => a.profile.name`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails 3" }
How do I get my accordion to load with all the menus closed? I'm trying to follow the example here < I have placed a mockup here < Loading behavior is strange. It shows Menu1 then collapses it then shows Menu2 and Menu3. I would like everything to open collapsed. I have tried the following without success $('#accordion').collapse({hide: true})
Replacing $(".collapse").collapse(); $('#accordion').collapse({hide: true}) with: $('#collapseOne').collapse("hide"); should do the trick. I think the first one is toggled on by default and this one line switches it off.
stackexchange-stackoverflow
{ "answer_score": 29, "question_score": 62, "tags": "javascript, html, twitter bootstrap, jquery events" }
jquery $.getJSON, retrieving servlet parameters upon process method Is this the correct way to set parameters upon a servlet request (tags, tagmode, format)? $.getJSON('....Servlet', { tags: "cat", tagmode: "any", format: "json" }, function(data) { }); And can I retrieve the parameters like this (Servlet class extending HttpServlet | inside process method)? request.getParameter("tags"); request.getParameter("tagmode"); request.getParameter("format"); I haven't found the right terms to search google or stackoverflow. So if anyone has a proper answer or documentation to this issue, then just let me know.
Yes, that should be all correct. And BTW, you could have answered your own question if you had just written the code and tried it. ;o)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, jquery, tomcat" }
What is the minimal landing area required for an EC135 air medical services helicopter? The Netherlands has a few Eurocopter EC135s for air medical services. (See _Wikipedia_.) How much clear landing space is required (either theoretically, practically or regulatory) for these?
Theoretically the diameter of the rotor plus some room for the tail is sufficient. If it fits, it fits. Practically, a bit of room for manoeuvring is required. Also special attention to the generated turbulence is needed in cramped spaces. Regulatory I don't know the exact size required for the EC135 operated as air ambulance in the Netherlands. But I do know that the Dutch police helicopters are allowed to land on an area with a diameter of 1.5 $\times$ LOA (length over all) during daytime operations. They hit a lamp mast once which resulted in this investigation (in Dutch - or English text-only translation) by the Onderzoeksraad (Dutch Safety Board). Page 5 and 6 show some of the regulations in force at the time (2008). ![](
stackexchange-aviation
{ "answer_score": 5, "question_score": 11, "tags": "landing, helicopter, emergency services, netherlands" }
Python return list class alexicon(object): def __init__(self): self.directions = ['north', 'south', 'west', 'east', 'up', 'down'] self.items = [] def scan(self, words): self.word = words.split() # direction self.direction_word = [i for i in self.word if i in self.directions] self.direction_list = [] for x in self.direction_word: self.direction_list.append(('direction', '%s' %(x)) ) if self.direction_list != []: self.items.extend(self.direction_list) else: pass return self.items lexicon = alexicon() result = lexicon.scan('north') print result Why print result get a 'None'? How can I get the items list? But if I print the lexicon.items I can get the right list(There are elements in that list).
You need to change the indentations: class alexicon(object): def __init__(self): self.directions = ['north', 'south', 'west', 'east', 'up', 'down'] self.items = [] def scan(self, words): self.word = words.split() # direction self.direction_word = [i for i in self.word if i in self.directions] self.direction_list = [] for x in self.direction_word: self.direction_list.append(('direction', '%s' %(x)) ) if self.direction_list != []: self.items.extend(self.direction_list) else: pass return(self.items) lexicon = alexicon() result = lexicon.scan('north') print(result) Output: [('direction', 'north')]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, python 3.x, python 2.7, class, object" }
why Lapack routine dgesv doesn't solve this? Suppose I have the following 3 by 3 matrix: p<-3 X<-matrix(1/p,p,p) \--$\pmb X$ is just a $p$ by $p$ matrix where every entry is $1/p$. Now I want to solve the system $$\pmb a\pmb X=\pmb 1_p$$ where $\pmb 1_p$ is a vector of 1 of length $p$. I know $\pmb 1_p$ is the solution to such a system, but when I do, in `R`, solve(X,rep(1,p)) I get Error in solve.default(X, rep(1, p)) : Lapack routine dgesv: system is exactly singular: U[2,2] = 0 instead of $\pmb 1_p$. My question is why
Your matrix does not have an inverse, which is why `dgesv` returns an error.
stackexchange-scicomp
{ "answer_score": 5, "question_score": 2, "tags": "r, matrix factorization" }
Seaborn module 'histplot' not found I am running seaborn on pycharm. However when I'm running the `histplot` module, it says there are no module in that name. However, the seaborn version is the latest (0.11.0) and the python version I'm using is `3.6.2`. Where is the error?
I tried to reproduce the error with seaborn version `0.10.0`and `0.11.0`. I believe you are not using `0.11.0` as the `histplot` is a method under the documentation of version `0.11.0`. Check the version using: import seaborn as sns print(sns.__version__) Code from @StupidWolf produces the following results with `0.11.0`. : ![enter image description here]( I could reproduce the error in `0.10.0`. Therefore, I would suggest to reinstall/upgrade seaborn with the following: pip install seaborn==0.11.0
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, python 3.x, seaborn" }
how to conditionally show/hide link in DetailsView ItemTemplate I'm new to ASP.NET, and I'm trying to figure out how to only show a chunk of code in the .aspx file if a value is not null or whitespace. Here's what I have, within a `DetailsView`: <asp:TemplateField HeaderText="Phone"> <EditItemTemplate> <asp:TextBox runat="server" ID="txtPhone" Text='<%# Bind("Phone") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <a href="tel:<%# Eval("Phone") %>"> <i class="icon-phone"></i> <%# Eval("Phone") %> </a> </ItemTemplate> </asp:TemplateField> I want to conditionally hide the whole `a` tag if `Eval("Phone")` is null or whitespace. I would prefer to do this all in the markup, as opposed to doing something in the code-behind.
David's answer pointed me in the right direction: <asp:HyperLink runat="server" NavigateUrl='tel:<%# Eval("Phone") %>' Visible='<%# !string.IsNullOrWhiteSpace(Eval("Phone").ToString()) %>'> <i class="icon-phone"></i> <%# Eval("Phone") %> </asp:HyperLink>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, asp.net, detailsview" }
How to access Library, File, and Field descriptions in DB2? I would like to write a query that uses the IBM DB2 system tables (ex. SYSIBM) to pull a query that exports the following: LIBRARY_NAME, LIBRARY_DESC, FILE_NAME, FILE_DESC, FIELD_NAME, FIELD_DESC I can access the descriptions via the UI, but wanted to generate a dynamic query. Thanks.
Along with `SYSTABLES` and `SYSCOLUMNS`, there is also a `SYSSCHEMAS` which appears to contain the data you need. Please note that accessing this information through `QSYS2` will restrict rows returned to those objects with which you have _some_ access - the `SYSIBM` schema appears to disregard this (check the reference - for V6R1 it's about page 1267). You also shouldn't need to retrieve this with a dynamic query - static with host variables (if necessary) will work just fine.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "db2" }
PHP Export to CSV from SQL Server I need some help to export from a SQL Server query to csv. I have the query but when I'm fetching the result I need to put it on an variable and export it. This is what I have: $query = 'select * from sqlserver_table'; $result = odbc_exec($conMsSql,$query); // this gives me the columns while(odbc_fetch_row($result)){ $field1 = odbc_result($result, 1); $field2 = odbc_result($result, 2); $field3 = odbc_result($result, 3); $field4 = odbc_result($result, 4); $field5 = odbc_result($result, 5); $field6 = odbc_result($result, 6); $field7 = odbc_result($result, 7); } // this is to export $file = fopen("export.csv","w"); foreach ($list as $line){ // how can I put the result in this variable ($list)? fputcsv($file,explode(',',$line)); } fclose($file);
You'd want something like this: $csvName = "export.csv" $sqlQuery = 'select * from sqlserver_table'; $sqlRresult = odbc_exec($conMsSql, $sql); $fp = fopen(csvName , 'w'); while ($export = odbc_fetch_array($sqlRresult)) { if (!isset($headings)) { $headings = array_keys($export); fputcsv($fp, $headings, ',', '"'); } fputcsv($fp, $export, ',', '"'); } fclose($fp);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, sql server, csv, odbc" }
How to "simplify" UIImagePickerController I am using UIImagePickerController to take photo, there are two steps involved, "Take photo" and "Use photo". Is there any way to override the behavior, merge these two action in one? Say "Take and use photo". Thanks.
There is no way in the current SDK to do this, you should file a bug requesting the feature. There are some published examples where people crawl around in the view hierarchy to programmatically read surfaces and trigger UI elements, but those are complex to do, can have weird visual artifacts that cause support issues, and are likely to break with firmware updates.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 6, "tags": "ios, iphone, objective c, cocoa touch, uiimagepickercontroller" }
How to translate IDA pseudocode to C/C++ code? I am trying to reverse engineer a packet protocol and I was abled to find a subroutine which is likely to be an encryption function. I do not know much about cryptography but it looked like a CBC encryption. Here's the pseudocode I got from IDA: < and here is a part from the original subroutine: also here's a part from where the subroutine is called: . Is it possible to translate this pseudocode to C code without further reverse engineering ? If so how should I do it ?
This specific pseudocode is actually regular C code because it doesn't access global variables and stack. You'll probably need to add some typedefs for basic types. Please note that this code should be compiled as 32 bit code (or any other where sizeof int is equal to sizeof of pointer for your specific system) to avoid problems with pointer sizes.
stackexchange-reverseengineering
{ "answer_score": 2, "question_score": -1, "tags": "ida, packet" }
Icon as Integer and Integer to Icon I need to save an `Icon` as an `int` and later convert it back to an `Icon`. I thought I can achieve this with the icon's `codePoint`; `IconData` takes a parameter `codePoint` in the constructor but the following does not work: `Icon(IconData(Icons.person.codePoint))` The icon is some Chinese sign, not the actual person icon.
You also need to pass back in the font, for example: Icon(IconData(Icons.person.codePoint, fontFamily: 'MaterialIcons'));
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "flutter" }
In Noether's theorem, what is a "classical solution of the equations of motion"? I'm reading a book which states that: > for each generator of a global symmetry transformation, there is a current $j^{\mu}_{a}$ which, _when evaluated on a classical solution of the equations of motion $\phi_{cl}$_ , is conserved. I.e. $\partial_{\mu}j^{\mu}_{a}\vert_{\phi=\phi_{cl}} =0 $ I get the general principle, but I'm uncertain about the bit I have made _italics_. Can anyone shed some light on this?
1) The word _classical_ in this context means $\hbar=0$. 2) In the context of an action principle, the Euler-Lagrange equations $$ \frac{\delta S}{\delta\phi^{\alpha}}~\approx~0 $$ are often referred to as the (classical) equations of motion (eom), cf. comment by Jia Yiyang. Here the $\approx$ symbol means equality modulo eom. Let on-shell (off-shell) refer to whether eom are satisfied (not necessarily satisfied), respectively. 3) In the context of a global continuous (off-shell) symmetry of an action, Noether's (first) theorem implies an off-shell Noether identity $$d_{\mu} J^{\mu} ~\equiv~ - \frac{\delta S}{\delta\phi^{\alpha}} Y_0^{\alpha},$$ where $J^{\mu}$ is the full Noether current, and $Y_0^{\alpha}$ is a (vertical) symmetry generator. This leads to an on-shell conservation law $$d_{\mu} J^{\mu}~\approx~0.$$
stackexchange-physics
{ "answer_score": 1, "question_score": 1, "tags": "lagrangian formalism, field theory, noethers theorem" }
How to change a href value if certain string is found How to change a href value if a certain string is found $string ='<a href=" if facebook is found on the href, replace to just facebook.com
Use this code, $string ='<a href=" echo preg_replace('# ' $string ); Thanks Amit
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php" }
CNTK Asymmetric padding warning When creating a model in CNTK, with a convolutional layer, I get the following warning: > WARNING: Detected asymmetric padding issue with even kernel size and lowerPad (9) < higherPad (10) (i=2), cuDNN will not be able to produce correct result. Switch to reference engine (VERY SLOW). I have tried increasing the kernel size from 4x4 to 5x5 so the kernel size is not even without result. I have also tried adjusting lowerPad, upperPad (the paramater named in the docs), and higherPad (the parameter listed in the message). Setting autoPadding=false does not affect this message. Is it just a warning that I should ignore? The VERY SLOW part concerns me, as my models are already quite slow.
I figured this out if anyone else is interested in the answer. I stated in the question that I tried setting "autopadding=false". This is the incorrect format for the autopadding parameter; it must actually be a set of boolean values, with the value corresponding to the InputChannels dimension being false. So the correct form of the parameter would be "autopadding=(true:true:false)", and everything works correctly.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "cntk" }
$\sigma$-additivity Can someone explain me in simple words what $\sigma$-additivity is? For example, if we have a probability space ($\Omega$,$\mathcal{F}$,P), what it means that the application $$ B \mapsto P(A\cap B) $$ is $\sigma$-additive over $\mathcal{F}$? I found it for the first time in probability theory and I don't understand the implication that it has in the theory.
A map $m\colon \mathcal F\to \Bbb R_{\geq 0}$ is $\sigma$-additive if for each sequence $\\{B_n\\}\subset \mathcal F$ of pairwise disjoint measurable sets, we have $$m\left(\bigcup_{n=1}^{+\infty}B_n\right)=\sum_{n=1}^{+\infty}m(B_n).$$ This is the formal definition. This means that the "measure" of a disjoint union is the sum of the "measures" of each elements of the union. The letter $\sigma$ expresses an idea of countability, as we can work with maps finitely-additive. It allows us to work with sequences of sets.
stackexchange-math
{ "answer_score": 0, "question_score": 3, "tags": "probability" }
How do I know the "default include directories", "default link directories" and "default link libraries" of gcc, g++/c++ in Ubuntu 11.04? For the following 3 compile cases : gcc -o helloc hello.c (1) g++ -o hellocpp hello.cpp (2) c++ -o hellocpp hello.cpp (3) how do I know the "default include directories", "default link directories" and "default link libraries" in each case ? I am using gcc 4.5.2 in a 32 bit Ubuntu 11.04 environment. For case (1), is gcc using the standard C libraries or the GNU C libraries ? Is there difference between the two C libraries ? Comparing cases (2) and (3), is there any difference in the "default link libraries" used by the compiler ? Are they using the standard C++ libraries or the GNU C++ libraries ? What is the difference between the two C++ libraries ? Thanks in advance for any suggestion. Lawrence Tsang
Say `gcc -v`, or `g++ -v` to print out verbose information about the environment. E.g. for me this says: #include <...> search starts here: /usr/local/lib/gcc/i686-pc-linux-gnu/4.6.2/../../../../include/c++/4.6.2 /usr/local/lib/gcc/i686-pc-linux-gnu/4.6.2/../../../../include/c++/4.6.2/i686-pc-linux-gnu /usr/local/lib/gcc/i686-pc-linux-gnu/4.6.2/../../../../include/c++/4.6.2/backward /usr/local/lib/gcc/i686-pc-linux-gnu/4.6.2/include /usr/local/include /usr/local/lib/gcc/i686-pc-linux-gnu/4.6.2/include-fixed /usr/include Also try `gcc -dumpspecs` to see details about the invoked tools in the tool chain.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 12, "tags": "c++, gcc" }
How do I check the page name in an if statement? I have two pages (default.aspx and view.aspx) and want to add a class to an anchor tag depending on page name. The code would be something like the following, but I'm not sure what to put for the condition part of the if statement when I have pagename="default.aspx". <li><a href="make.aspx" <% if(pagename="default.aspx") { %>class="open"<% } %>><i class="icon-comment-alt"></i> Make Request</a> <li><a href="view=.aspx" <% if(pagename="view.aspx") { %>class="open"<% } %>>><i class="icon-folder-open-alt"></i> View Requests</a></li>
<% string pagename = new FileInfo(this.Request.Url.LocalPath).Name; %> Something like this preceding the `if` statements in each page should generally work. I wouldn't recommend using a lot of inline C# code in your markup files with maintainability and separation of concerns in mind, but it can work. For more information and qualifications on getting the current page name as outlined above, check out a related SO question.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, asp.net" }
how to spread small image file in background and it should scroll with other elements this is my css code the image file (.png) 40*40px and it is a small file i want to spread it all over the body (background). i did with 'fixed' thing it worked, but when i scroll it doesn't move with other elements body{ background:url('short.png') fixed; } then i tried with repeat-x or repeat-y but i don't know how to implement both thing in body tag body{ background:url('short.png') repeat-x; } remember my image file is 40* 40px i want to apply everywhere and when i scroll it should move with other tags which is opposite to 'fixed' thing.
background:url('short.png') 0 0 repeat;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "html, css, image, tags" }
Windows 10 camera window opens without initiating Specs: Intel Atom processor x64 SoC inbuilt with RAM DDR3 2GB, eMMC 32 GB and intel HD graphics Windows 10pro x86 with original OEM license. Windows is updated up to 20H2. Problem: The computer opens camera window without me clicking. I have turned off my internet also to see if someone is remotely accessing my netbook but then also sometimes, the camera window show up with my camera turned on. I searched for jpg and mov/mpg but no photos or videos of myself is there is this netbook. Reason for asking the question: I am scared if someone has trying to see what I’m doing. I have searched some bad sites and after that this happened. I have not downloaded any softwares; just some videos. There is no cracked apps too. The only non Microsoft app is the Apache Open office. Question: Is someone watching me or is it any problem with Windows? How can I know if someone is watching me? Or should I reset my PC?
If this keeps happening even after reset and with no malware on your device, it means internal Windows app is doing it. While there's low risk of privacy breach (they're not likely sending anything to anyone), it's still something better avoided. Someone in a Microsoft forum thread said that in their case it was WavesSysSvc process: > I found out the application using my camera was WavesSysSvc. For some reason it was using my camera at those moments, so I ended it and disable it's startup. So far so good. Might be your case as well, worth checking.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "windows 10, camera" }
Last Day of Month - DataFrame Good evening, I have the following data in Pandas DataFrame: Date | DT_INI ---|--- 2021-03-01 | 01032021 2021-02-06 | 06022021 I wish to convert any of these 2 columns to get the last day of its data month. ![enter image description here]( Already tried lots of function.. but still nothing.
You can use the `pd.offset.MonthEnd(n=0)` as offset to add on the base dates to get the month-end dates, as follows: df['Date_Month_End'] = df['Date'] + pd.offsets.MonthEnd(n=0) print(df) Date DT_INI Date_Month_End 0 2021-03-01 1032021 2021-03-31 1 2021-02-06 6022021 2021-02-28 Parameter `n=0` is specified so that Date of `2021-03-31` will not roll forward to `2021-04-30`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, pandas, datetime" }
DNS record, paths and port > **Possible Duplicate:** > How to use DNS to redirect domain to specific port on my web server I have a domain xyz.com and a web application running at < When the user enters the URL xyz.com and www.xyz.com, I want that the page on < is displayed in the browser. What DNS records should I add? Update: 1) I changed the port to 80. 2) Thanks all for the help! Now I can reach the application via URLs www.xyz.com/pcc xyz.com/pcc , i. e. xyz.com and www.xyz.com point to AAA.BBB.CCC.DDD. One last thing remains: I want xyz.com to point to the pcc directory (as well as www.xyz.com). How can I do that?
You need to create an A record for xyz.com that points to AAA.BBB.CCC.DDD. You need to create a CNAME record for www.xyz.com that points to xyz.com. By default HTTP uses port 80. If you are using apache then you should be able to use mod_proxy to shift the port.
stackexchange-serverfault
{ "answer_score": 1, "question_score": -2, "tags": "domain name system, port" }
.NET How can I change position of a control in code behind? <Ellipse Canvas.Left="37" Canvas.Top="260"> I want to define the position of an ellipse in code behind relative to a Canvas.
Like this: Canvas.SetLeft(someControl, 42);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": ".net, wpf" }
Getting Android screen size type during runtime (drawable-small, drawable-normal, etc) As explained in Developer documentation Android supports setting different images for different sizes of the screen by putting them in separate folders (drawable-small, drawable-normal, drawable-large and drawable-xlarge). Is it possible to get the "type" of the screen that Android is using to load the resources during runtime? I need to log this variable for error reporting and it would help a lot if I can tell which drawable type folder system is using (similarly to how I can tell if it is ldpi, mdpi, hdpi or xhdpi by querying getResources().getDisplayMetrics().density).
> Is it possible to get the "type" of the screen that Android is using to load the resources during runtime? `getResources().getConfiguration()` gives you a `Configuration` object, and from there you can examine the `screenLayout` field. This tells you size, long/not-long, and direction (LTR or RTL).
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "android, android resources" }
Group a List<object[]> I have a question that's similar to yesterday's question. I've got this List<object[]> List<object[]> olst = new List<object[]>(); olst.Add(new object[] { "AA1", "X", 1, 3.50 }); olst.Add(new object[] { "AA2", "Y", 2, 5.20 }); olst.Add(new object[] { "AA2", "Y", 1, 3.50 }); olst.Add(new object[] { "AA1", "X", 1, 3.20 }); olst.Add(new object[] { "AA1", "Y", 2, 5.30 }); I need to produce List<object[]> to hold this: "AA1", "X", 2, 6.70 "AA2", "Y", 3, 8.70 "AA1", "Y", 2, 5.30 In other words, I need to group olst by the **1st** and **2nd** elements of each object[] and sum **3rd** and **4th**. I could use a for loop, but I was hoping someone could help me using lambda expressions and/or linq to accomplish this.
You need to group by an anonymous type, then sum the third and fourth columns: List<object[]> grouped = olst .GroupBy(o => new { Prop1 = o[0].ToString(), Prop2 = o[1].ToString() }) .Select(o => new object[] { o.Key.Prop1, o.Key.Prop2, o.Sum(x => (int)x[2]), o.Sum(x => (double)x[3]) }) .ToList();
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "c#, linq, lambda" }
Synonym for my prefix is master * Synonym for my prefix is master. * Synonym for my suffix is folder. * Synonym for my infix is about. * Synonym for my whole is shape.
> PROFILE > PRO or PROF is a master > FILE is a folder > OF Is about > PROFILE is a shape
stackexchange-puzzling
{ "answer_score": 5, "question_score": 4, "tags": "riddle, word" }
How to view the exact size of a file in Google Drive (e.g., expressed in bytes)? How to view the exact size of a file in Google Drive (e.g., expressed in bytes)? E.g., in the following I would like to know the exact file size, not rounded n KB: ![enter image description here]( ![enter image description here]( Link to the folder if you want to try: <
Apparently there are two different "detail views" in Google Drive. The one I showed in the question doesn't have the exact size, whereas the second one has it…: ![enter image description here]( ![enter image description here](
stackexchange-webapps
{ "answer_score": 3, "question_score": 2, "tags": "google drive" }
Upgrading wget on Ubuntu 16.04 server I'm trying to upgrade my copy of `wget` on the server. Currently its running: > 1.17.1-1ubuntu1.4 The problem is that I need **1.19** so I can get a new feature: < > My patch has been part of the changes released as Wget version 1.19.1, so now (if you run that version or newer) you can just write something like: > > wget --retry-on-http-error=503 ... We are having issues with a website giving 502 errors back when trying to request the images from them. Their tech guys are looking into it, but for the mean time I need a way to auto-retry the 502 files. This seems to fit the bill, but I can't seem to get it to upgrade. apt-get update apt-get install wget ...gives: Reading package lists... Done Building dependency tree Reading state information... Done wget is already the newest version (1.17.1-1ubuntu1.4). I'm not sure what else to try?
You don't necessarily need to go via the package manager, as long as you know which version goes where. The GNU wget source tarball + compilation instructions can be found here: < If this is your first time compiling software, try it on a separate computer or VM first - preferably one with the same OS version - so you know what to expect.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 1, "tags": "apt, ubuntu 16.04, wget" }
В каком числе ставить глагол? В каком числе нужно ставить глагол в данном случае: > После двух-трех попыток стало очевидно, что леска или удочка не (выдержит/выдержат). И почему так, а не иначе?
Тогда уж _леска или удилище_. Раз у вас "или", лучше написать "не выдержит". Сравните: _После двух-трех попыток стало очевидно, что леска и удилище не выдержат._
stackexchange-rus
{ "answer_score": 3, "question_score": 0, "tags": "согласование" }
an irreducible affine curve is normal if and only if it is nonsingular > An is normal if and only if it is nonsingular. This statement comes from Kemper, _A Course in Commutative Algebra_. He says to use Proposition 8.10 and Theorem 14.1. ![enter image description here]( **Theorem 14.1.** _A Noetherian local ring of dimension one is regular if and only if it is normal._ An irreducible affine curve is normal means that the coordinate ring $K[X]$ is normal. So, by the Proposition, for every $x$, the localization $K[X]_x$ is normal. How can I get that $K[X]_x$ is regular? Is that $K[X]_x$ is a local ring? Could someone tell me ?
An algebraic variety $X$ is regular if all of its local rings $O_{X,x}$ are regular local rings. The latter means that the maximal ideal $M_{X,x}$ of $O_{X,x}$ is generated by $\mathrm{dim}(O_{X,x})$ elements. Since regularity of a ring is stable under localization it suffices to require that the local rings $O_{X,x}$ in closed points of $X$ are regular. Regular local rings are normal - in fact they are factorial by a famous theorem due to Auslander and Buchsbaum. Now for a curve $X$ the dimension of every local ring $O_{X,x}$ in a closed point equals $1$. Hence if $x$ is regular $M_{X,x}$ must have one generator. Theorem 14.1 in combination with the mentioned normality yields the result.
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "ring theory, commutative algebra, affine varieties" }
Maintaining order of extracted patterns from strings in R I'm trying to extract a pattern from a string, but am having difficulty maintaining the order. Consider: library(stringr) string <- "A A A A C A B A" extract <- c("B","C") str_extract_all(string,extract) [[1]] [1] "B" [[2]] [1] "C" The output of this is a list; is it possible to return a vector that maintains the original ordering, ie that `"C"`precedes `"B"` in the string? I've tried many options of `gsub` with no luck. Thanks.
Try using the following regexp: str_extract_all(string,"[BC]") ## [[1]] ## [1] "C" "B" or more generally: str_extract_all(string, paste(extract, collapse = "|"))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "r, regex" }
iOS || Swift || how to convert date response String to expeced timestamp I have a `date` object whose type is `String`, and the value from backend response will be `2022-8-01T03:23:35.430+0000`, how can I convert it to the expected format like `Mon, 1 Aug 2022, 3:23 pm` Thanks in advance!
Use DateFormatter let dateString = "2022-8-01T03:23:35.430+0000" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX" let date = dateFormatter.date(from: dateString) print(date) // Date object /// Date to String let format = "EEE, d MMM YYYY, h:ss a" // format you need as a String let formatter = DateFormatter() formatter.dateFormat = format //By default AM/PM symbols are uppercased formatter.amSymbol = "am" formatter.pmSymbol = "pm" let label: String = formatter.string(from: date!) print(label) // "Mon, 1 Aug 2022, 3:23 pm"
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -7, "tags": "ios, swift" }
How do you group variables in Structured Text? How do you group variables in Structured Text? Say I have **n** global variables for lamps: lamp1 lamp2 lamp3 ... // and so on Then I have a button, and pressing it should set all variables to TRUE: IF buttonPressed Then lamp1 := TRUE; lamp2 := TRUE; lamp3 := TRUE; ... // and so on END_IF How can I group the lamps in a way to not to have to set every varriable to TRUE manually?
To set multiple variables at once, you would first have to collect the values you want to set in an array: VAR lamp1 : BOOL; lamp2 : BOOL; lamp3 : BOOL; lamps : ARRAY[1..3] OF BOOL := [lamp1, lamp2, lamp3]; END_VAR and then set the values in a for loop. FOR i := 1 TO 3 DO lamps[i] := TRUE; END_FOR ## Result ![enter image description here]( ## Function You can also define a custom function if you have to do it a lot: FUNCTION SetAllBools : BOOL VAR_IN_OUT bools : BOOL; END_VAR VAR_INPUT newValue : BOOL; END_VAR VAR i : INT; END_VAR which can then be used as `SetAllBool(lamps, TRUE);`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "codesys, structured text" }
an html tag for displaying html received from a specific url I created an API of sorts, that when you navigate to it, returns information in html. On my website, I would like to have the web page reach out to the API and display the information as part of the web page (sort of like a webpage reaches out for an img). What HTML tag would be best suited to achieving this result? I came across the and tags but not really sure which would be best. I am building this myself thus have full control over how the content is delivered back to the page. Is there specific pattern that is used for such "modular" sourcing of information? I could rewrite my website to - prior to serving the web page - reach out to the api and pull the info itself and then include the results in html but a) this would be more complex and require changes in several places b) will become really complex as the number of such api call results I would want to include increases.
You can use Iframe for this purpose and when you recieve html which you want to display , you can simply set html content in that iframe's ID : document.getElementById('myIframe').contentWindow.document.write("<html><body>Here is your html</body></html>"); Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, design patterns" }
How to efficiently operate on sub-arrays like calculating the determinants, inverse, I have to to multiple operations on sub-arrays like matrix inversions or building determinants. Since for-loops are not very fast in Python I wonder what is the best way to do this. import numpy as np n = 8 a = np.random.rand(3,3,n) b = np.empty(n) c = np.zeros_like(a) for i in range(n): b[i] = np.linalg.det(a[:,:,i]) c[:,:,i] = np.linalg.inv(a[:,:,i])
Those `numpy.linalg` functions would accept `n-dim` arrays as long as the last two axes are the ones that form the `2D` slices along which functions are intended to be operated upon. Hence, to solve our cases, permute axes to bring-up the axis of iteration as the first one, perform the required operation and if needed push-back that axis back to it's original place. Hence, we could get those outputs, like so - b = np.linalg.det(np.moveaxis(a,2,0)) c = np.moveaxis(np.linalg.inv(np.moveaxis(a,2,0)),0,2)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, function, numpy, sub array" }
What is node_modules directory in ember What is the usage of node_modules directory in ember? I could see this directory created accross my ember application. When does it get created and what is the significance? What harm if i delete this directory?
It's a directory for `npm`/`yarn`. It's created by running `npm install` or yarn. Theese commands install all dependecies specified in the `package.json` file into the `node_modules` directory. You need them to run any ember commands. If you delete the folder you can recreate it with `npm install`/`yarn`. It's not checked into source control.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ember.js, ember cli" }
MySQL updating records with condition Table A id | name | important | ----------------------- 1 Abe 0 2 Ann 1 3 John 1 4 Bill 0 I have a php array of id values $ids = [1, 4]; I want update table A setting important column equals 1 if id column value is in $ids array AND setting important column value equals 0 if not. So for the example, the table after update would be: id | name | important | ----------------------- 1 Abe 1 2 Ann 0 3 John 0 4 Bill 1 How to do? Thanks for any help!
Basically you need to run next query: UPDATE TableA SET important = (id IN (1,4)); Below php implementation of this: <?php $ids = [1,4]; //prepare SQL statement with plaseholders $placeholder = implode(',', array_pad([], count($ids) , '?')); $sql = "UPDATE TableA SET important = (id IN ($placeholder));"; // run update with ids $pdo->prepare($sql)->execute($ids); // Get updated data for check result $sth = $pdo->prepare("SELECT * FROM TableA"); $sth->execute(); print_r($sth->fetchAll()); And here you can test the code.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "php, mysql" }
Clarification on the Hausdorff property If $X$ is a Hausdorff space then for points $a,b \in X$ there are disjoint open sets $U$ and $V$ such that $a \in U$ and $b \in V$. So, take a set of points $\\{a_1, \ldots , a_n\\}$ and another point $x$. Then for each $a_i$ there are disjoint open sets $U_i$ and $V$ containing $a_i$ and $x$, respectively. My question is: is $V$ disjoint from all the $U_i$, or does this only hold pairwise? Are there conditions we can impose to guarantee an open set separating $x$ from all points in some given finite set?
Let $\\{a_1, ..., a_n\\}$ be a finite collection of points. Let $x$ be a point different from all the $a_i$'s. For each $i$, by being Hausdorff, there exists $U_i$ and $V_i$ such that $a_i \in U_i$, $x \in V_i$ and $U_i \cap V_i = \emptyset$. Then $V = \bigcap_{1 \leq i \leq n} V_i$ is an open set (being a finite intersection of open set) containing $x$ which is disjoint from all the $A_i$'s.
stackexchange-math
{ "answer_score": 8, "question_score": 5, "tags": "general topology" }
Find six triples of positive integers $(a, b, c)$ such that in $ \frac{9}{a} + \frac{a}{b} + \frac{b}{9} = c$. Solve for $a, b$ and $c$ in the following equation such that > Find six triples of positive integers (a, b, c) such that $$ \frac{9}{a} + \frac{a}{b} + \frac{b}{9} = c$$ I have tried various techniques with out any success.
I find $(9,9,3), (2,12,6), (162,4,41), (405,25,19), (18,36,5), (54,12,6)$ just by brute force search. I made an Excel sheet with $a$ down the first column, $b$ across the top row, computed the LHS and scanned for integers. Copy down/copy right is your friend. Added: extending the search with a Python program, I also find $(14,588,66), (378,588,66)$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "algebra precalculus" }
Java.Util.Set não adiciona novos elementos Na variavel loja ao tentar adicionar um novo elemento do tipo "Loja" ele sempre fica somente com um elemento e não adiciona um novo elemento. E nunca adiciona um novo. Segue os codigos: Metodo main: public static void main(String[] args) { Usuario usuario = new Usuario(); Set<Integer> idsLojas = new HashSet<>(); idsLojas.add(123); idsLojas.add(333); idsLojas.add(3333); Set<Loja> lojas = new HashSet<>(); for (Integer idLoja : idsLojas) { lojas.add(new Loja(idLoja)); } usuario.setLojas(lojas); System.out.println(usuario.getLojas().size()); } Construtor de loja: public Loja(Integer id) { this.setId(id); } O resultado sempre é 1, mesmo eu adicionando 3 valores.
Sobrescreva os métodos `equals()` e `hashcode()` da classe `Loja`. De preferência deixe o seu IDE criá-los por você. Quando ele lhe pedir por quais critérios especificar os métodos adicione o id da loja como critério. Leia mais aqui: Como definir a comparaçao de igualdade entre dois objectos presentes num ArrayList?
stackexchange-pt_stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "java" }
How to try until resolve (Promise in JavaScript) lately I have been facing a connection problem that makes the connection between my code and db unstable... TimeOut Error As you may have noticed, that create a connection request error, and I need a way to make my Promise keep trying until resolve. My code: var results = sqlQuery(sql) function sqlQuery (sql) { return new Promise((resolve, reject) => { sql.query(/*query*/, function (error, results, fields) { if (error) { console.log(error) reject(error) } resolve(results) }) }) } **IMPORTANT :** The code above is inside a while() that change the /*query*/ in each loop
I don't have a way of testing this, but try something like this, using a recursive function: var results = sqlQuery(sql) function sqlQuery (sql) { return new Promise((resolve, reject) => { sql.query(/*query*/, function (error, results, fields) { if (error) { return sqlQuery(sql).then(res => resolve(res)); } resolve(results) }) }) } Although I have to say that redoing it over and over again just isn't the best idea...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, node.js, asynchronous, promise, timeout" }
Database Mirroring protocol TCP ports used. One default, one dynamic? When running below query on the primary/secondary replica of a SQL Server Always On Availability Group™ SELECT DISTINCT local_tcp_port,protocol_type,num_reads,num_writes FROM sys.dm_exec_connections WHERE local_net_address is not null; Two local tcp ports show up for the Database mirroring protocol, `5022` & `63420` Server Name local_tcp_port protocol_type num_reads num_writes ServerName 5022 Database Mirroring 102942598 5 ServerName 63420 Database Mirroring 5 89655349 The `5022` port is expected, as this is the one configured as the mirroring endpoint. The other one seems to be a dynamic port, why and for what is this one used? Could it have to do with the fact that one is showing a high number of reads (`5022`) and the other one showing a high number of writes (`63420`). > Build version: 13.0.5264.1
When an application establishes a TCP connection, it specifies a port for the inbound (receive) port, and uses a (somewhat) randomly selected port for outbound (source, or send). The inbound port for AG replication is 5022 by default, so all replication traffic is sent TO port 5022. Accordingly, you see the network reads occurring on port 5022, as SQL Server is listening on port 5022 and reading packets that are sent to that port. The outbound port, which is selected randomly (more or less), is the port it is sent FROM. Accordingly, you see the writes associated with the random port (63420 in your example), as SQL Server is writing data to this port to be sent on the connection. See How are source ports determined... for more
stackexchange-dba
{ "answer_score": 7, "question_score": 8, "tags": "sql server, sql server 2016, availability groups" }
What is the best practice for setting JPEG metadata for CC-BY-NC licensed pictures? I want to publish my pictures with a CC-BY-NC license but I could not find a tutorial how store this information with my JPEG metadata. Is there a best practice? Do services like Flickr, Google+ or Facebook read this information?
As @coneslayer notes, Creative Commons does indeed provide guidance for XMP information. The main thing is to set **xmpRights:UsageTerms** to _This work is licensed to the public under the Creative Commons Attribution-ShareAlike license verify at That "verify" link is optional and should be a web site explaining the licensing in more detail. If you have such a web page, you should also set **xmpRights:WebStatement** to that URL. They also recommend duplicating **xmpRights:UsageTerms** into **dc:rights** , because some people might use that tag instead. You also can and should set XMP properties using Creative Commons' own schema, which defines **cc:license** , **cc:morePermissions** (for possible other allowed uses), **cc:attributionURL** , and **cc:attributionName**.
stackexchange-photo
{ "answer_score": 6, "question_score": 17, "tags": "metadata, licensing, creative commons" }
How to initialize and return an object in a single line I am trying to create Option objects based on the following typed interface: interface Option { /** Text for rendering */ label: string; /** Value for searching */ value: string | number; /** * Allow this option to be cleared * @default true */ clearableValue?: boolean; } Is it possible to convert the following to a single line? const options = [1, 2, 3].map<Option>((t) => { const option: Option = { label: String(t), value: String(t) }; return option; }); I tried: const options = [1, 2, 3].map<Option>((t) => Option = { label: String(t), value: String(t) }); but it doesn't work.
You're almost there: const options = [1, 2, 3].map(t => <Option>{ label: String(t), value: String(t) }); Type assertion `<Option>{ label: String(t), value: String(t) }` can also be done with `as` operator: `t => ({ label: String(t), value: String(t) }) as Option` **Update** : As you've already figured out - the first option (`<Option>`) creates ambiguity in _*.tsx_ files, so `as` syntax is preferred.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, typescript, lambda, object initialization" }
Do minions summoned by other enemies or bosses give XP? Enemies such as The Tomb Guardian will summon skeletons during battle. Do these minions give XP when they are killed?
Yes, Skeletons summoned by the Tomb Guardian give both XP and can also drop items and gold. It's a nice bonus, to be sure, but given the slow rate it takes for Tomb Guardians to summon more of their friends, you'll have better gold and XP rates if you just kill them and press on. As far as I'm aware (and in my own experience), all summoned monsters give xp. Most summoned monsters can drop loot too, with the exception of boss adds (or if they do, it gets added to the boss' loot).
stackexchange-gaming
{ "answer_score": 4, "question_score": 5, "tags": "diablo 3" }
PHP generate json - list of categories Hi I need to generate json code with php like this <
You can use an multi-dimensional array with the json_encode function to achieve this structure. $var = array( "contacts" => array ( array( "id" => 1, "name" => "foo" ), array( "id" => 2, "name" => "bar" ) ) ); echo json_encode($var);
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -6, "tags": "php, json" }
Defining a contact form I am trying to understand contact structures. To this end, as an exercise, I intend to define a contact form on $S^3$. Here is what I have so far: Since $S^3$ is in $\mathbb R^4$ one can specify a point on $S^3$ by a $4$-tuple $(x,y,z,w)$. If one endows $S^3$ with stereographic coordinate charts one obtain coordinates as follows: $({2X\over X^2 + Y^2 + Z^2 + 1}, {2Y\over X^2 + Y^2 + Z^2 + 1}, {2Z\over X^2 + Y^2 + Z^2 + 1}, {X^2 + Y^2 + Z^2 - 1\over X^2 + Y^2 + Z^2 + 1})$ where $(X,Y,Z)$ is a point in $\mathbb R^3$. The standard contact structure on $S^3$ is given by $xdz - z dx + y dw - w dy$. My question is: > Does $xdz - z dx + y dw - w dy$ mean the contact structure is ${2X\over X^2 + Y^2 + Z^2 + 1}d{2Z\over X^2 + Y^2 + Z^2 + 1} - \dots$ and so on?
Yes, if you use the stereographic projection then it is the form you indicated. To be precise, $\alpha = x dz - zdx + y dw - wdy$ is a one form on $\mathbb R^4$. So the contact structure on $\mathbb S^3$ is really $\iota^* \alpha$, where $\iota : \mathbb S^3 \to \mathbb R^4$ is the inclusion.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "differential geometry, contact topology" }
Can I rotate a spinner? Androidstudio simple question I cant find the answer anywhere, is there a way to rotate a spinner, without rotating screen or anything just create a spinner which is rotated 90 degrees? Thanks in advance.
On API Level 11+, you are welcome to rotate any `View` via `android:rotation` in your layout XML or `setRotation()` in Java. Whether this will give you something that your users will like, I cannot say.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, android studio, spinner" }
Youtube pay-per-view I am currently working on a project for a customer who needs a video-service. Users have to pay to get access to the videos, however it should be possible to get a preview of the video (30 sec) without paying. Now we've been looking into some hosting solutions and as it turns out it is not cheap when you need that much traffic on a website (and no - no-limit traffic is not an option). So we were talking about using YouTube to host the videos, however we have no idea if this is even possible? It would have to be a private (or semi-private) video on YouTube that can then be watched from the website whenever we allow a user to watch it. I know it is fairly easy to implement an embedded player on the website but I want to ensure that people cannot just get the video ID from the source code or from an AJAX request and then watch and share the video elsewhere. Thanks..
You have private and unlisted videos. For private videos you can only share them with 50 people. If you'd like to share them with more than 50, then they have to be unlisted. At that point the URL needs to be known to view them. If you need more than 50 people being able to view the video, unlisted is your only choice. Unlisted video is like a phone number. You can have it unlisted, but once anyone gets it (and is willing to share it with others) it is no longer private. How much traffic/storage/bandwidth are you looking at using? _**update:_** I've created an unlisted video and the embedded code looks like this: <iframe width="420" height="315" src=" frameborder="0" allowfullscreen></iframe> You could write your own player though that would obscure the URL.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "video, youtube, pay per view" }
Using 'dummy' pointers just for comparison I have a struct that contains a string (character pointer). This string/array should be in the form of one of the following: 1. contain actual string data 2. no actual data, just should be able to show it's in something called `STATE_1` 3. same as above, but `STATE_2` I want to be able to check if a 'string' is in `STATE_1` or `STATE_2`, and do something differently than if it contained actual data. If I had only one state, I could use a null pointer. I tried something along the lines of this, but it leads to undefined behavior. char *STATE_1, *STATE_2; ... if(tstruct.string == STATE_1 || tstruct.string == STATE_2){ ... }
Reserve two static addresses. They're guaranteed to be unique. static char STATE_1[1]; static char STATE_2[1]; if (tstruct.string == STATE_1 || tstruct.string == STATE_2) { ... } These could be global variables or they could be static locals, either one.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c, pointers" }
How do you determine how far to normalize a database? When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?
You want to start designing a normalized database up to 3rd normal form. As you develop the business logic layer you may decide you have to denormalize a bit but _never, never_ go below the 3rd form. Always, keep 1st and 2nd form compliant. You want to denormalize for simplicity of code, not for performance. Use indexes and stored procedures for that :) The reason not "normalize as you go" is that you would have to modify the code you already have written most every time you modify the database design. There are a couple of good articles: <
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 18, "tags": "database design, language agnostic, database normalization" }
Different answers for same code in c What happens in this code? #include <stdio.h> int main(){ int e; printf("%d ", e); printf("%s", e); return 0; } Does e will have a) Garbage value? b) NULL In GCC it shows garbage value and in g++ it shows 0 and NULL. Thanks!!
Both statements invoke undefined behavior because `e` object is not initialized so its value is indeterminate. The second statement also has the wrong conversion specifier, `%s` specification requires a `char *` argument. So as someone mentioned in the comments, the correct answer is neither a) nor b) but c) _demons flying out your nose_.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -4, "tags": "c, gcc, g++" }
What would be the name of a LIFO structure with the following behavior? I have been documenting myself about stacks, queues and deques for a small project. I will be requiring use of both stacks and queues for the project, and another type of structure, something similar to a stack, but that removes the final elements, such as this: Stack from top to bottom (max 5 elem): [B][C][D][E][F] Push A, becomes [A]=>[B][C][D][E]=>[F], result: [A][B][C][D][E] I have been searching around wikipedia and such, but I don't know how to call this other than "some kind of stack". Results are LIFO, so popping would return A in the example, not F. The code is done as well, so I don't ask for help on that aspect. My question is simpler: what would be the proper name for this structure? EDIT: After examining the G5 library as suggested below. I decided to call them "Limited Stacks" or "Lstacks" since it's a name already used in a library. That would make the code more readable. Thanks to everyone!
That looks like a FIFO stack to me. Item A is your last in, Item F is your first out.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "naming conventions, stack" }
Extract a string after some string I have a text paragraph `my_text` which contains lines like ........ licensed in Bangladesh. We are happy to announce ...................... ................................................ I want to extract the word "Bangladesh" from it. To decide if i want that word depends upon the presence of "licensed in" in the sentence. Current code is like: texts = my_text.split("licensed in") # extract the word before the first dot (.) from texts[1] What is more appropriate way to do it in python?
That's a job for a regex: import re location = re.search(r"licensed in ([^.]*)", my_text).group(1) **Explanation:** licensed\ in\ # Match "licensed in " ( # Match and capture in group 1: [^.]* # Any number of characters except dots. ) # End of capturing group 1
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python" }
Replace element of a matrix with condition consider a matrix > $\left( \begin{array}{ccccc} 0 & 0 & 1 \\\ 1 & 0 & 0 \\\ 1 & 1 & 0 \\\ \end{array}\right)$ How do I do a program that does these steps 1-Replace each element equal to 1 by $x_{ij}$ 2- Replace elements on the diagonal by 1 After execution the matrix will be formed > $\left( \begin{array}{ccccc} 1 & 0 & x_{1,3} \\\ x_{2,1} & 1 & 0 \\\ x_{3,1} & x_{3,2} & 1 \\\ \end{array}\right)$ My attempts with the function ReplacePart[MM, {i,j} -> x_] , If and MM[[i,j]]=new But I did not come out with a result, knowing that I am beginning in Mathematica
MapIndexed[If[Equal @@ #2, 1, # Subscript[x, ##& @@ #2]]&, #, {2}]&@ {{0, 0, 1}, {1, 0, 0}, {1, 1, 0}}; % // TeXForm > $\left( \begin{array}{ccc} 1 & 0 & x_{1,3} \\\ x_{2,1} & 1 & 0 \\\ x_{3,1} & x_{3,2} & 1 \\\ \end{array} \right)$ MapIndexed[f[Equal @@ #2, 1, # Subscript[x, ## & @@ #2]] &, #, {2}] &@ RandomInteger[1, {10, 10}] // TeXForm > $\left( \begin{array}{ccccccccc} 1 & x_{1,2} & 0 & x_{1,4} & x_{1,5} & 0 & x_{1,7} & 0 & x_{1,9} \\\ 0 & 1 & x_{2,3} & 0 & x_{2,5} & x_{2,6} & 0 & x_{2,8} & x_{2,9} \\\ 0 & x_{3,2} & 1 & 0 & x_{3,5} & 0 & 0 & x_{3,8} & 0 \\\ 0 & x_{4,2} & 0 & 1 & x_{4,5} & 0 & 0 & 0 & 0 \\\ 0 & 0 & x_{5,3} & 0 & 1 & 0 & x_{5,7} & x_{5,8} & 0 \\\ x_{6,1} & 0 & 0 & 0 & 0 & 1 & x_{6,7} & 0 & 0 \\\ 0 & 0 & x_{7,3} & x_{7,4} & 0 & 0 & 1 & x_{7,8} & 0 \\\ x_{8,1} & x_{8,2} & 0 & 0 & 0 & x_{8,6} & x_{8,7} & 1 & x_{8,9} \\\ 0 & x_{9,2} & 0 & x_{9,4} & x_{9,5} & 0 & x_{9,7} & 0 & 1 \\\ \end{array} \right) $
stackexchange-mathematica
{ "answer_score": 4, "question_score": 4, "tags": "list manipulation, matrix, replacement, expression construction" }
Spotlight equivalent for Windows 7? Can anyone make recommendations? I used to use Launchy back in the XP days, but I don't know if there are better alternatives now.
Why not Windows Search? !start menu search It has been there since Vista and has been refined even more in Windows 7. By just pressing the "Windows" key on your keyboard, you can instantly start searching your Start Menu and your entire computer. The best thing about it is that it is built in, and is available in every Explorer window.
stackexchange-superuser
{ "answer_score": 21, "question_score": 14, "tags": "windows 7, launcher" }
Boost array Initialization in C++ I need to declare a boost::array. I did it as `boost::array<char, 116> buf;` is there a possibility that I can declare with the size stored as a constant that is initialized from property file. something like `boost::array<char, BUFFER_SIZE> buf;` Any Help?
No. If you want a dynamically sizable array, use a `std::vector` Reason for No is that the template parameter cannot be provided at run time (caveat: current standard)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c++, arrays, boost" }
Inotifywait doesn't run command I have a basic inotifywait script called watch.sh and a few files ending in .styl in the same directory. Here's the script, that catches the changes, but doesn't execute the code within the do/done I init it like `sh watch.sh` and here's the script #!/bin/sh while inotifywait -m -o ./log.txt -e modify ./*.styl; do stylus -c %f done I tried having `echo "hi"` within the exec portion but nothing executes
The problem you are having is with the `-m` option for `inotifywait`. This causes the command to never exit. Since `while` checks the exit status of a command, the command must exit in order to continue execution of the loop. Here is the description of `-m` from the manpage: Instead of exiting after receiving a single event, execute indefinitely. The default behaviour is to exit after the first event occurs. Removing the `-m` option should resolve your issues: while inotifywait -o ./log.txt -e modify ./*.styl; do stylus -c %f done
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "bash, inotify, stylus" }
Date format change SSRS I have a view with a date column with this format : `YYYY-MM-DD` and I am using that column in a SSRS report but the final user wants to have something like this: > December 31, 2018 I am using this expression: =FormatDateTime(Parameters!prmReportDate.Value,DateFormat.LongDate) But I am getting this: > Monday December 31, 2018 I don't need the day. Is there a way to remove it?
Try something like this: =MonthName(Month(Parameters!prmReportDate.Value),false) & " " & day(Parameters!prmReportDate.Value) & "," & year(Parameters!prmReportDate.Value)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, reporting services, ssrs 2012" }
Tensorboard in Colab: No dashboards are active for the current data set I am trying to display a Tensorboard in Google Colab. I import tensorboard: `%load_ext tensorboard`, then create a `log_dir`, and fit it as follows: log_dir = '/gdrive/My Drive/project/' + "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1) history = model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size, callbacks=[tensorboard_callback]) But when I call it with `%tensorboard --logdir logs/fit` it doesn't display. Instead, it throws the following message: > No dashboards are active for the current data set. Is there a solution for this? is the problem in the fixed path I passed in `log_dir`?
Please try the below code log_dir = '/gdrive/My Drive/project/' + "logs/fit/" tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1) history = model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size, callbacks=[tensorboard_callback]) %load_ext tensorboard %tensorboard --logdir /gdrive/My Drive/project/logs/fit/
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "python, tensorflow, google colaboratory, tensorflow2.0, tensorboard" }
Regex involving nested delimiters/quotes I have a string that is enclosed by either apostrophes or double-quotes. Within the string, the other ('non-enclosing') character may appear. I'd like to extract the contents of the string using regex. Example: `string = "isn't";` and I want to extract `isn't`. Using `/\'"[\'"]/` doesn't work because it doesn't impose the constraint that the string is opened and closed by the same character. Using `/([\'"])([^\'"]*)(?1)/` fixes that, but disallows the 'other' character from occurring within the string. I need something like `/([\'"])(!(?1)*)(?1)/` but how do I write that? As a bonus, can I avoid capturing the opening character so that `?1` contains the string contents?
Group index 1 contains the characters which are present within the double quotes or single quotes. (?|"([^"]*)"|'([^']*)') DEMO **OR** You could use the below regex also, ([\'"])((?:(?!\1).)++)\1 DEMO **Pattern Explanation:** * `([\'"])` Captures the starting single or double quotes. * `((?:(?!\1).)+)` Captures one or more characters but not of the character which was present inside the group index 1. * `\1` Must end with a character captured by the group 1.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, regex" }
get number of weeks away from today i have a date in the future and i want to find out how many weeks away this is.
(futureDate - DateTime.Today).TotalDays / 7
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "c#, date" }
How does $x^4+y^4=z^2 \implies x^4+y^4=z^4$? Why is the statement "the following cannot be satisfied" for $x^4+y^4=z^2$ more strong than for $x^4+y^4=z^4?$ More specifically, how does $x^4+y^4=z^2 \implies x^4+y^4=z^4?$ This statement was found on page 4 of the following document.
Your question is mistaken: you have not correctly understood what is written in the document that you refer to. Of course that if $(x,y,z)$ satisfies $x^4 + y^4 = z^2$, it does _not_ follow that it also satisfies $x^4 + y^4 = z^4$ _unless_ $z^2 = z^4$ (i.e. $z \in \\{-1,0,1\\}$), which is very restrictive and not what that author meant to say. What is meant there is that if $(x,y,z)$ satisfies $x^4 + y^4 = z^4$, then there exist _another_ triple $(X,Y,Z)$ satisfying $X^4 + Y^4 = Z^2$ (and that triple is precisely $(X,Y,Z) = (x,y,z^2)$).
stackexchange-math
{ "answer_score": 5, "question_score": 0, "tags": "algebra precalculus, elementary number theory, diophantine equations, pythagorean triples" }
How to replace 'makeIso' from the older lens versions in the new version (4.3)? I have some code which uses `makeIso` from the `lens` package: newtype Foo = Foo Integer makeIso Foo' incrementFoo :: Foo -> Foo incrementFoo = foo +~ 1 Now I would like to use this code with the 4.3 version of the `lens` package. This version lacks `makeIso` and the changelog says: > Removed `makeIsos` in favor of `makePrisms` and `makeLenses`. Each of these functions will construct `Isos` when appropriate. Because there never was such a function as `makeIsos` I think it's a spelling mistake and they mean `makeIso`. So I tried to replace `makeIso` by `makeLenses` but that doesn't create a foo `Iso`. What is the correct way to replace `makeIso`? Thanks for your help
Define an accessor with an underscore: {-# LANGUAGE TemplateHaskell #-} import Control.Lens newtype Foo = Foo { _getFoo :: Integer } deriving Show $(makeLenses ''Foo) This will create a `getFoo` iso: getFoo :: (Profunctor p, Functor f) => p Integer (f Integer) -> p Foo (f Foo)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "haskell, haskell lens" }
Authenticaion, hash, salt, https process? Hi I think I may have done this the wrong way round can anyone help explain how you hash/salt a password. Do you do it from the client or the webservice? I have a datacontract which has a password datamember, in my service I do this to create a hash/salt of the password before it is saved: So here is the process in which I was thinking. Rest Service has https for secure connection User creates account (along with password) //to stop packet sniffing when user creates account https is used during POST so no one can see the password? web service then creates a hash of the password to store it //so if anyone did get access to the service/database they couldnt make much use of the data in terms of breaching accounts Then some means to authenticate that user there after Is this correct?
Sounds like you're on the right track. Hashing along with the salt value should never occur on client side, as attackers will have access to that code. And https would indeed secure the connection, disallowing others from reading the data. During authentication you do the same thing: take the password the user entered via https, hash/salt that value, then compare the result hash with the value in the database. And of course if you ever return a `Student` object to the client, it should contain neither of the values. It may be wise not to reuse the `Password` property of `Student` since now you can't tell whether it contains the plain password or the hashed value.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, wcf, web services, rest, authentication" }
Problem with permute and lattice while installing vegan package I'm trying to do my homework, but got somehow stuck. Please help! !Screenshot I've already installed "permute" and "lattice" ... but it still doesn't work. What can I do?
There is no indication of an error there; R is telling you that the packages were loaded correctly and that _vegan_ also loaded correctly.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "installation, lattice, vegan, permute" }
What's the value of the angle $x$ in the figure below? For reference: (Figure without scale ) $AK = 8, JC = 4, BE = 10$ (Answer:$53^o)$ ![enter image description here]( My progress: exterior angle bisector theorem: $~~~~~~~~~~~~~~~~~~~~~~~~~~\frac{AE}{CE}=\frac{AB}{BC}$ $\triangle ABK \sim \triangle BCJ~(AA):\\\ \frac{8}{4}=\frac{K}{BJ}=\frac{AB}{BC} \implies BK = 2JB, AB = 2BC$ ![enter image description here](
You have found that $C$ is midpoint of $AE$. Construct the median $CD$ with $D$ on $AB$. Since $CD$ joins the midpoints of two sides of $\triangle ABE$, it is parallel to the third side $BE$ and is half its length. $\triangle CJD$ turns out to be a $3-4-5$ right triangle with $$x = \angle JDC = \sin^{-1} \frac{4}{5} \approx 53^\circ$$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "euclidean geometry, plane geometry" }
How to make Tomcat stream media? I am entirely new to streaming implementation. I have developed some RESTful web services using Jersey/Tomcat. There are few cases where I need to send audio/video files to the clients, which uptil now I have been sending as a file fr download - now I want to stream these files. Do I need to write some code for this ? Or I need some third party solutions ...I have heard about Wowza / Darwin / Red5...But I dont know if they can be integrated with Tomcat and my existing services. Any third party solutions need to be free / opensource, and they should support both audio and video streaming. In the near future I need to add transcoding support too..for which I am planning to use Xuggler. So it would be good if the server is having such support. Any pointers would be appreciated. Thanks !!
Red5 is essentially Tomcat with added features. I don't know how far back in time the fork was made but the basic functionality is all there. Also - Red5 and xuggler play nicely together. You'd still need to code up the client side of the streaming portion though. Its possible that HTML 5 will give you this for cheap.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "java, tomcat, streaming, media" }
Why do Disk utility and Gparted show different information for the same hdd(s)? Gparted and Disks utility give me different sizes for my hard drive and its partitions. Is there a reason, for both programs, to list different information or is it an error? **GParted & Terminal output:** `sudo lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL` > dev/sda = 298.1 Gib > /dev/sda3 = 191.40 GiB > /dev/sda4 = 92 GiB > /dev/sda5 = 88.40 GiB > /dev/sda6 = 3.60 GiB **Disks Utility output** > dev/sdb = 320 Gib > /dev/sda3 = 206 GiB > /dev/sda4 = 99 GiB > /dev/sda5 = 95 GiB > /dev/sda6 = 3.9 GiB
The result shown by `sudo lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL` performs calculations using the _binary prefix_ i.e. multiples of _1024_ (which is 210). So _500107862016 bytes_ would be equal to _465.76 GB_ or approximately _466 GB_. (You can use `-b` switch to print in bytes instead of human readable as `sudo lsblk -b -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL`.) Calculation: 500107862016 bytes = (500107862016 / (1024 ^ 3)) GB = 465.76 GB While Disks Utility uses decimal prefix for calculation so expressed as multiples of _1000_. So _500107862016 bytes_ here would mean _500.11 GB or 500 GB_ approx. Calculation: 500107862016 bytes = (500107862016 / (1000 ^ 3)) GB = 500.11 GB
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 3, "tags": "hard drive, gparted" }
Example- $l_p$ norm space $$||x||= {[{\sum _{i=1}^\infty |x_i|^p}]}^{1/p}$$ Is a norm on $l_p$ space :- space of all sequences made of scalars from $\mathfrak C$(filed of complex numbers). To prove that above is norm on $l_p$ space; firstly, we need to show that $||x||\ge0$.[first property of norm space] It is written in my book that this is trivially. But I couldn't convince myself. Here $x=<x_1,x_2........>$ sequences, where scalars $x_i\in \mathfrak C$, So $|x_i|>0$ and their sum is positive. But its whole power is $1/p$ then how come its always positive. for example if $p= 1/2$ then $||x||$ has two values one is positive and another negative.
In this context (and quite generally in the context of analysis) $x^\alpha $ for non-negative $x$ is assumed to be the non-negative value of $x^\alpha $ (in case more than one value is possible). So, in particular, $x^{1/2}$ means the non-negative square root of $x$.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "linear algebra, analysis, functional analysis, self learning" }
Auto Starting & Stopping a YouTube Video with Twitter Bootstrap I am using Twitter Bootstrap's modal box to pop-up a video `lightbox` when a user clicks on a video thumbnail image (example: < use password: shc). If possible, I would like to have the video auto-play when the `lightbox` pops up and auto-stop when the user closes the `lightbox`. There are some similar questions to this, but none of them have helped me out much. Any help would be greatly appreciated. Thanks!
add `&autoplay=1` to the youtube video url. * * * **EDIT:** You can use the Event show to trigger a function which add the code into the modal $('#myModal').on('show', function () { $('div.modal-body').html('<iframe src=" width="500" height="281" frameborder="0" allowfullscreen=""></iframe>'); }); **Demo :** < The solution is not complete, you will have to remove the iframe when closing the modal.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "jquery, youtube, twitter bootstrap, modal dialog" }
if $2$ is root of equation $|A-xI|=0$ (where $A$ is non-singular matrix), $\frac{|A|}{2}$ root of equation $|B-xI|=0$ then $B$ can be if $2$ is root of equation $|A-xI|=0$ (where $A$ is non-singular matrix), $\frac{|A|}{2}$ root of equation $|B-xI|=0$ then $B$ can be (Where $x$ is a real Number) (A) $e$ (B) $Adj (A)$ (C) $\cos(\alpha)-i\sin(\alpha)$ (D) NONE Using option I got option B. Is there any other way to solve this question?
$$ \begin{align} &\ \det(A-2I) = 0 \\\ \implies &\ \det\left(\frac{A}{2} - I\right) = 0 \\\ \implies &\ \det\left(\frac{A\det(A)}{2} - \det(A) I\right) = 0 ~~(\because \det(A) \ne 0)\\\ \implies &\ \det \left(\frac{A\det(A)}{2} - A ~\text{adj} (A)\right) = 0 \\\ \implies &\ \det(A)\det\left(\frac{\det(A)}{2}I - \text{adj} (A)\right) = 0 \\\ \implies &\ \det\left(\frac{\det(A)}{2}I - \text{adj} (A)\right) = 0 ~~(\because \det(A) \ne 0) \\\ \implies &\ \det\left(\text{adj} (A)-\frac{\det(A)}{2}I\right) = 0 \\\ \end{align}$$ Therefore, $\frac{\det(A)}{2}$ is a root of the equation $\det(B-xI) = 0$ where $B = \text{adj}(A)$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "matrices, matrix equations" }
Soft-keyboard squeezes textedit box in Android How can I solve the following issue? What I would like to happen is for the input window to be displaced, not squeezed, by the soft-keyboard. ![enter image description here]( ![enter image description here](
Add `android:windowSoftInputMode="adjustPan"` to your activity tag in your AndroidManifest.xml
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android, manifest, android softkeyboard" }
In Descent, can you make an attack without an implement? In Descent each character has a number of dice representing their skill with melee, ranged, or magic. There are also dice added for their weapons. Can a character attack without a weapon? Are there any special rules for this?
Yes, a character can attack unarmed. "If a hero attacks without a weapon, he attacks with his fists. This is a melee attack that grants one red die and has no special abilities." (Descent rules, p19.) So it's a base melee attack using the minimum melee dice - the red plus however many black. Ranged and Magic attacks cannot be made without a weapon. If you want to house-rule allowing weaponless attacks of all three kinds, I would argue strongly in favour of using the base red (melee), blue (range) or white (magic) die as well as the black; this is the basic die used for all weapons of that type and is important for game design in distinguishing the range/damage properties of each attack type. These basic attack dice also carry the important one-in-six automatic-miss chance.
stackexchange-boardgames
{ "answer_score": 8, "question_score": 8, "tags": "descent" }
Please give the equation of this inequality Duchess, a dressmaker, ordered several meters of yellow cloth from a vendor, but the vendor only had 4 meters of yellow cloth in stock. The vendor bought the remaining lengths of yellow cloth from a wholesaler for PhP 1120. He then sold those lengths of yellow cloth to Duchess along with the original 4 meters of cloth for a total of PhP 1600. If the vendor's price per meter is at least PhP 10 more than the wholesaler's price per meter, what possible lengths of cloth did the vendor purchase from the wholesaler?
Hints: Let $x$ be the length purchased from the wholesaler Price per meter paid to wholesaler: $p_w = \dfrac{1120}{x}$ Price charged to customer per meter: $p_c =\dfrac{1600}{x+4}$ Stated inequality: $p_c \ge p_w+10$ Substitute and solve the quadratic inequality to get a range for $x$. For example $x=2$ and $x=200$ do not work, but $x=20$ does work
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "inequality, word problem" }
Database Replication Issue We had two MySQL 5.6.35 Server in our organization working as Master/Slave replication. The replication was working fine in this situation. But we have a new requirement to place another server which will be replicated from the slave server. **For example:** **Server1** \- Will work as master **Server2** \- Will work as slave in Server1 perspective and will work as master in **Server3** **Server3** \- Will act as slave and will receive replication from **Server2** Kindly help me on that.
You are asking for Master --> Relay --> Slave. This is quite possible. 1. Server2: `STOP SLAVE` 2. Server2: Pretend it is a Master and do the operations necessary to add its first Slave (Server3). (Dump data Server2, copy to Server3, etc) 3. Server2: `START SLAVE` Be sure to turn on `log_slave_updates` and `log_bin` and have different `server-id`. Why do you want M->R->S? It is a rather unusual setup. Is it the start of something more grandiose? I ask because there may be other tips to impart.
stackexchange-dba
{ "answer_score": 1, "question_score": 0, "tags": "mysql, database design, replication, mysql 5.6" }