qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
35,652,459
First I would like to note that I'm quite a beginner in using MATLABalthough I have some idea of syntax. I am working on a project trying to map the displacement of a particle in the environment. I have already manipulated all the data so it's all down to estetics. So basically I have two matrices 12 by 19 by 15, in which the coordinates (lat, long) of the particles are and the third dimension are timesteps. So the location of a particle changes through time. Now I wish to plot this in a way that at the first time step each element (so 12 by 19 although there are quite a few zeros and NaNs in the array) has it's own color that doesn't change in the next time step. This way you could track the movement of the particle. Note that I am operating with two matrices (one for latitude and the other for longitude, giving the location of the particle). So the plotting looks something like this ``` for it=1:nt plot(lat(:,:,it), long(:,:,it), 's'); hold on; end ``` It would also be nice if a connector line would be drawn in each succesive time step between the previous location and the new one. I am having problems with this because when I assign the color in `plot()` all the elements get their own color. Also when I try to draw lines, all elements in a time step get connected to each other and it's all just a big mess. I can do for only one particle, but if I introduce many it doesn't work.
2016/02/26
[ "https://Stackoverflow.com/questions/35652459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5986166/" ]
`org.springframework.web.context.ContextLoaderListener` is a class from Spring framework. As it implements the `ServletContextListener` interface, the servlet container notifies it at startup (`contextInitialized`) and at shutdown (`contextDestroyed`) of a web application. It is specifically in charge of bootstrapping (and orderly shutdown) the Spring ApplicationContext. Ref: javadoc says: > > Bootstrap listener to start up and shut down Spring's root WebApplicationContext. Simply delegates to ContextLoader as well as to ContextCleanupListener. > > > `org.springframework.web.context.request.RequestContextListener` is another class from same framework. Its javadoc says: > > Servlet 2.4+ listener that exposes the request to the current thread, through both LocaleContextHolder and RequestContextHolder. To be registered as listener in web.xml. > > > Alternatively, Spring's RequestContextFilter and Spring's DispatcherServlet also expose the same request context to the current thread. In contrast to this listener, advanced options are available there (e.g. "threadContextInheritable"). > > > This listener is mainly for use with third-party servlets, e.g. the JSF FacesServlet. Within Spring's own web support, DispatcherServlet's processing is perfectly sufficient. > > > So it is normally not used in a Spring MVC application, but allows request or session scoped bean in a JSF application using a Spring ApplicationContext
36,899,591
I have a query that takes over 2 seconds. Here is my table schema: ``` CREATE TABLE `vouchers` ( `id` int(11) NOT NULL, `voucher_dealer` int(11) NOT NULL, `voucher_number` varchar(20) NOT NULL, `voucher_customer_id` int(11) NOT NULL, `voucher_date` date NOT NULL, `voucher_added_date` datetime NOT NULL, `voucher_type` int(11) NOT NULL, `voucher_amount` double NOT NULL, `voucher_last_debt` double NOT NULL, `voucher_total_debt` double NOT NULL, `voucher_pay_method` int(11) NOT NULL, `voucher_note` text NOT NULL, `voucher_inserter` int(11) NOT NULL ) ``` The primary key is `id` and is auto incremented. The table has more than 1 million rows. The query looks like this: ``` select * from vouchers where voucher_customer_id = ** and voucher_date between date and date ``` and sometimes it looks like this: ``` select sum(voucher_amount) from vouchers where voucher_customer_id=** and voucher_date> date limit 1 ``` Is there a way to speed up my queries?
2016/04/27
[ "https://Stackoverflow.com/questions/36899591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4588796/" ]
You'll want to use MySQLs "EXPLAIN" to determine what's going on and why. <http://dev.mysql.com/doc/refman/5.7/en/explain.html> To do so, simply add "EXPLAIN " prior to your statement like this: ``` EXPLAIN select * from vouchers where voucher_customer_id = ** and voucher_date between date and date ``` It will give you information about available keys, how many rows it's needing to search...etc etc. You can use that information to determine why it's running slow and how you can improve it's speed. Once you've run it, you can use any of the many online resources that explain (no pun intended) how to use the "EXPLAIN" results. Here are some: <http://www.sitepoint.com/using-explain-to-write-better-mysql-queries/> [How to optimise MySQL queries based on EXPLAIN plan](https://stackoverflow.com/questions/10148851/how-to-optimise-mysql-queries-based-on-explain-plan) <https://www.digitalocean.com/community/tutorials/how-to-optimize-queries-and-tables-in-mysql-and-mariadb-on-a-vps>
1,568,444
> > Let $X$ be locally compact, Hausdorff and non compact. Prove that if $X$ has one “end”, then $X^\wedge - X$ , (where $X^\wedge$ is any Hausdorff compactification), is a continuum (=compact, connected). > > > **Definition** Let $X$ be a topological space. An "end" of $X$ assigns, to each compact subspace $K$ of $X$, a connected component $eK$ of its complement $X\setminus K$, in such a way that $eK′\subseteq eK$ whenever $K\subseteq K′$.
2015/12/09
[ "https://math.stackexchange.com/questions/1568444", "https://math.stackexchange.com", "https://math.stackexchange.com/users/289289/" ]
This isn't true in general. For instance, suppose $X=[0,\infty)\sqcup D$, where $D$ is an infinite discrete space. Then $X$ has only one end (the one coming from $[0,\infty)$, since every connected component in $D$ is compact). But you can compactify $X$ as $X^\wedge=[0,\infty]\sqcup E$ for any compactification $E$ of $D$, and then $X^\wedge-X=\{\infty\}\sqcup (E-D)$ is disconnected. However, if you assume $X$ is connected and locally connected, then it is true. First, I claim that for any compact set $K\subset X$, $X-K$ has only finitely many unbounded components (where "unbounded" means its closure in $X$ is not compact). To prove this, let $L\subset X$ be a compact set containing $K$ in its interior (such an $L$ exists by local compactness of $X$). Note that by local connectedness, every component of $X-K$ is open, and so by compactness only finitely many components of $X-K$ can intersect $\partial L$. But if $A\subseteq X-K$ is an unbounded component, it is not contained in $L$ and so $A-L$ is a nonempty open set. Since $X$ is connected, $A-L$ cannot be closed in $X$. But $A$ is closed in $X-K\supseteq X-int(L)$, and so $\overline{A-L}$ is both contained in $A$ and must contain points of $\partial L$. Thus $A$ intersects $\partial L$, and by the remarks above, this means there are only finitely many such $A$. Second, I claim that if $K\subseteq K'\subset X$ are compact subsets and $A$ is an unbounded clopen subset of $X-K$ (in particular, if $A$ is an unbounded component of $X-K$), then $A$ contains an unbounded component of $X-K'$. To prove this, let $L\subset X$ be a compact set containing $K'$ in its interior. As above, only finitely many components of $X-K'$ intersect $\partial L$. Moreover, the argument of the previous paragraph shows that every component of $X-K'$ that intersects $X-L$ must also intersect $\partial L$. We conclude that every component of $A-K'$ is either contained in $L$ or is one of the finitely many components of $X-K'$ intersecting $\partial L$. If all of these finitely many components are bounded, then $A-K'$ would be bounded (since it is contained in the union of $L$ and finitely many bounded sets). This is impossible, since $A$ is unbounded. Thus one of the components of $A-K'$ is unbounded. It now follows by a standard compactness argument that if $A$ is an unbounded component of $X-K$ for some compact $K\subset X$, then there is an end $e$ of $X$ such that $eK=A$. (Explicitly, let $F\_K$ denote the set of unbounded components of $X-K$ with the discrete topology. Then an end is a point in the product $\prod\_K F\_K$ satisfying certain identities, and paragraph above shows that any finite number of those identities can be satisfied by an element of the product sending $K$ to $A$. Compactness of the product then gives an element satisfying all of the identities.) Now suppose $X^\wedge$ is a compactification of $X$ such that $X^\wedge-X$ is disconnected. We will show $X$ has more than one end. Let $C$ be a nonempty proper clopen subset of $X^\wedge-X$. Then $C$ and $D=(X^\wedge-X)-C$ are disjoint closed subsets of $X^\wedge$, so we can find disjoint open sets $U,V\subset X^\wedge$ such that $C\subset U$ and $D\subset V$. We then have that $K=X^\wedge-(U\cup V)$ is compact and contained in $X$. Now $X\cap U$ is an unbounded clopen subset of $X-K$, so as shown above (taking $K'=K$), it must contain an unbounded component of $X-K$. This unbounded component then extends to an end $e$ such that $eK\subset U$. But by the same argument with $V$ in place of $U$, there also exists an end $e'$ such that $e'K\subset V$. We thus have two distinct ends of $X$. (The argument above was adapted from the standard proof that if $X$ is locally compact Hausdorff, connected, and locally connected, then you can compactify $X$ by adding a point for each end of $X$. This proof can be found [here](https://chiasme.wordpress.com/2014/08/12/freudenthal-compactification/), among many other places (the hypothesis of $\sigma$-compactness used there is easily seen to be unnecessary).)
67,084,877
I had been working on a project that uses Firebase Authentication. Everything worked fine until I updated to Flutter 2. Now it's telling me that "User" isn't a type. I can't find anything in their changelog that might have caused this error. ``` splashScreenFunction: () async { //// check if login User result = FirebaseAuth.instance.currentUser; print("User: $result"); if (result != null) return mainPage(userID: result.uid,); else return LoginPage(); }, ``` Here's an example of one of the parts in my project that is giving me an error. This specific part is where I check if the user is logged in by trying to fetch the User ID. In other parts of the code I am using similar ways in order to obtain the user ID. What is the new way of doing this?? Did i miss something? I can't seem to find any information as this is a somewhat new update.
2021/04/14
[ "https://Stackoverflow.com/questions/67084877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14710307/" ]
try prefixing firebase\_auth import (like firebase\_auth) ``` import 'package:firebase_auth/firebase_auth.dart' as firebase_auth; . . . //Change firebase_auth.User result = firebase_auth.FirebaseAuth.instance.currentUser; ```
70,510
We recently changed IP schemes from `192.168.x.x` to `10.x.x.x` In doing so, I noticed that the prior network engineer had `ip default-gateway` in the configuration pointing to an old default gateway that no longer exist. I happened to notice this after our maintenance window ended. ``` ip default-gateway 192.168.10.1 ip classless ip route 0.0.0.0 0.0.0.0 10.6.0.1 no ip http server no ip http secure-server ``` **Question: Im assuming that I can safely remove this without affecting the current connection status, since 192.168.x.x scheme is no longer in effect and the `192.168.10.1` gateway is no longer in effect?**
2020/10/15
[ "https://networkengineering.stackexchange.com/questions/70510", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/46890/" ]
A router that is configured to route does not use the `ip default-gateway`. It uses the default route, and you have that in the configuration. Cisco has a document that explains the differences: *[Configuring a Gateway of Last Resort Using IP Commands](https://www.cisco.com/c/en/us/support/docs/ip/routing-information-protocol-rip/16448-default.html)*: > > The **ip default-gateway** command differs from the other two > commands. It should only be used when **ip routing** is disabled on > the Cisco router. > > > You can, and should, eliminate the `ip default-gateway` command if `ip routing` is enabled. Configuring the `ip default-gateway` command on a device that has routing enabled is a rookie mistake that gets made all too often.
12,992,681
I don't know if this is possible, I've never really used html canvas, but I am aware of ``` var imgPixels = canvasContext.getImageData(0, 0, canvas.width, canvas.height); ``` but how do I use this to get for example all the pixels with a certain color and change these pixels to white? So let's say I have a pixel colored red: ``` if(pixel==red){ pixel = white; } ``` that's the simple version of what I would like but not sure how to do that... anyone any ideas?
2012/10/20
[ "https://Stackoverflow.com/questions/12992681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/926978/" ]
Do something like this (here's the [canvas cheat sheet](https://websitesetup.org/wp-content/uploads/2015/11/Infopgraphic-CanvasCheatSheet-Final2.pdf)): ```js const canvas = document.querySelector("canvas"); const context = canvas.getContext("2d"); const { width, height } = canvas; const gradient = context.createLinearGradient(0, 0, 0, height); gradient.addColorStop(0.25, "#FF0000"); gradient.addColorStop(0.75, "#000000"); context.fillStyle = gradient; context.fillRect(0, 0, width, height); setTimeout(() => { const image = context.getImageData(0, 0, width, height); const { data } = image; const { length } = data; for (let i = 0; i < length; i += 4) { // red, green, blue, and alpha const r = data[i + 0]; const g = data[i + 1]; const b = data[i + 2]; const a = data[i + 3]; if (r === 255 && g === 0 && b === 0 && a === 255) { // pixel is red data[i + 1] = 255; // green is set to 100% data[i + 2] = 255; // blue is set to 100% // resulting color is white } } context.putImageData(image, 0, 0); }, 5000); ``` ```html <p>Wait for 5 seconds....</p> <canvas width="120" height="120"></canvas> ``` Hope that helps.
122,130
How do I detect a click on a layer and find out information about the layer that was clicked? Currently I can do the usual binding a popup and adding a click handler on the layer: ``` L.geoJson(data.streets, { onEachFeature: function(feature, featureLayer) { featureLayer.bindPopup(feature.properties.name); featureLayer.on('click', function(e) { console.log('Layer clicked!', e); }); ... ``` However the click handler on the layer doesn't give me any information about the layer, just the following: ``` containerPoint: o.Point latlng: o.LatLng { lat: 50.804443085898185, lng: -1.089920997619629 } __proto__: Object layerPoint: o.Point originalEvent: MouseEvent target: e type: "click" __proto__: Object ``` How can I get a reference to the layer it's clicking?
2014/11/14
[ "https://gis.stackexchange.com/questions/122130", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/39543/" ]
I was assigning layers to a featureGroup, I needed to put the click handler on the featureGroup in order to get a layer reference returned. Putting it on the individual layer didn't work.
39,158,502
In our TFS server 2013 we have several projects (Eg : P1, P2, **P3**, P4) When i'm going to **check in** the codes to a single project **Eg : P3** i'm getting below listed errors in output window of visual studio 2013. (but team connecting and other source control functions are working fine) > > All of the changes were either unmodified files or locks. The changes have been undone by the server. > > > Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. > > > The server returned content type text/html, which is not supported. > > > TF30063: You are not authorized to access > > > [![output window of visual studio 2013](https://i.stack.imgur.com/5WfwR.jpg)](https://i.stack.imgur.com/5WfwR.jpg) also some time it was working and I will get this message * Changeset 1874 successfully checked in Other projects are working fine Eg: P1, P2, P4
2016/08/26
[ "https://Stackoverflow.com/questions/39158502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2810828/" ]
It looks like something is intercepting the call and blocking it. TFS would normally always return a reponse type of `soap+xml`, `xml` or `json`, the fact you're seeing `text/html` indicates that a HTML error page is presented for some reason. I suspect it's your Virus scanner locally (if it provides web traffic protection), or an upstream proxy server or the anti-virus on the TFS server itself. That or your TFS server itself is really running into trouble in which case the eventlog on the TFS server should have a ASP.NET crash report. The easiest way to troubleshoot this is to install and run fiddler and try the check-in again. Look up the response you're getting and look at the HTML message. I suspect it will hold the actual error message and it will likely tell you the exact source of the error. --- As you reported, it was SonicWALL which is blocking the request before it reaches TFS. So either there is something fishy with the contents of the NuGet package, or the SonicWALL rules need to be adjusted to accept certain traffic to your TFS server.
31,421,844
How can I get File Object from absolute Path? The object is like when I get from `$request->file('fileInput')`. So i can use method like `$file->getClientOriginalName()` or `$file->getClientOriginalExtension()` or something like that. I can only find the way to get the File Object using `File::allFiles($absoluteFolderPath)` and loop through it to find the file that have the filename that i looking for. But is there something simpler?
2015/07/15
[ "https://Stackoverflow.com/questions/31421844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4243035/" ]
**Request::file()** method returns objects of the class **UploadedFile**. You can create such object yourself, but it kind of kills the purpose of the class, as it's supposed to be used for, well, uploaded files :) You should use the File class instead that is the parent class of the UploadedFile. You can create such object this way: ``` $uploadedFile = new \Symfony\Component\HttpFoundation\File\File($filePath); ``` If you instantiate the file this way, you won't have access to **getClient...()** methods as they are used to return the information about the file that it got from the client browser. If you want to get some additional info about the file you can use **getMimeType()** or **getExtension()** methods.
467,197
Let $X = \operatorname{Spec} k[x]\_{(x)}$ which consists of two elements, the generic point $\zeta$ corresponding to the zero ideal and the closed point $(x)$. Define an $\mathcal{O}\_X$-module $\mathcal{F}$ by setting $\mathcal{F}(X) = \{0\}$ and $\mathcal{F}(\zeta) = k(x).$ Now $\mathcal{F}$ is not a quasi-coherent sheaf because if $\mathcal{F}|\_{\operatorname{Spec} k[x]\_{(x)}} = \mathcal{F}$ is isomorphic to $\widetilde{M}$ for some $A$-module $M$, $\mathcal{F}(X) = 0$ implies that $\widetilde{M}(X) = M = 0$. But now $\mathcal{F}(\zeta)$ cannot be isomorphic to $\widetilde{M}(\zeta)$ because one is non-zero while the other is zero. Thus $\mathcal{F} \notin \operatorname{QCoh}(X)$. Are there any other examples of $\mathcal{O}\_X$-modules that are not quasi-coherent sheaves?
2013/08/14
[ "https://math.stackexchange.com/questions/467197", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let $R$ be a discrete valuation ring and $X=\mathrm{Spec}(R)$. Hence, as a set, we have $X=\{\eta,x\}$. The topology is such that $x$ is closed, but $\eta$ is not (in other words, it is the Sierpinski space). The structure sheaf is given by $\mathcal{O}(\emptyset)=0$, $\mathcal{O}(\{\eta\})=\mathcal{O}\_{\eta} = K$, the field of fractions of $R$, and $\mathcal{O}(X)=R$. An $\mathcal{O}$-module corresponds to an $R$-module $A$ (global sections) and an $K$-module $B$ (sections on $\{\eta\}$) equipped with a homomorphism of $R$-modules $A \to B|\_R$ (restriction), or equivalently a homomorphism of $K$-modules $\vartheta : A \otimes\_R K \to B$. It is quasi-coherent iff $\vartheta$ is an isomorphism. This gives lots of examples of $\mathcal{O}$-modules which are not quasi-coherent. For example, $\vartheta$ could be zero, etc.
68,421,527
I would like to scrape all the comments in this reddit page and then write the data into a csv file. I have written this code. I noticed that all comments were 'div' elements with a class of 'RichTextJSON-root'. Code written: ``` from bs4 import BeautifulSoup import requests import csv # Reddit source = requests.get( 'https://www.reddit.com/r/sysadmin/comments/gjkqvj/who_has_made_the_switch_from_dell_to_lenovo/').text soup = BeautifulSoup(source, 'html.parser') countreddit = 0 csv_file = open('reddit_scrape.csv', 'w') writer = csv.writer(csv_file) writer.writerow(['Comment']) comments = soup.find_all('div', class_='RichTextJSON-root') for comment in comments: for para in comment.find_all('p'): paratext = para.text writer.writerow([paratext]) countreddit += 1 print(f'Reddit Count: {countreddit}') csv_file.close() ``` Link to reddit post: <https://www.reddit.com/r/sysadmin/comments/gjkqvj/who_has_made_the_switch_from_dell_to_lenovo/> However, I have only managed to scrape till midway of the webpage, stopping at the comment 'Those using the WD15 docks would like to have a word with you.' May I ask how can I scrape till the end of this page? I read on other posts that it could be because when beautifulsoup scrapes, it only scrapes what is rendered on the webpage and at this point in time, the webpage has not been rendered completely. Thank you!
2021/07/17
[ "https://Stackoverflow.com/questions/68421527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16467488/" ]
Very close. The reshaping operation should be a [`pivot_table`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html) with the aggfunc set to count rather than [`pivot`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html): ``` plot_df = ( df_winter_start.pivot_table(index='month', columns='Disaster_Type', values='day', aggfunc='count') ) ``` Now that the data is in the correct format: `plot_df` ``` Disaster_Type Ice Snow Winter month 2 21.0 NaN NaN 3 7.0 NaN 6.0 4 5.0 9.0 NaN 6 NaN NaN 2.0 ``` It can be plotted with stacked bars: ``` plot_df.plot.bar(stacked=True, ax=ax, zorder=3, cmap=cmap, rot=0) ``` [![plot 1 stacked](https://i.stack.imgur.com/J4Z7q.png)](https://i.stack.imgur.com/J4Z7q.png) or as separate bars: ``` plot_df.plot.bar(ax=ax, zorder=3, cmap=cmap, rot=0) ``` [![plot 2 separate bars](https://i.stack.imgur.com/1DEH0.png)](https://i.stack.imgur.com/1DEH0.png)
540,937
What does the `apt-get install ...` command do? When I enter `apt-get install ...` command, there are some texts appearing on the screen, but that does not have enough information for me. I want to know if any file is created / edited, any service is started and other activities... Is there any `.sh` file executed when the `apt-get install ...` run? If so, how can I see the content of that `sh` file? The reason for this question is recently I tried to install tomcat7 with `apt-get install tomcat7`. Everything works fine until I install `tomcat7-admin` (manager web application), the server became unresponsive to any request. I tried this many times, and this always happen.
2014/10/24
[ "https://askubuntu.com/questions/540937", "https://askubuntu.com", "https://askubuntu.com/users/277876/" ]
Mostly, `apt-get` does the following things: * checks for dependencies (and asks to install them), * downloads the package, verifies it and then tells `dpkg` to install it. `dpkg` will: * extract the package and copy the content to the right location, and check for pre-existing files and modifications on them, * run [package maintainer scripts](https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html): `preinst`, `postinst`, (and `prerm`, `postrm` before these, if a package is being upgraded) * execute some actions based on [triggers](https://wiki.debian.org/DpkgTriggers) You might be interested in the maintainer scripts, which are usually located at `/var/lib/dpkg/info/<package-name>.{pre,post}{rm,inst}`. These are usually shell scripts, but there's no hard rule. For example: ``` $ ls /var/lib/dpkg/info/xml-core.{pre,post}{rm,inst} /var/lib/dpkg/info/xml-core.postinst /var/lib/dpkg/info/xml-core.postrm /var/lib/dpkg/info/xml-core.preinst /var/lib/dpkg/info/xml-core.prerm ```
31,499
Is it possible to attain the first jhana, then remain in first jhana, while walking, talking, eating and performing other daily activities? Or does one remain in first jhana only while in sitting meditation, then he has to leave the jhana and meditation, before he is able to perform daily activities such as walking, talking and eating?
2019/03/12
[ "https://buddhism.stackexchange.com/questions/31499", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/471/" ]
From [AN3.63](https://suttacentral.net/an3.63/en/sujato): > > With the giving up of pleasure and pain, and the ending of former happiness and sadness, I enter and remain in the fourth absorption, without pleasure or pain, with pure equanimity and mindfulness. > > > When I’m practicing like this, if I **walk** meditation, at that time I walk like the gods. > > > When I’m practicing like this, if I **stand**, at that time I stand like the gods. > > > When I’m practicing like this, if I **sit**, at that time I sit like the gods. > > > When I’m practicing like this, if I **lie** down, at that time I lie down like the gods. > > > There are some who find the above an indication that walking meditation in jhana is possible. There are also those who find the above impossible given the depth of absorption in which senses recede and physical processes such as breathing stop. There is also the matter of the Vinaya, which prohibits public discussion of attainments. To illustrate the difficulty of translation for those bound by the Vinaya, note that where Bhante Sujato uses "walking meditation", Bhikkhu Bodhi translates the section on walking in [AN3.63](https://suttacentral.net/an3.63/en/bodhi) with more ambiguity. Both are bound by the Vinaya: > > Then, brahmin, when I am in such a state, if I walk back and forth, on that occasion my **walking back and forth** is celestial. > > > Discussion of jhana attainments is problematic given the prohibitions of the Vinaya. In other words, the monastics who understand jhana are forbidden from discussing it. Therefore, this question can never be answered definitively in a public forum such as this.
2,585,429
It is possible to access bits of MATLAB's internal java code to programmatically change MATLAB itself. For example, you can programmatically open a document in the editor using ``` editorServices = com.mathworks.mlservices.MLEditorServices; editorServices.newDocument() %older versions of MATLAB seem to use new() ``` You can see the method signatures (but not what they do) using `methodsview`. ``` methodsview(com.mathworks.mlservices.MLEditorServices) ``` I have a few related questions about using these Java methods. Firstly, is there any documentation on these things (either from the Mathworks or otherwise)? Secondly, how do you find out what methods are available? The ones I've come across appear to be contained in JAR files in matlabroot\java\jar, but I'm not sure what the best way to inspect a JAR file is. Thirdly, are there functions for inspecting the classes, other than `methodsview`? Finally, are there any really useful methods that anyone has found?
2010/04/06
[ "https://Stackoverflow.com/questions/2585429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134830/" ]
There is no official documentation nor support for these classes. Moreover, these classes and internal methods represent internal implementation that may change without notice in any future Matlab release. This said, you can use my [uiinspect](http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methodspropertiescallbacks-of-an-object) and [checkClass](http://www.mathworks.com/matlabcentral/fileexchange/26947-checkclass) utilities to investigate the internal methods, properties and static fields. These utilities use Java reflection to do their job, something which is also done by the built-in ***methodsview*** function (I believe my utilities are far more powerful, though). In this respect, I believe we are not crossing the line of reverse-engineering which may violate Matlab's license. If you are looking for documentation, then my [UndocumentedMatlab.com](http://UndocumentedMatlab.com) website has plenty of relevant resources, and more is added on a regular basis so keep tuned. I am also working on a book that will present a very detailed overview of all these internal classes, among other undocumented stuff - I hope to have publication news later this year.
10,121,715
I am trying to increment progress bar and show percentage on a label. However, both remains without changes when "incrementaProgres" function is called. `IBOutlets` are properly linked on `xib` and also tested that, when function is called, variables have proper value. Thanks from delegate: ``` loadingViewController *theInstanceP = [[loadingViewController alloc] init]; [theInstanceP performSelectorOnMainThread:@selector(incrementaProgres:) withObject:[NSNumber numberWithFloat:0.15] waitUntilDone:YES]; ``` loadingView class: ``` - (void)viewDidLoad { [super viewDidLoad]; [spinner startAnimating]; [progress setProgress:0.0]; } - (void)incrementaProgres: (CGFloat)increment{ [progress setProgress:(progresInc + increment)]; carrega.text = [NSString stringWithFormat: @"%f", (progresInc + increment)]; } ```
2012/04/12
[ "https://Stackoverflow.com/questions/10121715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1238934/" ]
Progress bar's [progress](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIProgressView_Class/Reference/Reference.html) value is between `0.0` and `1.0`, your code sets it in the increments of `15.0`, which is out of range. Your increment should be `0.15`, not `15.0`.
27,503,621
I have the following code: ``` ids = set() for result in text_results: ids.add(str(result[5])) for result in doc_results: ids.add(str(result[4])) ``` Both `text_results` and `doc_results` are lists that contain other lists as items as you might have already guessed. Is there a more efficient way to do this using a nifty oneliner rather than two for loops?
2014/12/16
[ "https://Stackoverflow.com/questions/27503621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864413/" ]
I would probably write: ``` ids = set(str(result[5]) for result in text_results) ids.update(str(result[4]) for result in doc_results) ``` As for efficiency, if you want to squeeze every possible bit of performance then you first need a realistic dataset, then you can try things like `map` (or `itertools.imap` in Python 2) and `operator.itemgetter`, to see what's faster. If you absolutely must have a one-liner: ``` ids = set(itertools.chain((str(result[5]) for result in text_results), (str(result[4]) for result in doc_results))) ``` Although, if you want a one-liner it's also worth optimizing for conciseness so that your one-liner will be readable, and then seeing whether performance is adequate: ``` ids = set([str(x[5]) for x in text_results] + [str(x[4]) for x in doc_results])) ``` This "feels" inefficient because it concatenates two lists, which shouldn't be necessary. But that doesn't mean it really is inefficient for your data, so its worth including in your tests.
59,030,684
I am trying to see test coverage line by line in a class, however, only the first line is highlighted. [![enter image description here](https://i.stack.imgur.com/uW3o7.png)](https://i.stack.imgur.com/uW3o7.png) The *Show Inline Statistics* setting is enabled. [![enter image description here](https://i.stack.imgur.com/H4R7a.png)](https://i.stack.imgur.com/H4R7a.png) I get the test coverage for the **class**, **methods** and **lines** as below: [![enter image description here](https://i.stack.imgur.com/gydYw.png)](https://i.stack.imgur.com/gydYw.png) I remember this worked in a previous version of Android Studio (ca't exactly remember which). How can enable the feature so that coverage is shown for all lines.
2019/11/25
[ "https://Stackoverflow.com/questions/59030684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6275633/" ]
Step 1 - Run **testDebugUnitTest** with coverage [Click here to see unit test coverage](https://i.stack.imgur.com/Yy5oF.png) Step 2 - Generate coverage report - click on icon as shown in above image (yellow highlighted) give exported path to generate html file. Step 3 - Click on index.html file to view report. You will get test coverage percentage for **class, method and line** as shown in below image [Click here to see test coverage class](https://i.stack.imgur.com/guNFM.png) [click here to see overall coverage summary](https://i.stack.imgur.com/JWvoT.png)
23,323,344
I am working with a label and form which I want to center in the row, but encountering difficulties to do that. The label wont move to center next to the input field without moving the field down. This is the code: ``` <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="col-md-6 control-label pull right">Password: </label> <div class="col-md-6"> <input type="text" name="Password" class='form-control' /> </div> </div> </div> </div> ```
2014/04/27
[ "https://Stackoverflow.com/questions/23323344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3185936/" ]
I assume that you'd like to extract the first of two numbers in each string. You may use the `stri_extract_first_regex` function from the [stringi](http://stringi.rexamine.com) package: ``` library(stringi) stri_extract_first_regex(c("Pic 26+25", "Pic 1,2,3", "no pics"), "[0-9]+") ## [1] "26" "1" NA ```
30,778,140
Hi I am using `gem 'carmen-rails'` In my view I have written this ``` <%= f.country_select :country, prompt: 'Please select a country', :id=>'curr-country' %> ``` but its not taking this id 'curr-country'. Please guide how to give id in this. Thanks in advance.
2015/06/11
[ "https://Stackoverflow.com/questions/30778140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2739770/" ]
You'll have to pass a second hash with the HTML options: ``` <%= f.country_select :country, { prompt: 'Please select a country' }, { id: 'curr-country' } %> ``` The `carmen-rails` gem doesn't document this explicitly (it is documented [in code](https://github.com/jim/carmen-rails/blob/50ebda9ac696306abdfc6ebd75af06cd79de2ded/lib/carmen/rails/action_view/form_helper.rb#L54)). The `country_select` gem, however, does provide an example of this in the [Usage section of the `README`](https://github.com/stefanpenner/country_select#usage)
203,578
As the question says, where do each of the browsers store their offline data, be it cache, offline storage from html5, images, flash videos or anything web related that gets stored locally.
2012/10/20
[ "https://askubuntu.com/questions/203578", "https://askubuntu.com", "https://askubuntu.com/users/7035/" ]
Firefox store the offline data in `~/.mozilla` directory, to be more specific in `~/.mozilla/profiles/xxxxxxxx.default` directory. Chrome uses `~/.cache/google-chrome` directory for storing cache. Google chrome also uses `~/.config/google-chrome/Default` directory for storing recent history, tabs and other things. Like Chrome, Chromium uses as such with only the name changed. That is `~/.cache/chromium` and `~/.config/chromium/Default`
17,718,922
I have two classes * Author with attributes id, papers (Paper relationship), ... * Paper with attributes id, mainAuthor (Author relationship), authors (Author relationship) ... and want to map some JSON to it ``` "authors": [ { "id": 123, "papers": [ { "id": 1, "main_author_id": 123, ... }, ... ] }, ... ] ``` The problem is that the JSON is not structured like ``` "authors": [ { "id": 123, "papers": [ { "id": 1, "main_author": { "id": 123 } ... }, ... ] }, ... ] ``` so that I could easily map things (note the \*main\_author\* part of both JSON examples). I tried using mapping this value without a key path as explained [here](https://github.com/RestKit/RestKit/wiki/Object-Mapping#mapping-values-without-key-paths): ``` [authorMapping addAttributeMappingToKeyOfRepresentationFromAttribute:@"main_author_id"]; [authorMapping addAttributeMappingsFromDictionary:@{@"(main_author_id)": @"id"}]; ``` but I'm getting an error telling me that the keyPath *id* already exists and I may not add a second mapping for this keyPath. I totally understand this error, but I have no idea how to map from \*main\_author\_id\* back to *id*. Changing the data source may be the best solution, but this is unfortunately not possible. Any suggestion is highly welcome! Thanks!
2013/07/18
[ "https://Stackoverflow.com/questions/17718922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184245/" ]
This is exactly what foreign key mapping is for. It allows you to temporarily store the 'identity' value that you're provided with and then RestKit will find the appropriate object and complete the relationship.
12,157,558
I am learning matlab myself andI have made an animated plot using matlab;now i want to save it as an video file.can you tell me how to convert my animation into a video file in matlab.Below is my code ``` x=[1:2]; for i=1:25, m=randi([3,5]); n=randi([3,5]); y=[m n]; bar(x,y) axis equal A(i) = getframe; end ``` matlab version 7.8 R2009a
2012/08/28
[ "https://Stackoverflow.com/questions/12157558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/996366/" ]
use avifile: ``` aviobj = avifile('example.avi','compression','None'); x=[1:2]; for i=1:25, m=randi([3,5]); n=randi([3,5]); y=[m n]; bar(x,y) axis equal aviobj = addframe(aviobj,gcf); drawnow end viobj = close(aviobj) ```
71,941,740
I have installed Visual Studio 2022 on my PC today. I have an old app, which targets .NET 4.5. I see this error when attempting to build/compile the project: "Error MSB3644 The reference assemblies for .NETFramework,Version=v4.5 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at [https://aka.ms/msbuild/developerpacks"](https://aka.ms/msbuild/developerpacks%22) I have read this: <https://thomaslevesque.com/2021/11/12/building-a-project-that-target-net-45-in-visual-studio-2022/>. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5 already exists on my PC. I have downloaded the .NET 4.5 Developer Pack here: <https://learn.microsoft.com/en-gb/dotnet/framework/install/guide-for-developers>. I see this when I attempt to run it: [![enter image description here](https://i.stack.imgur.com/5PtsJ.png)](https://i.stack.imgur.com/5PtsJ.png) Is there anything else I can try?
2022/04/20
[ "https://Stackoverflow.com/questions/71941740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/937440/" ]
Because you might install a higher version of .net framework firstly, so installer might stop you install a lower version of .net framework There is another way can try to fix it without reinstalling. 1. Download [Microsoft.NETFramework.ReferenceAssemblies.net45](https://www.nuget.org/packages/microsoft.netframework.referenceassemblies.net45) package file [![enter image description here](https://i.stack.imgur.com/DaWmb.png)](https://i.stack.imgur.com/DaWmb.png) 2. Modify the file extension name from `microsoft.netframework.referenceassemblies.net45.nupkg` to `microsoft.netframework.referenceassemblies.net45.zip` and Unzip that 3. Copy the files from `build\.NETFramework\v4.5\` to `C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5` 4. Running your project again. **Note** This way was also work for .net4.0 [Microsoft.NETFramework.ReferenceAssemblies.net40](https://www.nuget.org/packages/Microsoft.NETFramework.ReferenceAssemblies.net40/) or other [older version of .net framework](https://www.nuget.org/packages?q=Microsoft.NETFramework.ReferenceAssemblies) which Microsoft might not support in feature
29,268,013
I am having MAJOR usort() issues! :( So basically I want to sort my array by their values. I would like the values to display in this order: Platinum, Gold, Silver, Bronze, Complete, None, Uncomplete. Now I can sort them well, but I would like to preserve their key (is that possible?). here is my code: ``` function compareMedals( $a, $b ) { $aMap = array(1 => 'Platinum', 2 => 'Gold', 3 => 'Silver', 4 => 'Bronze', 5 => 'Complete', 6 => 'None', 7 => 'Uncomplete'); $aValues = array( 1, 2, 3, 4, 5, 6, 7); $a = str_ireplace($aMap, $aValues, $a); $b = str_ireplace($aMap, $aValues, $b); return $a - $b; } usort($list, 'compareMedals'); ``` So is it possible to sort them WHILE preserving their keys? Thank You! :) **EDIT** Array: ``` $array = array("post1" => 'Platinum', "Post2" => "Bronze, "Post3" = > Gold) ``` Should output: ``` "Post1" => 'Platinum', "Post3" => 'Gold', "Post2" => 'Bronze' ``` Yet it is outputting this: ``` "0" => 'Platinum', "1" => 'Gold', "2" => 'Bronze' ```
2015/03/25
[ "https://Stackoverflow.com/questions/29268013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4492877/" ]
Just use `uasort` intead of `usort`. Definition of `uasort` is > > Sort an array with a user-defined comparison function and maintain > index association. > > > There is an example of code with your comparing function and uasort: ``` $list = array('post1' => 'Gold', 'post2' => 'None', 'post3' => 'Platinum'); function compareMedals( $a, $b ) { $aMap = array(1 => 'Platinum', 2 => 'Gold', 3 => 'Silver', 4 => 'Bronze', 5 => 'Complete', 6 => 'None', 7 => 'Uncomplete'); $aValues = array( 1, 2, 3, 4, 5, 6, 7); $a = str_ireplace($aMap, $aValues, $a); $b = str_ireplace($aMap, $aValues, $b); return $a - $b; } uasort($list, 'compareMedals'); print_r($list); ``` That code gives result ``` Array ( [post3] => Platinum [post1] => Gold [post2] => None ) ```
4,563,993
This is a problem that was shared to me by my old high school friend from Japan. While I did solve the problem and show him the solution, he remarked that it was a little complicated and he'd prefer a more "algebraic" approach (not sure what that means). This is why, I'm sharing it here. I'll post my own approach as an answer as well! [![enter image description here](https://i.stack.imgur.com/AkX7P.png)](https://i.stack.imgur.com/AkX7P.png)
2022/10/28
[ "https://math.stackexchange.com/questions/4563993", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1092912/" ]
This is my approach. I'll add an explanation as well! [![enter image description here](https://i.stack.imgur.com/vnSCr.png)](https://i.stack.imgur.com/vnSCr.png) Here's how I go about it: 1.) Label the triangle $\triangle ABC$ and label the internal point $O$. Now, rotate $\triangle BOC$ by $60$ degrees clockwise such that a new triangle $\triangle ADC$ is formed which is congruent to $\triangle BOC$ with $OC=DC=2a$ and $\angle OCD=60$ (can be proven easily). 2.) Connect points $O$ and $D$ via segment $OD$. Notice that because $\angle OCD=60$, and $OC=DC$, it follows that $\triangle OCD$ is equilateral, therefore $OC=DC=OD=2a$. This also means that $\angle ADO=120-60=60$. 3.) Since $AD=a$ and $OD=2a$, as well as $\angle ADO=60$, we can conclude that $\triangle ADO$ is a triangle that is congruent to a "$30-60-90$ triangle" where the hypotenuse has a measure of $2a$ via the SAS property. Therefore, we can infer that $\triangle ADO$ is a "$30-60-90$ triangle" with $\angle OAD=90$ and $\angle AOD=30$. This implies further that length $OA=a\sqrt{3}=9$. Therefore $a=3\sqrt{3}$.
8,314,823
I have the following Linq-to-SQL query. On line #5 I'm trying to get the number of records from my Packages table where the conditions listed in my Where statement are satisfied. I think everything is correct in this code except for line #5. What did I do wrong? ``` var Overage = from s in db.Subscriptions join p in db.Packages on s.UserID equals p.UserID where s.SubscriptionType != "PayAsYouGo" && (s.CancelDate == null || s.CancelDate >= day) && s.StartDate <= day && p.DateReceived <= day && (p.DateShipped == null || p.DateShipped >= day) let AverageBoxSize = (p.Height * p.Length * p.Width) / 1728 let ActiveBoxCount = p.Count() select new { p, AverageBoxSize, ActiveBoxCount, s.Boxes }; ``` The error message is "Unknown method Count() of Foo.Data.Package" **EDIT Here's an example to accompany my question:** Subscription Table: ``` UserID | Boxes 001 5 002 25 003 5 ``` Boxes is the max number each user is permitted under his or her subscription Packages Table ``` UserID | PackageID | Height | Length | Width 001 00001 10 10 10 001 00002 10 10 10 001 00003 20 10 10 003 00004 10 20 20 003 00005 10 10 10 ``` Desired Query Result ``` UserID | Boxes | Box Count | Average Box Size 001 5 3 1,333 003 5 2 2,500 ``` User 002 does not appear because the Where clause excludes that user
2011/11/29
[ "https://Stackoverflow.com/questions/8314823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549273/" ]
I prefer inheritance and events too :-) Try this: ``` class MyEntryElement : EntryElement { public MyEntryElement (string c, string p, string v) : base (c, p, v) { MaxLength = -1; } public int MaxLength { get; set; } static NSString cellKey = new NSString ("MyEntryElement"); protected override NSString CellKey { get { return cellKey; } } protected override UITextField CreateTextField (RectangleF frame) { UITextField tf = base.CreateTextField (frame); tf.ShouldChangeCharacters += delegate (UITextField textField, NSRange range, string replacementString) { if (MaxLength == -1) return true; return textField.Text.Length + replacementString.Length - range.Length <= MaxLength; }; return tf; } } ``` but also read Miguel's warning (edit to my post) here: [MonoTouch.Dialog: Setting Entry Alignment for EntryElement](https://stackoverflow.com/questions/7908991/monotouch-dialog-setting-entry-alignment-for-entryelement)
46,341,399
I have a web application that uses Apache Wicket. After the submitting of a form, I need to intercept the browser's back button, in order to redirect to the initial page, or to a expired page. How can I implement this? I try with ``` @Override protected void setHeaders(WebResponse response) { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store"); } ``` but it doesn't work.
2017/09/21
[ "https://Stackoverflow.com/questions/46341399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7465987/" ]
Interesting question! In the screenshot you've provided, the **Name** column is cut off, so I can't tell what resource is still being served from disk cache. I'll assume that it's a service worker script, based on the description in your "EDIT". The question I'll answer, then, is "how does the browser cache service worker (SW) scripts?" 1. When a SW gets registered, the browser stores the SW script in a separate database in the disk cache. I'll just call this the *SW database*, but note this isn't an official term. Note that if the service worker calls `importScripts()`, those scripts are also stored in the SW database. Also note that when a service worker script gets updated, the browser overwrites the currently-stored script in the SW database with the new script. This is the [Chrome implementation](https://cs.chromium.org/chromium/src/content/browser/service_worker/service_worker_database.h?q=serviceworker+version+database&sq=package:chromium&dr=CSs&l=5), other browsers may do it differently. 1 2. Every time you load the page, the browser makes an invisible request (i.e. you can't see this in DevTools) to see if there are any updates to the service worker script. IMO, DevTools should expose this request, so that developers get a better idea of the SW lifecycle. * If one byte of the script is different, then the browser updates the SW script in the SW database. * If the SW script hasn't changed, the browser just serves the script from the SW database. *This* is the request that you're seeing in DevTools. IMO it's misleading that DevTools describes this request as `(from disk cache)`. Ideally, it should have some other name to indicate that this cache isn't affected by the **Disable Cache** checkbox. So, in this case, you're right: the **Disable cache** checkbox does nothing. If you want to ensure that your cache is completely cleared (including service worker stuff): 1. Go to the [**Clear Storage** pane](https://developers.google.com/web/tools/chrome-devtools/manage-data/local-storage#clear-storage), make sure that all the checkboxes are enabled, and then click **Clear Site Data**. 2. While DevTools is still open, long-press Chrome's **Reload** button, and select **Empty Cache and Hard Reload**. See <https://stackoverflow.com/a/14969509/1669860> for an explanation of these different options. ![Empty cache and hard reload](https://i.stack.imgur.com/nWcug.png) 1 I got this info from Alex Russell, Chrome engineer and co-author of the service worker spec
22,800,104
Is it possible to extract properties of a `HTML tag` using Javascript. For example, I want to know the values present inside with the `<div>` which has `align = "center"`. ``` <div align="center">Hello</div> ``` What I know is: ``` var division=document.querySelectorAll("div"); ``` but it selects the elements between `<div> & </div>` and not the `properties` inside it. I want to use this in the **Greasemonkey script** where I can check for some **malicious properties of a tag** in a website using `Javascript`. Hope I'm clear..!!
2014/04/02
[ "https://Stackoverflow.com/questions/22800104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045807/" ]
You are looking for the [getAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute) function. Which is accessible though the element. You would use it like this. ``` var division = document.querySelectorAll('div') for(var i=0,length=division.length;i < length;i++) { var element = division[i]; var alignData = division.getAttribute('align'); //alignData = center if(alignData === 'center') { console.log('Data Found!'); } } ``` If you're looking to see what attributes are available on the element, these are available though ``` division.attributes ``` [MDN Attributes](https://developer.mozilla.org/en-US/docs/Web/API/Node.attributes) So for instance in your example if you wanted to see if an align property was available you could write this. ``` //Test to see if attribute exists on element if(division.attributes.hasOwnProperty('align')) { //It does! } ```
55,911,955
I try: ``` public interface I { abstract void F(); } ``` I get: > > The modifier 'abstract' is not valid for this item in C# 7.3. Please > use language version 'preview' or greater. > > > However I can find no mention of this feature ie in <https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8> Where can I find the docs for that ? or is the message wrong here ?
2019/04/29
[ "https://Stackoverflow.com/questions/55911955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460084/" ]
C# 8.0 will allow modifiers and default implementations for interface members. You can see discussion [here](https://github.com/dotnet/csharplang/issues/288) and details [here](https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md) However, the `abstract` modifier in an interface method makes zero sense IMO, but it might be available in the C# 8, since other modifiers will be valid as well. You can see the `abstract` is listed in the [allowed modifiers](https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md#modifiers-in-interfaces) > > The syntax for an interface is relaxed to permit modifiers on its members. The following are permitted: private, protected, internal, public, virtual, **abstract**, sealed, static, extern, and partial. > > >
8,706,597
I have a nice default-value check going and client wants to add additional functionality to the `onBlur` event. The default-value check is global and works fine. The new functionality requires some field-specific values be passed to the new function. If it weren't for this, I'd just tack it onto the default-check and be done. My question is can I do this sort of thing and have them both fire? What would be a better way? THE DEFAULT-CHECK ``` $(document.body).getElements('input[type=text],textarea,tel,email').addEvents ({ 'focus' : function(){ if (this.get('value') == this.defaultValue) { this.set('value', ''); } }, 'blur' : function(){ if (this.get('value') == '') { this.set('value', (this.defaultValue)); } } }); ``` ADDED FUNCTIONALITY `<input type='text' id='field_01' value='default data' onBlur='driveData(event, variableForThisField, this.value);'>` The idea is to handle default values as usual, but fire the new function when the field's values are entered. Seems to me one has to fire first, but how? Again, because the values passed a *field* specific, I can't just dump it into the global `default-check` function. I hope this makes sense.
2012/01/03
[ "https://Stackoverflow.com/questions/8706597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/901426/" ]
Just store the custom variable in a [custom data attribute](http://ejohn.org/blog/html-5-data-attributes/). Not technically standards-compliant [in HTML 4], but it works: ``` <input type='text' id='field_01' value='default data' data-customvar="variableForThisField"> $(document.body).getElements('input[type=text],textarea,tel,email').addEvents ({ 'focus' : function(){ if (this.get('value') == this.defaultValue) { this.set('value', ''); } }, 'blur' : function(){ if (this.get('value') == '') { this.set('value', (this.defaultValue)); } else { driveData(this.get('value'), this.get('data-customvar')); } } }); ``` fiddle: <http://jsfiddle.net/QkcxP/6/>
8,405,711
I would like to load an image previously loaded using GDI+ into Direct X; is it possible? I know that I can save the image to disk and then load it using: ``` D3DXLoadSurfaceFromFile ``` But I would like to use ``` D3DXLoadSurfaceFromMemory ``` with the GDI+ image loaded in memory; the GDI+ image is a *GdiPlus*::Image type. I'm using Visual C++ 2010. Thanks in advance. **Update:** ``` using namespace Gdiplus; std::string decodedImage = base64_decode(Base64EncodedImage); DWORD imageSize = decodedImage.length(); HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize); LPVOID pImage = ::GlobalLock(hMem); memcpy(pImage, decodedImage.c_str(), imageSize); IStream* pStream = NULL; ::CreateStreamOnHGlobal(hMem, FALSE, &pStream); Image image(pStream); ``` The above pice of code let me transform an image encoded in base64 (**Base64EncodedImage**) to a GDI+ image; so far so good, next I convert the image as a byte array (**buffer**): ``` int stride = 4 * ((image.GetWidth() + 3) / 4); size_t safeSize = stride * image.GetHeight() * 4 + sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER) + 256 * sizeof(RGBQUAD); HGLOBAL mem = GlobalAlloc(GHND, safeSize); LARGE_INTEGER seekPos = {0}; ULARGE_INTEGER imageSizeEx; HRESULT hr = pStream->Seek(seekPos, STREAM_SEEK_CUR, &imageSizeEx); BYTE* buffer = new BYTE[imageSizeEx.LowPart]; hr = pStream->Seek(seekPos, STREAM_SEEK_SET, 0); hr = pStream->Read(buffer, imageSizeEx.LowPart, 0); ``` As a side note, I can save the byte array to disk as a png image with no loss, and then load it using **D3DXLoadSurfaceFromFile**. Next I create and load the surface: ``` hr = d3ddevex->CreateOffscreenPlainSurface(image.GetWidth(), image.GetHeight(), D3DFMT_X8R8G8B8, D3DPOOL_SYSTEMMEM, &surf, NULL); RECT srcRect; srcRect.left = 0; srcRect.top = 0; srcRect.bottom = image.GetWidth(); srcRect.right = image.GetHeight(); hr = D3DXLoadSurfaceFromMemory(surf, NULL, NULL, buffer, D3DFMT_X8R8G8B8,image.GetWidth(), NULL, &srcRect,D3DX_FILTER_NONE,0); ``` This IS working, BUT the image appears all disordered, colored pixels everywhere but not a "readable" image at all (like if it were a test pattern from an arcade game).
2011/12/06
[ "https://Stackoverflow.com/questions/8405711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007264/" ]
The problem is that WebBrowser has airspace concerns. You can't overlay content on top of a WebBrowser control. For details, see the [WPF Interop page on Airspace](http://msdn.microsoft.com/en-us/library/aa970688%28v=vs.85%29.aspx).
30,265,728
I have eliminated labels on the y axis because only the relative amount is really important. ``` w <- c(34170,24911,20323,14290,9605,7803,7113,6031,5140,4469) plot(1:length(w), w, type="b", xlab="Number of clusters", ylab="Within-cluster variance", main="K=5 eliminates most of the within-cluster variance", cex.main=1.5, cex.lab=1.2, font.main=20, yaxt='n',lab=c(length(w),5,7), # no ticks on y axis, all ticks on x family="Calibri Light") ``` ![cluster plot](https://i.stack.imgur.com/c2ako.png) However, suppressing those tick labels leaves a lot of white space between the y axis label ("Within-cluster variance") and the y axis. Is there a way to nudge it back over? If I somehow set the (invisible) tick labels to go *inside* the axis, would the axis label settles along the axis?
2015/05/15
[ "https://Stackoverflow.com/questions/30265728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2573061/" ]
Try setting `ylab=""` in your `plot` call and use `title` to set the label of the y-axis manually. Using `line` you could adjust the position of the label, e.g.: ``` plot(1:length(w), w, type="b", xlab="Number of clusters", ylab="", main="K=5 eliminates most of the within-cluster variance", cex.main=1.5, cex.lab=1.2, font.main=20, yaxt='n',lab=c(length(w),5,7), # no ticks on y axis, all ticks on x family="Calibri Light") title(ylab="Within-cluster variance", line=0, cex.lab=1.2, family="Calibri Light") ``` ![enter image description here](https://i.stack.imgur.com/6dwlR.png) Please read `?title` for more details.
2,733,830
Sorry - my question title is probably as inept at my attempt to do this. I have the following (well, similar) in a table in a CMS ``` pageID key value 201 title Page 201's title 201 description This is 201 201 author Dave 301 title Page 301's title 301 description This is 301 301 author Bob ``` As you've probably guessed, what I need is a query that will produce: ``` pageID title description author 201 Page 201's title This is page 201 Dave 301 Page 301's title This is page 301 Bob ``` If anybody could help, i'd be eternally grateful - I know this is "please send me the code" but I'm absolutely stuck. Thanks in advance.
2010/04/28
[ "https://Stackoverflow.com/questions/2733830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/311757/" ]
Quick hack may be ``` select a.pageID, a.value as Title, b.value as Description, c.value as Author from Table a left outer join Table b on a.pageID = b.pageID and b.key = 'description' left outer join Table c on a.pageID = c.pageID and c.key = 'author' where a.key = 'title' ``` May not be the best solution, but it may work for you.
67,868,509
When the user typing a text in Textformfield, **onChanged** callback is triggered per character and **onFieldSubmitted** callback is triggered if the user presses enter button after finish the typing. But, I want different behavior than onChanged and onFieldSubmitted. (What I mean by **outside** in the following is background or any other UI element) Does anyone know a way to identify when the user touches **outside** of the Textformfield after finish typing? What I am asking is very similar to the behavior of the onFieldSubmitted. ***But without pressing the enter button***. Thank you!
2021/06/07
[ "https://Stackoverflow.com/questions/67868509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12306259/" ]
As described on Media.Plugin: > > Xamarin.Essentials 1.6 introduced official support for picking/taking > [photos and videos](https://learn.microsoft.com/xamarin/essentials/media-picker?WT.mc_id=friends-0000-jamont) with the new Media Picker API. > > >
563,340
``` \documentclass{article} \usepackage{amsmath} \usepackage{array} \usepackage{mathtools} \begin{document} \renewcommand{\arraystretch}{1.2} \newcommand{\minus}{\scalebox{0.4}[1.0]{$-$}} \[ \begin{bmatrix*}[r] 0& \minus\frac{1}{2} &\frac{1}{2} \\ \minus\frac{1}{2}& 0&\minus\frac{1}{2}\\ \frac{1}{2}& \minus\frac{1}{2}&0 \end{bmatrix*} \] \end{document} ``` [![enter image description here](https://i.stack.imgur.com/1yvlc.png)](https://i.stack.imgur.com/1yvlc.png) How to reduce the number “0” size to fit fraction "1/2"? (reduce height of "0" ?) --- update sample As below photo shows the proportion close to 1/3 [![enter image description here](https://i.stack.imgur.com/Ofr0I.jpg)](https://i.stack.imgur.com/Ofr0I.jpg)
2020/09/19
[ "https://tex.stackexchange.com/questions/563340", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/221248/" ]
I wouldn't reduce the size of the `0` numerals. If you believe that they look too big in relation to the text-style `\frac{1}{2}` expressions, maybe what's *really* needed is to replace the `\frac` terms with their decimal representations -- of course while aligning the numbers on their (explicit or implicit decimal markers. [![enter image description here](https://i.stack.imgur.com/K0r1B.png)](https://i.stack.imgur.com/K0r1B.png) ```none \documentclass{article} \usepackage{mathtools} % for 'bmatrix*' env. \usepackage{siunitx} % for 'S' column type \begin{document} \[ \renewcommand\arraystretch{1.33} \begin{bmatrix*}[r] 0 & -\frac{1}{2} & \frac{1}{2} \\ -\frac{1}{2} & 0 & -\frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & 0 \end{bmatrix*} \] \[ \left[ % note: no need to increase the value of '\arraystretch' \begin{array}{@{} *{3}{S[table-format=-1.1]} @{}} 0 & -0.5 & 0.5 \\ -0.5 & 0 & -0.5\\ 0.5 & -0.5 & 0 \end{array} \right] \] \end{document} ```
144,739
Is it possible to install/register another local server instance in any SqlServer version, besides the default local instance, where only one SqlServer version is installed?
2008/09/27
[ "https://Stackoverflow.com/questions/144739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23087/" ]
Yes, it's possible. I have several combinations in my servers. I have one server that has both SQL Server 2000 and 2005 installed side by side. My desktop at work is a Windows 2003 Server, and I have SQL Server 2005 and 2008 installed side by side. What you want is called a named instance. There will be a screen during the install, where you will be able to give it a name.
19,343
I'm trying to define a Display Suite Code Field which would be responsible for converting a list item key (selected in a dropdown on admin side) into an image on the output side. The field simply assumes the list keys: ``` series1|Series 1 Name series2|Series 2 Name ``` correspond to the images names and the tokenized field definition is as in: ``` <img class="product-series" src="/path/to/image/[node:field-product:field-series].png"/> ``` However what I got after replacement is the label ("Series 1 Name"), instead of the key. Is there a way to force the key replacement? (Yes I know I could drop the Label part, but this would not be admin friendly)
2012/01/10
[ "https://drupal.stackexchange.com/questions/19343", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/1691/" ]
"Promoted to front page" can be used as a views filter. So you could create views based on that (so it displays node teasers that have a certain taxonomy and are "Promoted to front page"). Another simple way to mimic "Promoted to front page" is to add a taxonomy select field to your content types, and then the taxonomy pages would display the specified content. Does this answer your question?
43,633,263
I have a Spring boot project that uses spring-kafka. In this project I've built some event driven components that wrap spring-kafka beans (namely KafkaTemplate and ConcurrentKafkaListenerContainer). I want to make this project a reusable library accross a set of Spring boot applications. But when I add dependency to this library from a spring boot app I get an error at app startup: ``` APPLICATION FAILED TO START Description: Parameter 1 of method kafkaListenerContainerFactory in org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration required a bean of type 'org.springframework.kafka.core.ConsumerFactory' that could not be found. - Bean method 'kafkaConsumerFactory' in 'KafkaAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.kafka.core.ConsumerFactory; SearchStrategy: all) found bean 'kafkaConsumerFactory' Action: Consider revisiting the conditions above or defining a bean of type 'org.springframework.kafka.core.ConsumerFactory' in your configuration. ``` Since I need to autowire a `ConsumerFactory<A, B>` (and not a `ConsumerFactory<Object, Object>`) I create this bean in a configuration class that's annotated with @EnableConfigurationProperties(KafkaProperties.class) All I need is to reuse org.springframework.boot.autoconfigure.kafka.KafkaProperties without other beans being autoconfigured in KafkaAutoConfiguration and KafkaAnnotationDrivenConfiguration. I've tried to put **@EnableAutoConfiguration(exclude = KafkaAutoConfiguration.class)** in my library but this is not preventing applications that depends on my library to trigger the spring-kafka autoconfiguration excluded in the library. How can I specify that I don't want autoconfiguration of some beans (KafkaAutoConfiguration and KafkaAnnotationDrivenConfiguration) in my library but **also in any app that depends on this library**?
2017/04/26
[ "https://Stackoverflow.com/questions/43633263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3484517/" ]
Im found work around to solve this problem by creating AutowireHelper.java and AutowireHelperConfig.java Put it under spring config folder > util > > AutowireHelper.java > > > ``` package com.yourcompany.yourapplicationname.config.util; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Helper class which is able to autowire a specified class. * It holds a static reference to the {@link org.springframework.context.ApplicationContext}. */ public final class AutowireHelper implements ApplicationContextAware { private static final AutowireHelper INSTANCE = new AutowireHelper(); private static ApplicationContext applicationContext; AutowireHelper() { } /** * Tries to autowire the specified instance of the class if one of the specified beans which need to be autowired * are null. * * @param classToAutowire the instance of the class which holds @Autowire annotations * @param beansToAutowireInClass the beans which have the @Autowire annotation in the specified {#classToAutowire} */ public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) { for (Object bean : beansToAutowireInClass) { if (bean == null) { applicationContext.getAutowireCapableBeanFactory().autowireBean(classToAutowire); } } } @Override public void setApplicationContext(final ApplicationContext applicationContext) { AutowireHelper.applicationContext = applicationContext; } /** * @return the singleton instance. */ public static AutowireHelper getInstance() { return INSTANCE; } } ``` > > AutowireHelperConfig.java > > > ``` package com.yourcompany.yourapplicationname.config.util; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * configuration class to create an AutowireHelper bean */ @Configuration public class AutowireHelperConfig { @Bean public AutowireHelper autowireHelper(){ return new AutowireHelper(); } } ``` > > Call service in implement class without getting NULL **Autowire your Service** then call it with **AutowireHelper.autowire(this, this.csvService)** see example below ! > > > ``` public class QueWorker implements MessageListener { @Autowired private CsvService csvService; @Override public void onMessage(Message message) { Map msgGet = (Map) SerializationUtils.deserialize(message.getBody()); Map<String, Object> data = (Map) msgGet.get("data"); ArrayList containerData = new ArrayList((Collection) msgGet.get("containerData")); try { AutowireHelper.autowire(this, this.csvService); csvService.excutePermit(containerData, data); System.out.println(" [x] Received Message'"); } catch (Exception e){ e.printStackTrace(); } finally { System.out.println(" [x] Done Process Message'"); } } } ```
8,495,507
When I draw lines in my program the position is perfect, but when I use those same coordinates for a square or oval they are way off the mark. My code is: ``` g2d.drawRect(one1, one2, two1, two2); g2d.drawOval(one1, one2, two1, two2); ``` And the points are gather by: ``` one1 = (int)e.getX(); one2 = (int)e.getY(); ``` This is a follow on to a [question I previously asked](https://stackoverflow.com/questions/8479432/lines-arent-drawing-exactly-where-i-clicked).
2011/12/13
[ "https://Stackoverflow.com/questions/8495507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639627/" ]
Alright, I got what your problem is. If you see the below image, the way that the parameters taken by oval and sqaure are different from the line. To draw a line --> You will have to specify the starting point and the ending point. Just passing them directly to the Graphics object would do the job for you. However for a Square or Oval, it is different. You first click will grab a point and then you should do some manipulation on what should be the output when you do the second click. The second click should not be considered as a co-ordinate into the drawOval() or drawRect() methods directly. Because the Parameter for these methods are ``` x, y, width, height ``` Whereas you are getting ``` x1, y1 and x2, y2 ``` ![enter image description here](https://i.stack.imgur.com/lyEdU.png) ``` package sof; import java.awt.Color; import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JFrame; public class DrawTest { public static void main(String[] args) { JFrame frame = new JFrame("Draw Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new MyComponent()); frame.setSize(260, 280); frame.setVisible(true); } } class MyComponent extends JComponent { public void paint(Graphics g) { int height = 120; int width = 120; g.setColor(Color.black); g.drawOval(60, 60, width, height); g.drawRect(60, 60, width, height); g.drawLine(0,0,50,50); } } ```
31,164,883
I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array. That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it. I hope you can help me so that I can click on the text and it just runs once **HTML** ``` <label><input type="checkbox" value="XXX" >Active</label> ``` **JavaScript/jQuery** ``` function addOrRemoveBoxes(ID){ if(boxArr.indexOf(ID) != -1){ removeFromArray(ID) } else{ boxArr.push(ID); } } $(".checkBoxes").unbind().click(function() { event.stopPropagation(); addOrRemoveBoxes($(this).find('input').val()); }); ```
2015/07/01
[ "https://Stackoverflow.com/questions/31164883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5068532/" ]
Looks like the AWS Node JS has a bug, in that we need not mention the data type for the keys. I tried this and it worked well ``` { "RequestItems":{ "<TableName>":{ "Keys":[ {"<HashKeyName>":"<HashKeyValue1>", "<RangeKeyName>":"<RangeKeyValue2>"}, {"<HashKeyName>":"<HashKeyValue2>", "<RangeKeyName>":"<RangeKeyValue2>"} ] } } } ```
30,311,640
The error message of gcc 4.9.2 is: ``` could not convert from '<brace-enclosed initializer list>' to 'std::vector<std::pair<float, float> >' ``` of this code: ``` vector<pair<GLfloat, GLfloat>> LightOneColorsPairVec {{0.5f, 0.5f, 0.5f, 1.0f}, {0.0f, 0.0f, 1.0f, 1.0f}}; ``` The code is compiled with 'std=c++11' compiler flag.
2015/05/18
[ "https://Stackoverflow.com/questions/30311640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3163389/" ]
First of all because [`std::pair`](http://en.cppreference.com/w/cpp/utility/pair) doesn't have [constructor](http://en.cppreference.com/w/cpp/utility/pair/pair) that takes a [`std::initializer_list`](http://en.cppreference.com/w/cpp/utility/initializer_list). Secondly because `std::pair` is a *pair*, it only have two values, not four.
59,674,527
Before registering Product Variations (myVariations), I need to check if variations already exist. *One*: I want to register variation 2 and 6. I need to look in the *allVariations* array for this variation that contains the same *product\_detail\_id* *Two*: 2 and 6 would return true because both belong to the same product\_detail\_id (3) 2 and 4 would return false because: 2 belongs to product\_detail\_id 1 4 belongs to product\_detail\_id 2 If possible, I want it to return true or false In the example below, I have 2 and 6 in the myVariations variable, but it could be more than two variations. ``` console.log(allVariations) console.log(myVariations) /* CONSOLE */ [ RowDataPacket { product_detail_id: 1, variation_id: 2 }, RowDataPacket { product_detail_id: 1, variation_id: 5 }, RowDataPacket { product_detail_id: 2, variation_id: 4 }, RowDataPacket { product_detail_id: 2, variation_id: 6 }, RowDataPacket { product_detail_id: 3, variation_id: 2 }, RowDataPacket { product_detail_id: 3, variation_id: 6 } ] // allVariations [ { variation_id: 2 }, { variation_id: 6 } ] // myVariations ```
2020/01/10
[ "https://Stackoverflow.com/questions/59674527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12686390/" ]
Took me a while, probably has a better way but this works as it supposed to: Also works while for more than 2 elements ```js const allVariations = [ { product_detail_id: 1, variation_id: 2 }, { product_detail_id: 1, variation_id: 5 }, { product_detail_id: 2, variation_id: 4 }, { product_detail_id: 2, variation_id: 6 }, { product_detail_id: 3, variation_id: 2 }, { product_detail_id: 3, variation_id: 6 }, { product_detail_id: 4, variation_id: 1 }, { product_detail_id: 4, variation_id: 2 }, { product_detail_id: 4, variation_id: 3 }, ]; const isContain = variation => !!variation.reduce((acc, my) => [...acc, allVariations.filter(all => my.variation_id === all.variation_id)], []) .reduce((acc, cur) => cur.find(e1 => acc && [acc].flat().some(e2 => e1.product_detail_id === e2.product_detail_id))); console.log(isContain([{ variation_id: 2 }, { variation_id: 6 }])); // true console.log(isContain([{ variation_id: 2 }, { variation_id: 4 }])); // false console.log(isContain([{ variation_id: 1 }, { variation_id: 2 }, { variation_id: 3 }])); // true ```
40,349,778
I hava a list of sings: ``` var sings = [",",".",":","!","?"] ``` How do I check if a word contains one of these signs and return it? For example: ``` "But," return "," "Finished." return "." "Questions?" return "?" ```
2016/10/31
[ "https://Stackoverflow.com/questions/40349778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583481/" ]
You could solve that with a regular expression: ```js function match(input) { var regex = /([,\.\:!\?])/; var matches = input.match(regex); return matches ? matches[0] : false; } console.log(match("foo?")); // "?" console.log(match("bar.")); // "." console.log(match("foobar")); // false ```
14,635,594
Is there any extension or feature in VS2010 for previewing in multiple browsers (at the same time) the same as there is in Microsoft Expression Web 4? I know there is the "Default Browser Switcher" extension but this only lets you view one browser at a time. Cheers Will
2013/01/31
[ "https://Stackoverflow.com/questions/14635594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1510736/" ]
When you right click on the page to do the "Browse With...", you can set multiple defaults. Once you have added in multiple browsers to the list, you can CTRL Click each one you want (to highlight multiples). Once the desired ones are highlighted, click "Set as Default". From then on, whenever you hit "Browse" it should open in all your "Default" browsers you highlighted.
891,714
We have application which is using some additional files from one catalog. Right now when some of this file is changed we need to log in to each application container clone repository and copy files to catalog. We want to automate this process without rebuilding/restarting whole application. Is there some native approach how to handle such thing? I was thinking about using docker volume which is use/share by all containers and when is such need to rebuild just volume. Will it work as im expecting without restarting containers which are using this volume? Or maybe there is some better solution for such case eg like NFS volumes?
2018/01/11
[ "https://serverfault.com/questions/891714", "https://serverfault.com", "https://serverfault.com/users/278626/" ]
Have a look at PersistentVolume [Access Modes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes) matrix. What you are looking for is either ROX or RWX support. ROX is more common but you'll need some side process to update the content. RWX give you full access to change content on these volumes from any pod. ROX support is by definition much wider, as you do not need distributed write locking, so if you can handle that (and I think that in your case it is quite probable) that would be the best choice for a shared PV where your changing data can be stored.
1,532,937
I know this is a pretty simple question, but I'm just not getting the textbook... I'm taking a basic CS course and on one of the problems (not an assigned homework problem, just one I'm practicing on), it says that > > on the set of all integers, the relation $x \ne$ y is symmetric but not transitive where $(x,y) \in \Bbb R$. > > > I understand why it's symmetric, but why is it not transitive? I'm thinking it has something to do with the definition of transitive including ALL $a,b,c \in A$, but I'm not sure. I understand transitive in the context of a finite set, but something about applying it to all integers is throwing me off.
2015/11/17
[ "https://math.stackexchange.com/questions/1532937", "https://math.stackexchange.com", "https://math.stackexchange.com/users/264450/" ]
Let $f(x)=x^p$ By convexity $$f(\frac{X+Y}{2})\leq \frac{1}{2} f(X)+\frac{1}{2} f(Y) \implies \frac{(X+Y)^p}{2^p}\leq\frac{1}{2} X^p+\frac{1}{2}Y^p$$ The result follows.
104,851
We started learning about electromagnetism in physics class, and the Right Hand Rule comes in handy as seems easy to use, but I'm curious as to how it actually works. I guess it's more of a math question since I think it just involves solving the cross product of the velocity of the charge and the magnetic field. I don't know anything about cross products, but I searched some things up and it seems that the matrix is has unit vectors in it which determine the directions, so would one have to solve the whole thing to determine the direction of the force on the charge? I know it has to be perpendicular to both of the vectors but that still leaves 2 directions.
2014/03/23
[ "https://physics.stackexchange.com/questions/104851", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/41058/" ]
The formula for the force of a particle due to its magnetic field is $F = q \vec v \times \vec B$. The cross product has the property that its result is always perpendicular to both arguments. Its direction is simply a result of how the cross product function is defined and the sign of electric charge (an electron is defined as negative). It is important to note that the order of the arguments matters as the cross product function is not commutative; generally $ \vec A \times \vec B \neq \vec B \times \vec A$. For vectors the direction will be reversed; for matrices both sides can be wildly different.
16,810,876
I have an Iphone application in which I had 10 tab items in the tab bar. I don't want to add the more button behaviour of the tab bar here. Instead of that **I need to make my tab bar as scrollable**. Can anybody had the idea or links to illustrate this? Can anybody guide me in the right direction?
2013/05/29
[ "https://Stackoverflow.com/questions/16810876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/834925/" ]
But You can not use the `UITabbar`. You need to create custom `UITabbar` that behave the same. Here are links of some projects will help you more. 1. [Infinte Tab Bar](https://www.cocoacontrols.com/controls/infinitabbar) 2. [Scrollable Tab Bar](https://github.com/jasarien/JSScrollableTabBar)
13,155,318
Can somebody please suggest me when would I need a Level-Order Traversal (to solve some practical/real-life scenario)?
2012/10/31
[ "https://Stackoverflow.com/questions/13155318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[Level order traversal](http://en.wikipedia.org/wiki/Tree_traversal#Queue-based_level_order_traversal) is actually a Breadth First Search, which is not recursive by nature. From: <http://en.wikipedia.org/wiki/Breadth-first_search> Breadth-first search can be used to solve many problems in graph theory, for example: * Finding all nodes within one connected component * Copying Collection, Cheney's algorithm * Finding the shortest path between two nodes u and - v (with path length measured by number of edges) * Testing a graph for bipartiteness * (Reverse) Cuthill–McKee mesh numbering * Ford–Fulkerson method for computing the maximum flow in a flow network * Serialization/Deserialization of a binary tree vs serialization in sorted order, allows the tree to be re-constructed in an efficient manner.
275,272
If I build a module with a indexer, is Magento going to run the reindex automatically each night or do I need to create a cronjob for it?
2019/05/20
[ "https://magento.stackexchange.com/questions/275272", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/40598/" ]
If you want the reindex happen automatically, you need to set a cronjob for that. Please refer [here](https://magento.stackexchange.com/questions/269624/how-to-check-whether-the-reindex-working-or-not-in-magento) for detailed explanations:
528,999
I have two servers in a pool with Nginx, PHP5-FPM and Memcached. For some reason, the first server in the pool seems to inexplicably lose about 2GB of RAM. I can't explain where it's going. A reboot gets everything back to normal, but after a few hours the RAM is used again. At first I thought it was down to memcached, but eventually I'd killed every process I could reasonably kill and the memory was not released. Even init 1 did not free the memory. ipcs -m is empty and slabtop looks much the same on this and the server in the pool which is using very little memory. df shows about 360K in tmpfs In case it's relevant, the two servers are nearly identical in that they are both running the same OS at the same level of updates on the same hypervisor (VMWare ESXi 4.1) on different hosts but with identical hardware. The differences are that:- * The first server has an NFS mount. I tried unmounting this and removing the modules but no change to RAM usage * The first server listens for HTTP and HTTPS sites while the second only listens for HTTP. Here's the output of free -m ... ``` total used free shared buffers cached Mem: 3953 3458 494 0 236 475 -/+ buffers/cache: 2746 1206 Swap: 1023 0 1023 ``` Here's /proc/meminfo ... ``` MemTotal: 4048392 kB MemFree: 506576 kB Buffers: 242252 kB Cached: 486796 kB SwapCached: 8 kB Active: 375240 kB Inactive: 369312 kB Active(anon): 12320 kB Inactive(anon): 3596 kB Active(file): 362920 kB Inactive(file): 365716 kB Unevictable: 0 kB Mlocked: 0 kB SwapTotal: 1048572 kB SwapFree: 1048544 kB Dirty: 0 kB Writeback: 0 kB AnonPages: 15544 kB Mapped: 3084 kB Shmem: 412 kB Slab: 94516 kB SReclaimable: 75104 kB SUnreclaim: 19412 kB KernelStack: 632 kB PageTables: 1012 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB CommitLimit: 3072768 kB Committed_AS: 20060 kB VmallocTotal: 34359738367 kB VmallocUsed: 281340 kB VmallocChunk: 34359454584 kB HardwareCorrupted: 0 kB AnonHugePages: 0 kB HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 HugePages_Surp: 0 Hugepagesize: 2048 kB DirectMap4k: 59392 kB DirectMap2M: 4134912 kB ``` Here's the process list at the time ... ``` USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 24336 2160 ? Ss Jul22 0:09 /sbin/init root 2 0.0 0.0 0 0 ? S Jul22 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? S Jul22 0:38 [ksoftirqd/0] root 5 0.0 0.0 0 0 ? S Jul22 0:00 [kworker/u:0] root 6 0.0 0.0 0 0 ? S Jul22 0:04 [migration/0] root 7 0.0 0.0 0 0 ? S Jul22 0:32 [watchdog/0] root 8 0.0 0.0 0 0 ? S Jul22 0:04 [migration/1] root 10 0.0 0.0 0 0 ? S Jul22 0:22 [ksoftirqd/1] root 11 0.0 0.0 0 0 ? S Jul22 0:15 [kworker/0:1] root 12 0.0 0.0 0 0 ? S Jul22 0:31 [watchdog/1] root 13 0.0 0.0 0 0 ? S Jul22 0:04 [migration/2] root 15 0.0 0.0 0 0 ? S Jul22 0:04 [ksoftirqd/2] root 16 0.0 0.0 0 0 ? S Jul22 0:14 [watchdog/2] root 17 0.0 0.0 0 0 ? S Jul22 0:04 [migration/3] root 19 0.0 0.0 0 0 ? S Jul22 0:04 [ksoftirqd/3] root 20 0.0 0.0 0 0 ? S Jul22 0:11 [watchdog/3] root 21 0.0 0.0 0 0 ? S< Jul22 0:00 [cpuset] root 22 0.0 0.0 0 0 ? S< Jul22 0:00 [khelper] root 23 0.0 0.0 0 0 ? S Jul22 0:00 [kdevtmpfs] root 24 0.0 0.0 0 0 ? S< Jul22 0:00 [netns] root 25 0.0 0.0 0 0 ? S Jul22 0:02 [sync_supers] root 26 0.0 0.0 0 0 ? S Jul22 0:21 [kworker/u:1] root 27 0.0 0.0 0 0 ? S Jul22 0:00 [bdi-default] root 28 0.0 0.0 0 0 ? S< Jul22 0:00 [kintegrityd] root 29 0.0 0.0 0 0 ? S< Jul22 0:00 [kblockd] root 30 0.0 0.0 0 0 ? S< Jul22 0:00 [ata_sff] root 31 0.0 0.0 0 0 ? S Jul22 0:00 [khubd] root 32 0.0 0.0 0 0 ? S< Jul22 0:00 [md] root 34 0.0 0.0 0 0 ? S Jul22 0:04 [khungtaskd] root 35 0.0 0.0 0 0 ? S Jul22 0:15 [kswapd0] root 36 0.0 0.0 0 0 ? SN Jul22 0:00 [ksmd] root 37 0.0 0.0 0 0 ? SN Jul22 0:00 [khugepaged] root 38 0.0 0.0 0 0 ? S Jul22 0:00 [fsnotify_mark] root 39 0.0 0.0 0 0 ? S Jul22 0:00 [ecryptfs-kthrea] root 40 0.0 0.0 0 0 ? S< Jul22 0:00 [crypto] root 48 0.0 0.0 0 0 ? S< Jul22 0:00 [kthrotld] root 50 0.0 0.0 0 0 ? S Jul22 2:59 [kworker/1:1] root 51 0.0 0.0 0 0 ? S Jul22 0:00 [scsi_eh_0] root 52 0.0 0.0 0 0 ? S Jul22 0:00 [scsi_eh_1] root 57 0.0 0.0 0 0 ? S Jul22 0:09 [kworker/3:1] root 74 0.0 0.0 0 0 ? S< Jul22 0:00 [devfreq_wq] root 114 0.0 0.0 0 0 ? S Jul22 0:00 [kworker/3:2] root 128 0.0 0.0 0 0 ? S Jul22 0:00 [kworker/1:2] root 139 0.0 0.0 0 0 ? S Jul22 0:00 [kworker/0:2] root 249 0.0 0.0 0 0 ? S< Jul22 0:00 [mpt_poll_0] root 250 0.0 0.0 0 0 ? S< Jul22 0:00 [mpt/0] root 259 0.0 0.0 0 0 ? S Jul22 0:00 [scsi_eh_2] root 273 0.0 0.0 0 0 ? S Jul22 0:20 [jbd2/sda1-8] root 274 0.0 0.0 0 0 ? S< Jul22 0:00 [ext4-dio-unwrit] root 377 0.0 0.0 0 0 ? S Jul22 0:26 [jbd2/sdb1-8] root 378 0.0 0.0 0 0 ? S< Jul22 0:00 [ext4-dio-unwrit] root 421 0.0 0.0 17232 584 ? S Jul22 0:00 upstart-udev-bridge --daemon root 438 0.0 0.0 21412 1176 ? Ss Jul22 0:00 /sbin/udevd --daemon root 446 0.0 0.0 0 0 ? S< Jul22 0:00 [rpciod] root 448 0.0 0.0 0 0 ? S< Jul22 0:00 [nfsiod] root 612 0.0 0.0 21408 772 ? S Jul22 0:00 /sbin/udevd --daemon root 613 0.0 0.0 21728 924 ? S Jul22 0:00 /sbin/udevd --daemon root 700 0.0 0.0 0 0 ? S< Jul22 0:00 [kpsmoused] root 849 0.0 0.0 15188 388 ? S Jul22 0:00 upstart-socket-bridge --daemon root 887 0.0 0.0 0 0 ? S Jul22 0:00 [lockd] root 919 0.0 0.0 14504 952 tty4 Ss+ Jul22 0:00 /sbin/getty -8 38400 tty4 root 922 0.0 0.0 14504 952 tty5 Ss+ Jul22 0:00 /sbin/getty -8 38400 tty5 root 924 0.0 0.0 14504 944 tty2 Ss+ Jul22 0:00 /sbin/getty -8 38400 tty2 root 925 0.0 0.0 14504 944 tty3 Ss+ Jul22 0:00 /sbin/getty -8 38400 tty3 root 930 0.0 0.0 14504 952 tty6 Ss+ Jul22 0:00 /sbin/getty -8 38400 tty6 root 940 0.0 0.0 0 0 ? S Jul22 0:07 [flush-8:0] root 1562 0.0 0.0 58792 1740 tty1 Ss Jul22 0:00 /bin/login -- root 12969 0.0 0.0 0 0 ? S 07:18 0:02 [kworker/2:2] root 30051 0.0 0.0 0 0 ? S 10:13 0:00 [flush-8:16] root 30909 0.0 0.0 0 0 ? S 10:14 0:00 [kworker/2:1] johncc 30921 0.2 0.2 26792 9360 tty1 S 10:17 0:00 -bash root 31089 0.0 0.0 0 0 ? S 10:18 0:00 [kworker/0:0] root 31099 0.0 0.0 42020 1808 tty1 S 10:19 0:00 sudo -i root 31100 0.2 0.1 22596 5168 tty1 S 10:19 0:00 -bash root 31187 0.0 0.0 0 0 ? S 10:19 0:00 [kworker/2:0] root 31219 0.0 0.0 16880 1252 tty1 R+ 10:22 0:00 ps aux root 31220 0.0 0.0 53924 536 tty1 R+ 10:22 0:00 curl -F sprunge=<- http://sprunge.us ``` Can anyone suggest what to try next, or how to debug this problem? I'm at a loss!
2013/08/06
[ "https://serverfault.com/questions/528999", "https://serverfault.com", "https://serverfault.com/users/123168/" ]
The machine is a virtual guest running on **ESXi** hypervisor. What about **memory ballooning**? First of all, I would recommend you to check ESXi/vCenter memory/balloon statistics of this guest. It can happen that the hypervisor asked the guest to "inflate" the balloon in order to allocate some additional memory, e.g. for other running guests. But this requires to have loaded a balloon driver which is available as a kernel module **vmmemctl**. Finally, the obvious question may be whether the guest has vmware tools installed and running as I can't see any related processes in the process list you provided. By the change, wasn't there any **vmware-guestd** process before you started killing them?
40,128,449
Hi I remove my ssl cert from my website. I fixed the database from showing HTTPS and remove the necessary lines from htaccess file . but for now - anyone how trying to enter to my wordpress website get an error message (because the ssl...) How can I forward the user from HTTPS TO HTTP? htaccess below: ``` text/x-generic .htaccess ( ASCII text ) # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # <IfModule mod_rewrite.c> # RewriteEngine On # RewriteCond %{SERVER_PORT} 80 # RewriteRule ^(.*)$ https://www.*****.com/$1 [R,L] # </IfModule> <IfModule mod_headers.c> Header add Access-Control-Allow-Origin "*" </IfModule> Header unset Pragma FileETag None Header unset ETag ## EXPIRES CACHING ## <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType text/html "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 1 month" </IfModule> ## EXPIRES CACHING ## <FilesMatch "\\.(js|css|html|htm|php|xml)$"> SetOutputFilter DEFLATE </FilesMatch> <IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </IfModule> ```
2016/10/19
[ "https://Stackoverflow.com/questions/40128449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7041592/" ]
An approach I use when creating a table where I know all the possible sections is with enums. You create an enum for each of the possible section types: `enum SectionTypes { case sectionA, sectionB, sectionC }` And then create a variable to hold the sections: `var sections: [SectionTypes]` When you have your data ready then you populate sections with the sections that needs to be displayed. I usually also make a method to help get the section: ``` func getSection(forSection: Int) -> SectionTypes { return sections[forSection] } ``` With this in place you can start implementing the common DataSource delegate methods: ``` func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch getSection(forSection: section) { case .sectionA: return 0 //Add the code to get the count of rows for this section case .sectionB: return 0 default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch getSection(forSection: indexPath.section) { case .sectionA: //Get section A cell type and format as your need //etc } } ```
11,460,673
Bellow is a PHP script. I tried to implement the Observer pattern (without MVC structure)... only basic. The error which is encountered has been specified in a comment. First I tried to add User objects to the UsersLibrary repository. There was a error such as User::update() does not exists or something. Why is that error encountered? What fix should be applied and how? ``` interface IObserver { public function update(IObservable $sender); } interface IObservable { public function addObserver(IObserver $obj); public function notify(); } class UsersLibrary implements IObservable { private $container; private $contor; //private $z; public function __construct() {//IObserver $a) { $this->container = array(); $this->contor = 0; echo "<div>[constructing UsersLibrary...]</div>"; $this->addObserver(new Logger()); //$this->z = $a; } public function add($obj) { echo "<div>[adding a new user...]</div>"; $this->container[$this->contor] = $obj; $this->contor++; $this->notify(); } public function get($index) { return $this->container[$index]; } public function addObserver(IObserver $obj) { $this->container[] = $obj; } public function notify() { echo "<div>[notification in progress...]</div>"; foreach($this->container as $temp) { //echo $temp; ################################################################# $temp->update(); //--------ERROR //Fatal Error: Call to a member function update() on a non-object. ################################################################# } //$this->container[0]->update(); //$this->z->update($this); } } class User { private $id; private $name; public function __construct($id, $name) { $this->id = $id; $this->name = $name; } public function getId() { return $this->id; } public function getName() { return $this->name; } } class Logger implements IObserver { public function __construct() { echo "<div>[constructing Logger...]</div>"; } public function update(IObservable $sender) { echo "<div>A new user has been added.</div>"; } } $a = new UsersLibrary(); //new Logger()); //$a->add(new User(1, "DemoUser1")); //$a->add(new User(2, "DemoUser2")); $a->add("Demo"); echo $a->get(0); //echo $a->get(0)->getName(); ```
2012/07/12
[ "https://Stackoverflow.com/questions/11460673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1393475/" ]
Your `User` class is not implementing `interface IObserver` and therefore is not forced to have the method `update()`. You have to instantiate a `new User()` in order to add it to the `UsersLibrary`: ``` $library = new UsersLibrary(); $user = new User(1, "Demo"); $library->add($user); ``` Also, you are mixing **Users** and **Loggers** into your UsersLibrary container. Maybe think about separating the containers for them?
35,336,711
I have this array of objects. ``` [ { geom: '{"type":"Point","coordinates":[-3.81086160022019,50.4619066354793]}' }, { geom: '{"type":"Point","coordinates":[-4.038333333,51.17166667]}' }, { geom: '{"type":"Point","coordinates":[-4.286666667,50.99666667]}' }, { geom: '{"type":"Point","coordinates":[-4.006666667,51.11833333]}' }, { geom: '{"type":"Point","coordinates":[-3.155,50.75333333]}' } ] ``` I want it without the `geom:` leaving me with ``` [ {"type":"Point","coordinates":[-3.81086160022019,50.4619066354793]}, {"type":"Point","coordinates":[-4.038333333,51.17166667]}, {"type":"Point","coordinates":[-4.286666667,50.99666667]}, {"type":"Point","coordinates":[-4.006666667,51.11833333]}, {"type":"Point","coordinates":[-3.155,50.75333333]}] ``` Can this be done with underscore?
2016/02/11
[ "https://Stackoverflow.com/questions/35336711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3346163/" ]
You can do this without `underscore` as well. You just have to loop over array and return `currentObj.geom`. Also, `currentObj.geom` is a string, so you would need `JSON.parse` ```js var a = [ { geom: '{"type":"Point","coordinates":[-3.81086160022019,50.4619066354793]}' }, { geom: '{"type":"Point","coordinates":[-4.038333333,51.17166667]}' }, { geom: '{"type":"Point","coordinates":[-4.286666667,50.99666667]}' }, { geom: '{"type":"Point","coordinates":[-4.006666667,51.11833333]}' }, { geom: '{"type":"Point","coordinates":[-3.155,50.75333333]}' } ] var result = a.map(function(item){ return JSON.parse(item.geom); }); document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>"); ```
1,465,880
This is quoted from Feynman's lectures [The Dependence of Amplitudes on Position](http://www.feynmanlectures.caltech.edu/III_16.html) : > > In Chapter 13 we then proposed that the amplitudes $C(x\_n)$ should vary with time in a way described by the Hamiltonian equation. In our new notation this equation is > $$iℏ\frac{∂C(x\_n)}{∂t}=E\_0C(x\_n)−AC(x\_n+b)−AC(x\_n−b).\tag{16.7}$$ > The last two terms on the right-hand side represent the process in which an electron at atom $(n+1)$ or at atom $(n−1)$ can feed into atom $n.$ > We found that Eq. $(16.7)$ has solutions corresponding to definite energy states, which we wrote as > $$C(x\_n)=e^{−iEt/ℏ}e^{ikx\_n}.\tag{16.8}$$ > For the low-energy states the wavelengths are large ($k$ is small), and the energy is related to $k$ by > $$E=(E\_0−2A)+Ak^2b^2,\tag{16.9}$$ > or, choosing our zero of energy so that $(E\_0−2A)=0$, the energy is given by Eq. $(16.1).$ > Let’s see what might happen if we were to let the lattice spacing $b$ go to zero, keeping the wave number $k$ fixed. If that is all that were to happen the last term in Eq. $(16.9)$ would just go to zero and there would be no physics. But suppose $A$ and $b$ are varied together so that as $b$ goes to zero the product $Ab^2$ is kept constant—using Eq. $(16.2)$ we will write $Ab^2$ as the constant $ℏ^2/2m\_\text{eff}.$ Under these circumstances, Eq. $(16.9)$ would be unchanged, but what would happen to the differential equation $(16.7)$? > First we will rewrite Eq. $(16.7)$ as > $$iℏ\frac{∂C(x\_n)}{∂t}=(E\_0−2A)C(x\_n)+A[2C(x\_n)−C(x\_n+b)−C(x\_n−b)]. \tag{16.10}$$ > For our choice of $E\_0,$ the first term drops out. Next, we can think of a continuous function $C(x)$ that goes smoothly through the proper values $C(x\_n)$ at each $x\_n.$ As the spacing $b$ goes to zero, the points $x\_n$ get closer and closer together, and (if we keep the variation of $C(x)$ fairly smooth) **the quantity in the brackets is just proportional to the second derivative of $C(x).$** We can write—as you can see by making a Taylor expansion of each term—the equality > $$2C(x)−C(x+b)−C(x−b)≈−b^2\frac{∂^2C(x)}{∂x^2}.\tag{16.11}$$ > In the limit, then, as $b$ goes to zero, keeping $b^2A$ equal to $ℏ^2/2m\_\text{eff},$ Eq. $(16.7)$ goes over into > $$i\hbar\frac{∂C(x)}{∂t}=-\frac{\hbar^2}{2m\_{\text{eff}}}\, > \frac{\partial^2C(x)}{\partial x^2}.$$ > > > Can anyone tell me how Feynman equated the terms in the box $2C(x)−C(x+b)−C(x−b)$ with $\frac{\partial^2C(x)}{\partial x^2}?$ How could he tell '\_the quantity in the brackets is just proportional to the second derivative of$C(x)$ \_? How did he use the Taylor expansion here?
2015/10/05
[ "https://math.stackexchange.com/questions/1465880", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
HINT: [Taylor's Theorem](https://en.wikipedia.org/wiki/Taylor%27s_theorem#Statement_of_the_theorem) with the Peano form of the remainder is $$C(x\pm b)=C(x)\pm C'(x)b+\frac12 C''(x)b^2+h(x;b)b^2 \tag 1$$ where $\lim\_{b\to 0}h(x;b)=0$. Now, add the positve and negative terms in $(1)$ and see what happens.
52,521,159
I tried to adapt the 2d platformer character controller from this live session: <https://www.youtube.com/watch?v=wGI2e3Dzk_w&list=PLX2vGYjWbI0SUWwVPCERK88Qw8hpjEGd8> Into a 2d top down character controller. It seemed to work but it is possible to move into colliders with some combination of keys pressed that I couldn't really find out, but it's easy to make it happen. The thing is I don't understand how the collision detection is really working here so I don't know how to fix it. I appreciate if someone can explain how this works. Thanks :) This is how the player is set up: [Player Inspector](https://i.stack.imgur.com/fb6aK.png) **PlayerControllerTopDown2D.cs**: ``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControllerTopDown2D : PhysicsObject2D { public float maxSpeed = 7; private SpriteRenderer spriteRenderer; private Animator animator; private bool facingUp, facingDown, facingLeft, facingRight; void Awake() { spriteRenderer = GetComponent<SpriteRenderer>(); animator = GetComponent<Animator>(); facingUp = true; facingDown = facingLeft = facingRight = false; } protected override void ComputeVelocity() { Vector2 move = Vector2.zero; move.x = Input.GetAxis("Horizontal"); move.y = Input.GetAxis("Vertical"); targetVelocity = move * maxSpeed; if (move.y > minMoveDistance && !facingUp) { clearOthersAndSet(0); // sprite rotation } if (move.y < -minMoveDistance && !facingDown) { clearOthersAndSet(1); // sprite rotation } if (move.x < -minMoveDistance && !facingLeft) { clearOthersAndSet(2); // sprite rotation } if (move.x > minMoveDistance && !facingRight) { clearOthersAndSet(3); // sprite rotation } } void clearOthersAndSet(int x) { switch (x) { case 0; facingUp = true; facingDown = facingLeft = facingRight = false; break; case 1: facingDown = true; facingUp = facingLeft = facingRight = false; break; case 2: facingLeft = true; facingUp = facingDown = facingRight = false; break; case 3: facingRight = true; facingUp = facingDown = facingLeft = false; break; } } } ``` **PhysicsObject2D.cs**: ``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class PhysicsObject2D : MonoBehaviour { protected Rigidbody2D rb2d; protected Vector2 velocity; protected Vector2 targetVelocity; protected ContactFilter2D contactFilter; protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16]; protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16); protected const float minMoveDistance = 0.001f; protected const float shellRadius = 0.01f; protected bool hitSomething = false; void OnEnable() { rb2d = GetComponent<Rigidbody2D>(); } void Start() { contactFilter.useTriggers = false; int layerMask = Physics2D.GetLayerCollisionMask(gameObject.layer); contactFilter.SetLayerMask(layerMask); contactFilter.useLayerMask = true; } void Update() { targetVelocity = Vector2.zero; ComputeVelocity(); } protected virtual void ComputeVelocity() { } void FixedUpdate() { if (hitSomething) { targetVelocity = -targetVelocity * 5; hitSomething = false; } velocity.x = targetVelocity.x; velocity.y = targetVelocity.y; Vector2 deltaPosition = velocity * Time.deltaTime; Vector2 move = Vector2.right * deltaPosition.x; Movement(move, false); move = Vector2.up * deltaPosition.y; Movement(move, true); } void Movement(Vector2 move, bool yMovement) { float distance = move.magnitude; if (distance > minMoveDistance) { int count = rb2d.Cast(move, contactFilter, hitBuffer, distance + shellRadius); if (count > 0) hitSomething = true; else hitSomething = false; hitBufferList.Clear(); for (int i = 0; i < count; i++) { hitBufferList.Add(hitBuffer[i]); } for (int i = 0; i < hitBufferList.Count; i++) { float modifiedDistance = hitBufferList[i].distance - shellRadius; distance = modifiedDistance < distance ? modifiedDistance : distance; } } rb2d.position = rb2d.position + move.normalized * distance; } } ```
2018/09/26
[ "https://Stackoverflow.com/questions/52521159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10419464/" ]
simplifying, unity checks for collision each frame in a synchronized way (for the sake of frame drop compensation), if your object is moving fast (covering a great distance in a short time), there's a chance of your object pass through a wall in that exactly time gap of a collision check and another. as well stated and tested on this [thread](https://forum.unity.com/threads/collision-detection-discrete-vs-continuous-vs-continuous-dynamic.291818/). if your object is passing through a object, the first thing you want to change is the **collision detection mode**, when the mode is set to discrete, you're saying that the object is checking for collision in a lower rate.[![enter image description here](https://i.stack.imgur.com/ElHDR.jpg)](https://i.stack.imgur.com/ElHDR.jpg) and when you set it to continuous, the object checks for collision more frequently. [![enter image description here](https://i.stack.imgur.com/2gYDf.jpg)](https://i.stack.imgur.com/2gYDf.jpg) so probably setting detection mode from "discrete" to continuous should be enough to solve your problem.
34,633,844
I need to create a XAML `textbox` immediately after another `textbox` using code-behind. Maybe something like this: Before ``` <StackPanel> <TextBox Name="TextBox1"/> <TextBox Name="TextBox2"/> <TextBox Name="TextBox3"/> </StackPanel> ``` After ``` <StackPanel> <TextBox Name="TextBox1"/> <TextBox Name="TextBox2"/> <TextBox Name="InsertedTextBox"/> <!--This textbox was inserted after 'TextBox2'--> <TextBox Name="TextBox3"/> </StackPanel> ``` I have the name of the `textbox` I wish to insert the other `textbox` after. May I know how I can insert a `textbox` after another `textbox` which I know the name of? Note: I am programming for Universal Windows. Thanks in advance.
2016/01/06
[ "https://Stackoverflow.com/questions/34633844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719584/" ]
You need to name the `StackPanel` to reference it in code, and you need the index of the preceding `TextBox`: ``` var index = this.stackPanel1.Children.IndexOf(TextBox2); this.stackPanel1.Children.Insert(index + 1, new TextBox { Name = "InsertedTextBox" }); ```
17,266,818
Trying to split the `http://` from `http://url.com/xxyjz.jpg` with the following: ``` var imgUrl = val['url'].split(/(^http:\/\/)/); ``` And, even though I can get my desired result with the code above, I get some extra parameters that I would like not to have. Output: > > ["", "http://", "url.com/xxyjz.jpg"] > > > So, the question is: What am I doing wrong that I get the extra `""`, besides the `"http://"`?
2013/06/24
[ "https://Stackoverflow.com/questions/17266818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971392/" ]
You could use `match` instead of `split`: ``` var matches = str.match(/(http:\/\/)(.*)/).slice(1); ``` That will give you the array you want.
433,810
I have trouble displaying an abbreviation nicely. Removing largesmallcaps is a small improvement, but looks really bad in full document. I want normal numbers in the rest of the document. How can I make the zero appear the correct size and differentiate it nicely from the O? MWE: ``` \documentclass{article} \usepackage[largesmallcaps]{kpfonts} \begin{document} 1234567890 \oldstylenums{1234567890} \textsc{lod}\oldstylenums{0} \textsc{lod0} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/r0JDT.png)](https://i.stack.imgur.com/r0JDT.png)
2018/05/28
[ "https://tex.stackexchange.com/questions/433810", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/81219/" ]
This can be achieved by combining `multirow` from the eponymous package with `rotatebox` from the `graphicx` package as follows: ``` \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{booktabs} \usepackage{graphicx} \usepackage{multirow} \begin{document} \begin{table}[!ht] \centering \begin{tabular}{lllll} \toprule & & Surveillance de & Fonctionnalité & Feedback \\ \midrule \rotatebox[origin=c]{90}{AVQ} &Verre & Indépendance lors d'AVQs & & \\ \midrule \multirow{2}{*}{\rotatebox[origin=c]{90}{Main}} &Osselet & Dextérité & & \\ &Cube & Préhension globale de la main & & \\ \midrule \multirow{2}{*}{\rotatebox[origin=c]{90}{Bras}} &Bracelet & Activité motrice du bras & & \\ &Pull-over & Extension du coude & & \\ \bottomrule \end{tabular} \caption{Récapitulatif des fonctionnalités de chaque objet} \label{recap_fonctionnalites} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/XiP3S.png)](https://i.stack.imgur.com/XiP3S.png) Please note that I have additionally removed the vertical line as `booktabs` horizontal rules are not intended to be used in combination with vertical lines.
13,074,250
I am trying to display the correct button and link depending on what device the user browses to a page on. If android display android app store button if ios display apple store button. I cannot seem to get it to swap at all even though im making the function default to swap it from android to apple button. Here is the code: ``` <html> <head> <script type="text/javascript"> var uagent = navigator.userAgent.toLowerCase(); var apple = "/images/ios.jpg"; var android = "/images/android.jpg" function DetectDevice() { var but = document.getElementById("AppButton"); if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) { toswap.src = apple; alert("apple"); } else if(useragent.search("android")) { toswap.src = android; alert("android"); } but.src = apple; } DetectDevice(); </script> <title>Device Detection</title> </head> <div id="butttons"> <img src="images/android.jpg" name = "AppButton" id="AppButton"/> </div> ```
2012/10/25
[ "https://Stackoverflow.com/questions/13074250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1775052/" ]
Keep in mind, I do NOT program gmp, but a tail-dynamic buffer in a struct is usually implemented something like this (adapted to how I think you want to use it): ``` typedef struct { size_t length; //length of the array size_t numbits; //number of bits allocated per val in vals mpz_t vals[1]; //flexible array to hold some number of mpz_t array } CoolArray; ``` Allocation strategy, knowing the the number of values and bit-depth, would be: ``` CoolArray* allocArray(size_t length, size_t numbits) { CoolArray *p = malloc(sizeof(*p) + sizeof(mpz_t)*length); p->length = length; p->numbits = numbits; mpz_array_init(p->vals, length, numbits); return p; } ``` Freeing it (just a wrapper for free(), but you may need to do some gmp-cleanup I'm unfamiliar with): ``` void freeArray(CoolArray **pp) { if (*pp) { free(*pp); *pp = NULL; } } ``` Using it: ``` CoolArray *pca = allocArray(length, numbits); ``` Freeing it when done: ``` freeArray(&pca); ``` These are just ideas, but maybe you can get something from them.
112,536
I found myself in an interesting puzzle. Here is the simplified version: I have a flight from A to C, connecting through B. I decide that from B I actually want to go to D, so I buy a separate ticket for that journey\*. The B-C and B-D flights are around the same time and with the same airline\*\*. Will there be a problem with checking in to B-D, given that at that point I will already be checked in on their system to the whole trip A-C, including the leg B-C? No luggage is involved. Some extra information: (\*) Every leg is relatively short within Europe, on economy fare. In particular, changing the A-C ticket to A-D would likely be pricier. (\*\*) The B-D trip could be done with another airline. Does this change the answer?
2018/04/06
[ "https://travel.stackexchange.com/questions/112536", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/62048/" ]
**No**, there won't be any problem. Separate bookings are separate bookings and don't affect each other, even on the same airline. I will note, however, that if you make a habit of buying A-B-C tickets and getting off at B, and give your frequent flyer number every time, the airline will eventually get grumpy. However, doing this once or twice is fine.
18,456,454
we have a client application that plays flash files (.swf). This works on all other mobiles except iphone as Apple doesn't support Flash. Is there any workaround to play these flash files in iphone using HTML5 or any other tweaking? Since there aren't any answers to this question recently, I am submiting this question.
2013/08/27
[ "https://Stackoverflow.com/questions/18456454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2682102/" ]
No, there is no way to display a Flash file (SWF) in the iPhone browser. If you have access to the source of the Flash files in the application, it may be possible to export them as HTML5 from the Flash builder. There's no way to do this conversion just from the SWFs, though. As an aside: your application won't work on many newer smartphones either - under Android, Adobe has dropped support for the Flash plugin on current versions of the OS, and it's not supported at all on current versions of Windows Mobile or Blackberry OS. Sites which depend on Flash content are effectively unusable on mobile at this point.
32,785,066
I'm trying to read some French character from the file but some symbols comes if letter contains à é è. Can anyone guide me how to get actual character of the file. Here is my main method ``` public static void main(String args[]) throws IOException { char current,org; //String strPath = "C:/Documents and Settings/tidh/Desktop/BB/hhItem01_2.txt"; String strPath = "C:/Documents and Settings/tidh/Desktop/hhItem01_1.txt"; InputStream fis; fis = new BufferedInputStream(new FileInputStream(strPath)); while (fis.available() > 0) { current= (char) fis.read(); // to read character // from file int ascii = (int) current; // to get ascii for the // character org = (char) (ascii); System.out.println(org); } ```
2015/09/25
[ "https://Stackoverflow.com/questions/32785066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4485283/" ]
You're trying to read UTF-8 character actually using ASCII. Here's an example of how to implement your feature: ``` public class Test { private static final FILE_PATH = "c:\\temp\\test.txt"; public static void main(String[] args){ try { File fileDir = new File(FILE_PATH); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(fileDir), "UTF8")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } } } ``` Reference: [How to read UTF-8 encoded data from a file](https://www.mkyong.com/java/how-to-read-utf-8-encoded-data-from-a-file-java/)
14,639,130
My JSON data is like ``` { "Brand":["EM-03","TORRES"], "Price":["5.00000","10.00000","15.00000"], "Country":["US","SG"] } ``` I want to loop that JSON data to get ``` Brand = EM-03 - TORRES Price = 5.00000 - 10.00000 - 15.00000 Country = US - SG ```
2013/02/01
[ "https://Stackoverflow.com/questions/14639130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1474420/" ]
With [`$.each`](http://api.jquery.com/jQuery.each/) ``` $.each(data, function(key, value){ console.log(value); }); ```
358,755
**I'm pretty sure this happens to someone out there now and then:** You've read a question, done the work with writing a pretty decent answer, at least you think you have, then you find some detail in the question, either edited in at a later time or maybe not clearly defined in the title or pointed out in the context in the first place, that makes your answer either get down-voted because it isn't the most accurate or relevant answer or just kinda misplaced because it answers what you *thought* was asked, but then again, meh... So, it isn't directly wrong, but neither a good answer for the question when you realize that you misread the whole thing. Could be that something got lost in internal translation (like inside your head, for non-native English speaking folks) or just poorly written. Could be you rushed for a bounty, at 4 a.m after a couple of beers, whatever. What is the best approach in such cases? Should I (or could I) delete my answer? What are the rules for if / when I can delete an answer? Come to think of it, I really don't know the rules for if / when I can delete my own questions either... Is this written somewhere? Does deleting an answer impact anything other than what it sounds like, e.g. the answer is Poof! gone or does it cause any other reactions / rep changes? Is it considered bad practice to do so, if at all possible?
2020/12/26
[ "https://meta.stackexchange.com/questions/358755", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/201397/" ]
It can respond to another answer, but you still need to give at least a partial answer to the question. Thus, answering like this is okay: > > My experience about @X's answer (link) is negative, although I used a newer version of (...). Instead, what I did is (explanation), and now it works. > > > [(example)](https://stackoverflow.com/a/39034132/1783163) This answer is not okay, because it is a comment: > > @X's answer does not work. > > > The important thing is that the main focus of the answer should be at least a partial answer to the question on the top. --- Users starting with > > It is not an answer, but... > > > have typically two options: 1. Yes, it is an (at least partial) answer. These users typically think that giving a step-by-step guide is a requirement; the requirement is that at least a part of the question on the top should be answered. Users can get the supportive comment and editing out the "not an answer" part (superficial future reviewers might flag it for deletion without enough thinking on the details). 2. It is really not an answer. Some personalised advice, particularly in the case of newbies is still helpful, anyways flag as NAA (or for mod comment conversion if it is worthwhile). --- Who decides: mostly, the reviewers. I would say that about 80% of the cases are obvious (in the VLQ queue). For the border cases, this is why it requires 2k (or 1k on beta) the VLQ queue. --- Posting answer in comments: I do this if I am not sure or if I would flag my answer as VLQ/NAA. Because comments are second-grade citizens, if I write a bad comment, it will be at most deleted. I think the reason of others is the same. If you are the OP, and one or more comment has actually the worth of an answer, then you could ask the commenter(s) to do it for an upvote and accept. If they remain inactive, you can summarize them in a self-answer ([example1](https://android.stackexchange.com/a/231985/50837), [example2](https://meta.stackexchange.com/a/296950/259412)). This is not forbidden, although you should mention your source(s) to avoid plagiarism.
40,059
I would like to say in German, > > I would love to talk sometime. > > > So far I have this, > > Ich würde gerne mal reden. > > > Is *reden* the right verb here? How would you say it?
2017/11/05
[ "https://german.stackexchange.com/questions/40059", "https://german.stackexchange.com", "https://german.stackexchange.com/users/21516/" ]
Your translation works. Another possibility would be > > Ich würde mich gerne mal mit dir unterhalten > > > Which is a way to ask for a conversation some time in the future. The “dir“ is used when talking to a friend or close co-worker while it can be exchanged with “Ihnen“ to suit a more formal setting.
25,406,330
I have a star image in my activity. Now when the user clicks on that star image, that image should change to **ON Star image**, Same as favorite star image. For this I use the following code : ``` ImageView star=(ImageView)findViewById(R.id.favorite); star.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN) { star.setImageResource(android.R.drawable.star_big_on); } return false; } }); ``` But I am unable to change that image. Please suggest me.
2014/08/20
[ "https://Stackoverflow.com/questions/25406330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3898113/" ]
Use an OnClickListener instead of an OnTouchListener. ``` ImageView star=(ImageView)findViewById(R.id.favorite); star.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { star.setImageResource(android.R.drawable.star_big_on); } }); ``` Your code should look like that. You'll need to make the ImageView clickable as well either in XML (android:clickable="true") or in code (star.setClickable(true);). Conversely, you could use an ImageButton and set the image as the ImageButton's background. This way you don't have to worry about setting the View to be clickable, as it is inherently clickable.
43,278,020
In the success part of my ajax each result gets put into columns. What I am trying to achive is every 4 columns it will create a new row. Question: On success part of ajax how to make it so every after every 4 columns will create a new row? ``` <script type="text/javascript"> $("#select_category").on('keyup', function(e) { $.ajax({ type: "POST", url: "<?php echo base_url('questions/displaycategories');?>", data: { category: $("#select_category").val() }, dataType: "json", success: function(json){ list = ''; list += '<div class="row">'; $.each(json['categories'], function(key, value ) { list += '<div class="col-sm-3">'; list += value['name']; list += '</div>'; }); list += '</div>'; $('.category-box').html(list); } }); }); </script> ```
2017/04/07
[ "https://Stackoverflow.com/questions/43278020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419336/" ]
Remove one line from your css ``` tbody { height: 100%; display: block;//<--- Remove this line width: 100%; overflow-y: auto; } ```
6,110,068
**Assuming an invariant culture**, is it possible to define a different group separator in the format - than the comma? ``` Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Console.WriteLine(String.Format("{0:#,##0}", 2295)); ``` Output: ``` 2,295 ``` Desired output: ``` 2.295 ``` The invariant culture is a requirement because currencies from many different locales are being formatted with format strings, that have been user defined. Ie for Denmark they have defined the price format to be "{0:0},-", while for Ireland it might be "€{0:#,##0}".
2011/05/24
[ "https://Stackoverflow.com/questions/6110068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77884/" ]
When you have different format strings, this does not mean that you have to use InvariantCulture. If you have a format string for germany e.g. you format this string using the Culture("de-de"): ``` String.Format(CultureInfo.GetCultureInfo( "de-de" ), "{0:0},-", 2295) //will result in 2.295,- String.Format(CultureInfo.GetCultureInfo( "en-us" ), "{0:0},-", 2295) //will result in 2,295,- ``` Alternatively you can specify your custom [number format info](http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo%28v=VS.100%29.aspx): ``` NumberFormatInfo nfi = new NumberFormatInfo( ) { CurrencyGroupSeparator = ":" }; String.Format(nfi, "{0:0},-", 2295) //will result in 2:295,- ```
601,834
I need to terminate an unused op amp and plan to use the [recommended circuit](https://youtu.be/gwQiFuckMz0?t=727) below with +3.3V. How do I choose the resistor values? The op amp I'm using is the [MCP6002](https://www.microchip.com/en-us/product/MCP6002) ([datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/MCP6001-1R-1U-2-4-1-MHz-Low-Power-Op-Amp-DS20001733L.pdf)). [![](https://i.stack.imgur.com/gY6Ji.png)](https://i.stack.imgur.com/gY6Ji.png) I understand too low allows a lot of current, wasting power. Too high and it's not enough current to drive the load. In this case the load is just the op amp. Here is where I get lost. What determines a reasonable but low amount of current to put through the op amp? `Output Short-Circuit Current` is +/-6mA @ 1.8V, so something like < 3mA @ 3.3V would be very safe for the high end, but I want the low end. 10K ohms for both resistors would be 0.33mA. I guess that would be fine, but can I go lower?
2021/12/26
[ "https://electronics.stackexchange.com/questions/601834", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/303644/" ]
The op-amp has rail-to-rail input capabilities hence, you can tie the unused input to either: - * 3V3 or * 0 volts Noting this from the DS: - [![enter image description here](https://i.stack.imgur.com/T7p9M.png)](https://i.stack.imgur.com/T7p9M.png) I'd probably tie IN+ to 0 volts. > > *What determines a reasonable but low amount of current to put through > the op amp?* > > > Well, the graph above gives some indication but, unfortunately, the DS doesn't give an equivalent graph when the input is close to the positive rail. If you insist on using a potential divider, take note that the input bias current is about 1 nA over temperature and, if your resistors were 1 MΩ roughly, that would mean a 1 mV drop across them so, I'd go as high as possible because it won't really matter that much.
6,598,247
I made a survey and gave to certain user Contribute permission to answer the survey. Appears that even if you give to user "Read" permissions Action bar is still available. Is there any chance to hide "Action bar" for limited permission users?
2011/07/06
[ "https://Stackoverflow.com/questions/6598247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/671141/" ]
Try using the `onbeforeunload()` function or jQuery [unload()](http://api.jquery.com/unload/)
46,182,318
I am trying to make a simple 'Simon Game'. I am currently stuck trying to add a class 'on' to a div for one second, then remove that class for the same amount of time. So I have four divs that I am blinking on and off depending on a sequence of numbers, e.g. `[0, 1, 2, 3]`. This would blink `div[0]` on for one second and off for one second then move to `div[1]`, on and off and so on. Here is my function ``` /** * sequence => array [0, 1, 2, 3] * speed => int 1000 (one second) */ playSequence: function(sequence, speed){ var self = this; // removes class 'on' view.turnOffPads(); setTimeout(function(){ // adds the 'on' class to a specific div view.lightUpPad(model.startupSequence[model.count]); }, speed / 2); setTimeout(function(){ model.count++; // keeps track of the iterations if (model.count < sequence.length) { // if we are still iterating self.playSequence(sequence, speed); // light up the next div } else { model.count = 0; // set back to zero } }, speed); }, ``` The problem with this is that I am using two setTimeout functions with one another and although it works I am wondering if there is a better way. If you look I am using a count variable in my model object to keep track of iterations. Here is my full javascript app so far... ``` $(function(){ var model = { on: false, strictMode: false, startupSequence: [0, 1, 2, 3, 3, 3, 2, 1, 0, 3, 2, 1, 0, 2, 1, 3], score: 0, sequence: [], count: 0, } var controller = { init: function(){ view.cacheDOM(); view.bindEvents(); }, getSequence: function(){ // get a random number from one to 4 var random = Math.floor(Math.random() * 4); // push it to the sequence array model.sequence.push(random); console.log(model.sequence); // play it this.playSequence(model.sequence); }, /** * sequence => array [0, 1, 2, 3] * speed => int 1000 (one second) */ playSequence: function(sequence, speed){ console.log(sequence.length); var self = this; view.turnOffPads(); setTimeout(function(){ view.lightUpPad(model.startupSequence[model.count]); }, speed / 2); setTimeout(function(){ model.count++; if (model.count < sequence.length) { self.playSequence(sequence, speed); } else { model.count = 0; } }, speed); // view.turnOffPads(); }, } var view = { cacheDOM: function(){ this.$round = $('#round'); this.$start = $('#start'); this.$strict = $('#strict'); this.$pad = $('.pad'); this.$padArray = document.getElementsByClassName('pad'); }, bindEvents: function(){ this.$start .change(this.start.bind(this)); this.$strict.change(this.setStrictMode.bind(this)); }, start: function(){ // turn on pads if (model.on) { this.$pad.removeClass('on'); this.$round.text('--'); model.on = false; // reset everything } else { this.$round.text(model.score); model.on = true; controller.playSequence(model.startupSequence, 100) // controller.getSequence(); } }, lightUpPad: function(i){ $(this.$padArray[i]).addClass('on'); }, turnOffPads: function(){ this.$pad.removeClass('on'); }, setStrictMode: function(){ if (model.strictMode) { model.strictMode = false; } else { model.strictMode = true; } } } controller.init(); }); ``` Is there a cleaner way to add a class, and then remove a class?
2017/09/12
[ "https://Stackoverflow.com/questions/46182318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4030469/" ]
I think you could turn a list of buttons into a sequence of commands. Then you could use a single `setInterval` to play commands until it runs out of commands. The `setInterval` could use 1 second intervals if you want on and off to take just as long, but you could also set it to a little faster to easily allow for different durations. The example below isn't really based on your code, but just to illustrate the idea. It starts (at the button of the code) with an array of buttons pressed. Those are passed to `getSequence`. This will return an array of commands, in this case simply the color of the button to switch on, so a sequence could be red,red,red,red,'','','','' to have red light up for 4 'intervals', and then switch it off for 4 'intervals'. This way you could create complicates sequences, and with minor adjustments you could even light up multiple buttons simultaneously. The interval in the example is set to 1/10 of a second. Each color plays for 10 steps (= 1 second), and each pause plays for 5 steps (= .5 second). In the console you see the basis array of buttons/colors to play, followed by the more elaborate sequence that is played. ```js // The play function plays a sequence of commands function play(sequence) { var index = 0; var lastid = ''; var timer = setInterval(function(){ // End the timer when at the end of the array if (++index >= sequence.length) { clearInterval(timer); return; } var newid = sequence[index]; if (lastid != newid) { // Something has changed. Check and act. if (lastid != '') { // The last id was set, so lets switch that off first. document.getElementById(lastid).classList.remove('on'); console.log('--- ' + lastid + ' off'); } if (newid != '') { // New id is set, switch it on document.getElementById(newid).classList.add('on'); console.log('+++ ' + newid + ' on'); } lastid = newid; } }, 100); } // generateSequence takes a list of buttons and converts them to a // sequence of color/off commands. function generateSequence(buttons) { var result = []; for (var b = 0; b < buttons.length; b++) { // 'On' for 10 counts for (var i = 0; i < 10; i++) { result.push(buttons[b]); } if (b+1 < buttons.length) { // 'Off' for 5 counts for (var i = 0; i < 5; i++) { result.push(''); } } } // One 'off' at the end result.push(''); return result; } var buttons = ['red', 'green', 'red', 'yellow', 'yellow', 'blue']; console.log(buttons); var sequence = generateSequence(buttons); console.log(sequence); play(sequence); ``` ```css div.button { width: 100px; height: 100px; opacity: .5; display: inline-block; } div.button.on { opacity: 1; } #red { background-color: red; } #green { background-color: green; } #yellow { background-color: yellow; } #blue { background-color: blue; } ``` ```html <div id="red" class="button"></div> <div id="green" class="button"></div> <div id="yellow" class="button"></div> <div id="blue" class="button"></div> ```
7,188,989
> > **Possible Duplicate:** > > [Set array key as string not int?](https://stackoverflow.com/questions/3231318/set-array-key-as-string-not-int) > > > I know you can do something like `$array["string"]` in php but can you also do something like this in C# instead of using arrays with numbers?
2011/08/25
[ "https://Stackoverflow.com/questions/7188989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911848/" ]
Arrays in PHP are in reality more like dictionaries in C#. So yes, you can do this, using a [**`Dictionary<string, YourValueType>`**](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx): ``` var dict = new Dictionary<string, int>(); dict["hello"] = 42; dict["world"] = 12; ```
48,273,719
I'm new to programming. Here is the code I try to use: ``` <div style="width: 300px;"> texttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttext </div> ``` So, the problem is the text won't break after `300px`. Why and how can I fix that?
2018/01/16
[ "https://Stackoverflow.com/questions/48273719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9222224/" ]
this also work ```css div{ word-wrap: break-word; width: 300px; } ``` ```html <div> texttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttext </div> ```
73,901,048
Very simple, I want to round my 'base\_price' and 'entry' with the precision, here 0.00001. It doesn't work because it converts it to a scientific number. How do I do this; I have been stuck for 1 hour. Some post says to use `output="{:.9f}".format(num)` but it adds some zero after the last 1. It work with `precision = str(0.0001)` but start from 4 zeros after the dot, it change to scientific numbers and `digit = precision[::-1].find('.')` doesn't work with scientific numbers. ``` precision = str(0.00001) #5 decimals after the dot print(precision) base_price=0.0314858333 entry=0.031525 digit = precision[::-1].find('.') entry_price = float(round(float(entry), digit)) base_price = float(round(float(base_price), digit)) print(entry_price,base_price) ``` Expected result: ``` base_price=0.03148 #5 decimals after the dot entry=0.03152 #5 decimals after the dot ```
2022/09/29
[ "https://Stackoverflow.com/questions/73901048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18578687/" ]
If you want to round to a precision given by a variable, you can just do ```py precision = 0.00001 entry = 0.031525 entry_price = round(entry / precision) * precision ```
42,339,632
I am not able to understand the forced need of permission check in my code. Moreover, even after doing that, the location is null. This is the code of my onCreate method: Please help!! ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); provider = locationManager.getBestProvider(new Criteria(), false); if(provider.equals(null)){ Log.i("provdier","prob"); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } Location location = locationManager.getLastKnownLocation(provider); if (location != null) { Log.i("location info", "achieved"); textView.setText("Achieved"); } else { Log.i("location info", "failed"); textView.setText("Failed"); } } ```
2017/02/20
[ "https://Stackoverflow.com/questions/42339632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7591842/" ]
In D3 4.0 the [callback function for the `.on()` method is passed 3 arguments](https://github.com/d3/d3-selection#handling-events): the current datum (d), the current index (i), and the current group (nodes). Within the mouseover callback, you can `selectAll("rect")`, and filter out items which are in the current group (`node`). With this selection, you then set opacity to 0.5. On mouseout, you just need to set all opacity back to 1.0. The pertinent code is: ``` ... .on('mouseover', function(d, i, node) { d3.selectAll("rect") .filter(function (x) { return !isInArray(this, node)}) .attr('opacity', 0.5); } ) .on('mouseout', function() { d3.selectAll("rect").attr('opacity', 1.0); }); ``` with a small helper function to check if a value is present in an array (array of DOM elements in our case): ``` function isInArray(value, array) { return array.indexOf(value) > -1; } ``` The full code in context (given your linked example): ``` g.append("g") .selectAll("g") .data(data) .enter().append("g") .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; }) .selectAll("rect") .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); }) .enter().append("rect") .attr("x", function(d) { return x1(d.key); }) .attr("y", function(d) { return y(d.value); }) .attr("width", x1.bandwidth()) .attr("height", function(d) { return height - y(d.value); }) .attr("fill", function(d) { return z(d.key); }) .on('mouseover', function(d, i, node) { d3.selectAll("rect") .filter(function (x) { return !isInArray(this, node)}) .attr('opacity', 0.5); } ) .on('mouseout', function() { d3.selectAll("rect").attr('opacity', 1.0); }); ```
12,863,043
I've looking looking at this with no success so far. I need a regular expression that returns me the string after the one in a phone number. Let me give you the perfect example: phone number (in exact format i need): 15063217711 return i need: 5063217711 --> so the FIRST char if its a 1 is removed. I need a regular expression that matches a 1 only at the BEGINNING of the string and then returns the rest of the phone number. By the way im using objective C but it should not make much difference.
2012/10/12
[ "https://Stackoverflow.com/questions/12863043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/835883/" ]
For a playlist DEFINITELY the database. The preferences is just a simple key-value pair.
55,763,548
I have following docker file. ``` MAINTANER Your Name "youremail@domain.tld" RUN apt-get update -y && \ apt-get install -y python-pip python-dev # We copy just the requirements.txt first to leverage Docker cache COPY ./requirements.txt /app/requirements.txt WORKDIR /app RUN pip install -r requirements.txt COPY . /app ENTRYPOINT [ "python" ] CMD [ "app.py" ] ``` There is one file that I want to run even before app.py file runs. How can I achieve that? I don't want to put code inside app.py.
2019/04/19
[ "https://Stackoverflow.com/questions/55763548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972924/" ]
One solution could be to use a docker-entrypoint.sh script. Basically that entrypoint would allow you to define a set of commands to run to initialize your program. For example, I could create the following docker-entrypoint.sh: ``` #!/bin/bash set -e if [ "$1" = 'app' ]; then sh /run-my-other-file.sh exec python app.py fi exec "$@" ``` And I would use it as so in my Dockerfile: ``` FROM alpine COPY ./docker-entrypoint.sh / ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["app"] ``` There is a lot of articles and examples online about docker-entrypoints. You should give it a quick search I am sure you will find a lot of interesting examples that are used by famous production grade containers.
465,096
Hello we have an SQL server application running over a low bandwith connection. We use ADO.NET. I was wondering if anybody has any tips on minimizing traffic over the channel. Im looking for answers on ADO.NET/SQL-Server specific tips that make it more efficient. Not obvious answers like "dont fetch many records". En example for MySql would be "enable comptression=true" in the connection string. I'm cannot find anything on transport layer compression in SQL server. Do any of you people have experience with this ? Are there important do's and dont's that we must know ? Thanks in advance..
2009/01/21
[ "https://Stackoverflow.com/questions/465096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44894/" ]
I would use the OUTPUT clause present in SQL SERVER 2008 onwards... [**OUTPUT Clause (Transact-SQL)**](http://msdn.microsoft.com/en-us/library/ms177564.aspx) Something like... ``` BEGIN TRANSACTION DELETE [table] OUTPUT deleted.* WHERE [woof] ROLLBACK TRANSACTION ``` INSERTs and UPDATEs can use the 'inserted' table too. The MSDN article covers it all. **EDIT:** This is just like other suggestions of SELECT then DELETE inside a transaction, except that it actually does both together. So you open a transaction, delete/insert/update with an OUTPUT clause, and the changes are made while ALSO outputting what was done. Then you can choose to rollback or commit.
41,084,005
I have three divs red, black and green. I want red div whose height is 45mm and next black div on its right whose height is 55mm and then green div just below the red div and green div height is 50mm. I am using the code ``` <div style="height:45mm;width:30mm;border:1mm solid red;float:left;position:relative;"> </div> <div style="height:55mm;width:20mm;border:1mm solid black;display: inline-block;"> </div> <div style="height:50mm;width:20mm;border:1mm solid green;"> </div> ``` But I am getting the following result: <https://i.stack.imgur.com/wSNpW.jpg> What I desire is: <https://i.stack.imgur.com/4d5wn.jpg> Thanx
2016/12/11
[ "https://Stackoverflow.com/questions/41084005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6482428/" ]
This uses a flexbox with direction of column, wrap, and tight constraints (height and width). I've used `order` to change the order of the elements, but you can just switch the order in the HTML. ```css #container { display: flex; flex-direction: column; flex-wrap: wrap; width: 35mm; height: 105mm; } #rect1 { height:45mm; width:30mm; border:1mm solid red; } #rect2 { order: 1; height:55mm; width:20mm; border:1mm solid black; } #rect3 { height:50mm; width:20mm; border:1mm solid green; } ``` ```html <div id="container"> <div id="rect1"></div> <div id="rect2"></div> <div id="rect3"></div> </div> ```
73,667,680
My program is loading some news article from the web. I then have an array of html documents representing these articles. I need to parse them and show on the screen only the relevant content. That includes converting all html escape sequences into readable symbols. So I need some function which is similar to `unEscape` in JavaScript. I know there are libraries in C to parse html. But is there some easy way to convert html escape sequences like `&amp;` or `&#33;` to just `&` and `!`?
2022/09/09
[ "https://Stackoverflow.com/questions/73667680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18572447/" ]
There are several packages at CRAN that may help: * [Ryacas](https://cran.r-project.org/package=Ryacas) interfacing yacas * its predecessor [Ryacas0](https://cran.r-project.org/web/packages/Ryacas0/index.html) * [rim](https://cran.r-project.org/web/packages/rim/index.html) interfacing maxima * [caracas](https://cran.r-project.org/web/packages/rim/index.html) interfacing sympy They may all have different levels of difficulty in terms installing the underlying 'engine' but this should get you started.
41,368,915
I want to use sqlite with the json extension so I've installed it with homebrew. When I run `which sqlite` though, the one that is being used is the anaconda install. If I try and use pythons sqlite library I have the same issue. It's linked to the Anaconda version and the JSON functions aren't available. How do I replace this with the brew version? Brew provided some values when I installed sqlite but I don't know if I need them or how they are used. LDFLAGS: -L/usr/local/opt/sqlite/lib CPPFLAGS: -I/usr/local/opt/sqlite/include PKG\_CONFIG\_PATH: /usr/local/opt/sqlite/lib/pkgconfig
2016/12/28
[ "https://Stackoverflow.com/questions/41368915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6862111/" ]
Sqlite installed by Homebrew is keg-only, which is not linked to /usr/local/... . This is because system already have older version of `sqlite3`. If you really want to invoke Homebrew's sqlite binary, specify full path as below. ``` $ /usr/local/opt/sqlite/bin/sqlite3 ``` (All Homebrew package is symlinked under `/usr/local/opt`) I'm not so familiar with python, but AFAIK sqlite is statically linked to python executable. In other words, maybe you have to build python from source to use with Homebrew's sqlite.
3,004
I swear that for the past couple of weeks or so the speed of responses on serverfault.com has really degraded from what it used to be. Is it time to beef that site up a little?
2012/02/23
[ "https://meta.serverfault.com/questions/3004", "https://meta.serverfault.com", "https://meta.serverfault.com/users/1592/" ]
Are you sure it's nothing at your end? I've noticed no difference here.
20,113,314
I have database having hundreds of tables with relations. I want to look a db design for understanding tables relations in a single place. Any idea how I can do this? Regards
2013/11/21
[ "https://Stackoverflow.com/questions/20113314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966709/" ]
If it is displaying a different hour you may need to set the default timezone after setting the dateFormat (this happens only after ios7) ``` [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; ``` it seems that the default timezone is the one the device has, so if you no specify the default timezone you might get strange results. Prior to ios7 it was always GMT. **update:** if the `NSDate` is nil after the formatting you should probably use: ``` [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; ``` I had this issue with a Mexican iPhone, if you like your users to be happy with your app I strongly recommend always adding this code. I always use both code sniplets since IOS7
60,942,686
Brand new to Python and could use some help importing multiple Excel files to separate Pandas dataframes. I have successfully implemented the following code, but of course it imports everything into one frame. I would like to import them into df1, df2, df3, df4, df5, etc. Anything helps, thank you! ``` import pandas as pd import glob def get_files(): directory_path = input('Enter directory path: ') filenames = glob.glob(directory_path + '/*.xlsx') number_of_files = len(filenames) df = pd.DataFrame() for f in filenames: data = pd.read_excel(f, 'Sheet1') df = df.append(data) print(df) print(number_of_files) get_files() ```
2020/03/31
[ "https://Stackoverflow.com/questions/60942686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13160761/" ]
The easiest way to do that is to use a list. Each element of the list is a dataframe ``` def get_files(): directory_path = input('Enter directory path: ') filenames = glob.glob(directory_path + '/*.xlsx') number_of_files = len(filenames) df_list = [] for f in filenames: data = pd.read_excel(f, 'Sheet1') df_list.append(data) print(df_list) print(number_of_files) return df_list get_files() ``` You can then access your dataframes with `df_list[0]`, `df_list[1]`...
201,164
a few weeks ago, we setup a cronjob that wipes the entire contents of /tmp every Sunday at 5am. I wasn't really convinced that this is a good idea. Today we discovered that a certain task depended on an existing directory inside /tmp - the task was broken, and worse, it remained silence about why it failed. The question is: Is it generally a bad idea to just wipe out /tmp?
2010/11/12
[ "https://serverfault.com/questions/201164", "https://serverfault.com", "https://serverfault.com/users/39808/" ]
It's not a bad idea to do something about stale old files in /tmp, but I'm not sure that nuking the contents is the best thing you could do. My CentOS servers use something called tmpwatch, which runs daily and can be configured to remove only files that haven't been accessed in a certain period (30 days is a popular delay), or modified in a certain period; it can be told to leave directories alone unless they're empty, or not to touch directory files at all, or to exclude files used by a certain user (root is a popular choice). This works well for me, and it offers enough hooks that you can tune it to do what you want. I'd recommend tmpwatch, or whatever your distro offers that's like that.
56,406,047
I have a table view which has card kind of cells as shown in picture. I have set the content Inset so that I can get the cells with 20px spacing in left,right and top. [![enter image description here](https://i.stack.imgur.com/zEaDl.png)](https://i.stack.imgur.com/zEaDl.png) tableVw.contentInset = UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20) Its displaying as I expected but the problem is, cells can be moved in all direction. But when I move it to right/top, it automatically comes back to original position. But when I move to left it just goes inside and don't scroll back to original position as shown in picture. [![enter image description here](https://i.stack.imgur.com/yDK1c.png)](https://i.stack.imgur.com/yDK1c.png) I don't want the cells to move at all or I want the cells to come back to centre if its dragged anywhere also. Please help!
2019/06/01
[ "https://Stackoverflow.com/questions/56406047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4253261/" ]
Have a look at the [API for the datasets](https://docs.ckan.org/en/2.7/api/) that will likely be the easiest way to do this. In the meantime, here is how you can get the API links at id level from those pages and store the entire package info for all packages in one list, `data_sets`, and just the info of interest in another variable (`results`). Be sure to review the API documentation in case there is a better method - for example, it would be nice if ids could be submitted in batches rather than per id. Answer below is taking advantage of the endpoint detailed in the documentation which is used to get *a full JSON representation of a dataset, resource or other object* Taking the current first result on landing page of: **Vegetation of the Guyra 1:25000 map sheet VIS\_ID 240**. We want the last child `a` of parent `h3` with a parent having class `.dataset-item`. In the below, the spaces between selectors are [descendant combinators](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator). ``` .dataset-item h3 a:last-child ``` You can shorten this to `h3 a:last-child` for a small efficiency gain. This relationship reliably selects all relevant links on page. [![enter image description here](https://i.stack.imgur.com/LgnmB.png)](https://i.stack.imgur.com/LgnmB.png) Continuing with this example, visiting that retrieved url for first listed item, we can find the id using api endpoint (which retrieves json related to this package), via an attribute=value selector with contains, \*, operator. We know this particular api endpoint has a common string so we substring match on the `href` attribute value: ``` [href*="/api/3/action/package_show?id="] ``` The domain can vary and some retrieved links are relative so we have to test if relative and add the appropriate domain. First page html for that match: [![enter image description here](https://i.stack.imgur.com/FJGzU.png)](https://i.stack.imgur.com/FJGzU.png) --- Notes: 1. `data_sets` is a list containing all the package data for each package and is extensive. I did this in case you are interest in looking at what is in those packages (besides reviewing the API documentation) 2. You can get total number of pages from soup object on a page via ``` num_pages = int(soup.select('[href^="/data/dataset?page="]')[-2].text) ``` You can alter the loop for less pages. 1. Session object is used for [efficiency of re-using connection](https://2.python-requests.org/en/master/user/advanced/). I'm sure there are other improvements to be made. In particular I would look for any method which reduced the number of requests (why I mentioned looking for a batch id endpoint for example). 2. There can be none to more than one resource url within a returned package. See example [here](https://jsoneditoronline.org/?id=773bc5675faa422d988902cef6b920f6). You can edit code to handle this. --- Python: ``` from bs4 import BeautifulSoup as bs import requests import csv from urllib.parse import urlparse json_api_links = [] data_sets = [] def get_links(s, url, css_selector): r = s.get(url) soup = bs(r.content, 'lxml') base = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) links = [base + item['href'] if item['href'][0] == '/' else item['href'] for item in soup.select(css_selector)] return links results = [] #debug = [] with requests.Session() as s: for page in range(1,2): #you decide how many pages to loop links = get_links(s, 'https://data.nsw.gov.au/data/dataset?page={}'.format(page), '.dataset-item h3 a:last-child') for link in links: data = get_links(s, link, '[href*="/api/3/action/package_show?id="]') json_api_links.append(data) #debug.append((link, data)) resources = list(set([item.replace('opendata','') for sublist in json_api_links for item in sublist])) #can just leave as set for link in resources: try: r = s.get(link).json() #entire package info data_sets.append(r) title = r['result']['title'] #certain items if 'resources' in r['result']: urls = ' , '.join([item['url'] for item in r['result']['resources']]) else: urls = 'N/A' except: title = 'N/A' urls = 'N/A' results.append((title, urls)) with open('data.csv','w', newline='') as f: w = csv.writer(f) w.writerow(['Title','Resource Url']) for row in results: w.writerow(row) ``` --- All pages --------- (very long running so consider threading/asyncio): ``` from bs4 import BeautifulSoup as bs import requests import csv from urllib.parse import urlparse json_api_links = [] data_sets = [] def get_links(s, url, css_selector): r = s.get(url) soup = bs(r.content, 'lxml') base = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) links = [base + item['href'] if item['href'][0] == '/' else item['href'] for item in soup.select(css_selector)] return links results = [] #debug = [] with requests.Session() as s: r = s.get('https://data.nsw.gov.au/data/dataset') soup = bs(r.content, 'lxml') num_pages = int(soup.select('[href^="/data/dataset?page="]')[-2].text) links = [item['href'] for item in soup.select('.dataset-item h3 a:last-child')] for link in links: data = get_links(s, link, '[href*="/api/3/action/package_show?id="]') json_api_links.append(data) #debug.append((link, data)) if num_pages > 1: for page in range(1, num_pages + 1): #you decide how many pages to loop links = get_links(s, 'https://data.nsw.gov.au/data/dataset?page={}'.format(page), '.dataset-item h3 a:last-child') for link in links: data = get_links(s, link, '[href*="/api/3/action/package_show?id="]') json_api_links.append(data) #debug.append((link, data)) resources = list(set([item.replace('opendata','') for sublist in json_api_links for item in sublist])) #can just leave as set for link in resources: try: r = s.get(link).json() #entire package info data_sets.append(r) title = r['result']['title'] #certain items if 'resources' in r['result']: urls = ' , '.join([item['url'] for item in r['result']['resources']]) else: urls = 'N/A' except: title = 'N/A' urls = 'N/A' results.append((title, urls)) with open('data.csv','w', newline='') as f: w = csv.writer(f) w.writerow(['Title','Resource Url']) for row in results: w.writerow(row) ```
59,837,873
I have a problem that should be easy to solve but I simply cannot figure it out. I have a huge dataset with groups and a variable. Some groups are empty for this variable (filled only with NAs) and some contains values but also NAs. For example: ``` ID <- c("A1","A1","A1","A1","B1","B1","B1","B1", "B1", "C1", "C1", "C1") Value1 <- c(0,2,1,1,NA,1,1,NA,1,NA,NA,NA) data <- data.frame(ID, Value1) ``` I would like to change all NAs to zeros but only in groups that otherwise contain information. So like this: ``` ID <- c("A1","A1","A1","A1","B1","B1","B1","B1","B1","C1","C1","C1") Value1 <- c(0,2,1,1,0,1,1,0,1,NA,NA,NA) ``` I tried to use group\_by(ID) and "replace" with the condition max(Value1)>=0 but either max() doesn't work as a condition or it doesn't work with NAs. Unfortunately I would need this kind of conditioning often in my work so I would also appreciate any suggestions on which are the best packages to treat groups selectively.
2020/01/21
[ "https://Stackoverflow.com/questions/59837873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9804952/" ]
You can use a simple if` statement, i.e. ``` library(dplyr) library(tidyr) data %>% group_by(ID) %>% mutate(Value1 = if (all(is.na(Value1))){Value1}else{replace_na(Value1, 0)}) ``` which gives, > > > ``` > # A tibble: 12 x 2 > # Groups: ID [3] > ID Value1 > <fct> <dbl> > 1 A1 0 > 2 A1 2 > 3 A1 1 > 4 A1 1 > 5 B1 0 > 6 B1 1 > 7 B1 1 > 8 B1 0 > 9 B1 1 > 10 C1 NA > 11 C1 NA > 12 C1 NA > > ``` > >
2,914
Specifically for the SpaceX SES-8 mission going on right now. But, generally, how long does it take for a satellite to reach GEO at a minimum?
2013/11/25
[ "https://space.stackexchange.com/questions/2914", "https://space.stackexchange.com", "https://space.stackexchange.com/users/603/" ]
In theory, the shortest practical time from spacecraft separation would be about five and a quarter hours, which is half of a geosynchronous transfer orbit. At apogee, which is carefully placed to occur over the equator, a single burn raises the perigee and changes the inclination of the orbit, and you're there. All early GEO birds used this approach, and many launches still do, especially from near the equator (Ariane, Sea Launch). SES-8 went to a supersynchronous transfer orbit, which allows for much lower $\Delta V$ to change the inclination, since the spacecraft is going so much slower at apogee. It would be 1800 m/s from GTO, but it's 1500 m/s from SSTO. That includes some inclination assistance from the Falcon upper stage, which reduced the inclination from 28° in the parking orbit to 20.75° in SSTO. The SSTO in this case is 295 km x 80000 km. The SSTO approach takes longer, and there are several maneuvers required. But it is usually well worth it to save that fuel for extending the useful life of the spacecraft. Lifetime is money. A supersynchronous transfer orbit was first used in 1992. SES-8 will perform five maneuvers over two weeks to get into GEO.
68,473,791
``` #include <iostream> using namespace std; int main(){ int a=0 , b=0; cin>>a>>b; for(int i = a+1;i < b;i++){ int counter = 0; for(int j = 2;j <= i / 2;j++){ if(i % j == 0){ counter++; break; } } if(counter == 0 && i!= 1){ cout<<i<<","; } } return 0; } ``` How to remove the last comma from this code? I think we have to add 1 if statement but I don't know what should I do... please help me thanks
2021/07/21
[ "https://Stackoverflow.com/questions/68473791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16497151/" ]
You haven't provided any code so, I may not give you exact answer but you can try this: ``` st={'captchaId': '67561984031', 'code': '03AGdBq26D5XwT-p6LuAwftuZ3gUcvj0dB7lhZUT7OOfKIZU_wZzN03CCVZAaRGzzD0rXVbsJOjTBN1Ed2d0v0X6Tl2wQQPbT_R1lRHOkh5FFU46MN3tfVbajIFyZfZHUHZAt_h-5yY0cVqfJTy1_fwebyr-ilN_N1R04214z9WVXg9-cuSYJD9a2cpDNknXhvVjLxIfmVGgW9dJlouGCxZ0QbJxodRNUkQBXQTLr7DI1h-uJINlVzKvq4XguuChbQ0k2s1PrbEQK_Ir15-cAfPmldrJT5gEfjFAyBedn2Syum6axx_PRhVouXHpSKpx7-65Cw1FeBiUZ-IUSt_-E2i8NgUBXYpGt9nMIglKSSiFfO0nLcbOJuwbOObt5LvCPgfPhy2Uss9yz19F-e6GlGUuFgc7dODLN91fKUXCEmW9XG_FonSd2XV3k'} st=dict(st) print(st["code"]) ``` And if it is response from `requests` then you may do this: ``` response=requests.get() response=response.json() #or response=requests.get().json() print(response["code"]) ```
32,037
I'm using a tablet with Android 2.2. Is there something like `Tab` to switch to the next form field?
2012/10/19
[ "https://android.stackexchange.com/questions/32037", "https://android.stackexchange.com", "https://android.stackexchange.com/users/18840/" ]
Is this what you are looking for [paid app]: <https://play.google.com/store/apps/details?id=com.vmlite.vncserver&hl=en> However, if you are willing to go through a lengthy process [but free], you can follow the tutorial [here](http://www.howtogeek.com/howto/42491/how-to-remote-view-and-control-your-android-phone/) to access your phone via PC.
26,697,879
I have a "rawqueryset" object that its fields can be vary in term of some business rules. How can I access to its count and name of fields in corresponding template? View.py ``` objs=MyModel.objects.raw(sql) return list(objs) ``` template.py ``` {%for obj in objs%} {{obj.?}} {{obj.?}} . ? {%endfor%} ```
2014/11/02
[ "https://Stackoverflow.com/questions/26697879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1843934/" ]
I solved this issue using two filters: template.py: ``` {% load my_tags %} {%for obj in objs%} {%for key in obj|get_dict %} {% with d=obj|get_dict %} {{key}} - {{ d|get_val:key }} {% endwith %} {%endfor%} {%endfor%} ``` my\_tags.py: ``` @register.filter(name='get_dict') def get_dict(v): return v.__dict__ @register.filter(name='get_val') def get_val(value, arg): return value[arg] ```
17,254,122
I'm making a core data model, and I have a Client entity that has a to-many relationship to an Appointment entity. An Appointment can turn into a Transaction (if it has been paid for etc.), and I need to keep track of the Appointments of Clients that have turned into Transactions (where Transaction is an entity along with other attributes). A Client can have multiple Transactions, and a Transaction can have multiple Clients (optional). If I put a relationship between Transaction and Client, then I don't think there's a way I can detect which of the appointments have turned into transactions and which haven't... Any help as to how I can set my model up to do this would be appreciated. Thanks
2013/06/22
[ "https://Stackoverflow.com/questions/17254122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362840/" ]
It sounds like the ajax call is made when one of the elements is clicked, but you need to pass different values in the ajax call depending on which element is clicked. Rather than use an "onclick" attribute, you could do the following: HTML: ``` <div class="test" data-param1="value1a" data-param2="value2a">hi</div> <div class="test" data-param1="value1b" data-param2="value2b">hey</div> <div class="test" data-param1="value1c" data-param2="value2c">yo</div> <div class="test" data-param1="value1d" data-param2="value2d">What's up</div> ``` JavaScript: ``` $('.test').click(function() { var $div = $(this); $.ajax(url, { data: { param1: $div.attr('data-param1'), param2: $div.attr('data-param2') }, success: function() { $div.toggleClass("btn-danger btn-success"); } }); }); ``` Of course, you would set the values of the `data-` attributes using PHP variables.
608,991
I have setup a Remote Desktop Gateway server using Windows Server 2012 R2. I am using the Remote Desktop Gateway as an intermediary between to provide the remote desktop session over 443 since 3389 is blocked at many client locations. However, I ran into a problem with a client who's network seems to be using an web proxy. Is is possible to configure Remote Desktop to connect via web proxy? If so, how? If not does any one have any suggestions on how to provide a Remote Desktop session via 443 over proxy for situations where you don't control the client's PC or network? Does RemoteApps allow for access via web proxy when using RD Gateway? The error message is below: **Your computer can't connect to the remote computer because the web proxy server requires authentication. To allow unauthenticated traffic to an RD Gateway server through your web proxy server, contact your network administrator.** Thanks for any help!
2014/06/30
[ "https://serverfault.com/questions/608991", "https://serverfault.com", "https://serverfault.com/users/228593/" ]
As of 2008 [a Microsoft employee indicated there was "no official way" to accomplish this](http://social.technet.microsoft.com/Forums/windowsserver/en-US/a341fda4-10ef-4c4c-8646-3ff10bea3a38/connecting-to-ts-gateway-through-a-web-proxy?forum=winserverTS). Given the six intervening years you'd like to think there has been progress, but I'm not seeing that there has been. If I were in your situation I'd try to find a small Win32 HTTP/HTTPS proxy that can be "pointed" at an upstream proxy and configured to provide authentication. I don't have an immediate recommendation for such a thing. (I'd probably just throw something together with Perl or Python, personally.)
73,315,389
I am trying to create a new data frame using R from a larger data frame. This is a short version of my large data frame: ``` df <- data.frame(time = c(0,1,5,10,12,13,20,22,25,30,32,35,39), t_0_1 = c(20,20,20,120,300,350,400,600,700,100,20,20,20), t_0_2 = c(20,20,20,20,120,300,350,400,600,700,100,20,20), t_2_1 = c(20,20,20,20,20,120,300,350,400,600,700,100,20), t_2_2 = c(20,20,20,20,120,300,350,400,600,700,100,20,20)) ``` The new data frame should have the first variable values as the number in the end of the large data frame variables name (1 and 2). The other variables name should be the number in the middle of the large data frame variables (0 and 2) and for their values I am trying to filter the values greater than 300 for each variable and calculate the time difference. For example for variable "t\_0\_1", the time that the values are greater than 300 is 13 to 25 seconds. So the value in the new data frame should be 12. The new data frame should look like this: ``` df_new <- data.frame(height= c(1,2), "0" = c(12,10), "2" = c(10,10)) ``` Any help where I should start or how I can do that is very welcome. Thank you!!
2022/08/11
[ "https://Stackoverflow.com/questions/73315389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7033156/" ]
You could calculate the time difference for each column with `summarise(across(...))`, and then transform the data to long. ```r library(tidyverse) df %>% summarise(across(-time, ~ sum(diff(time[.x > 300])))) %>% pivot_longer(everything(), names_to = c(".value", "height"), names_pattern = "t_(.+)_(.+)") # # A tibble: 2 × 3 # height `0` `2` # <chr> <dbl> <dbl> # 1 1 12 10 # 2 2 10 10 ```
3,739,753
I'm trying to figure out how to unit test my object that persists itself to session state. The controller does something like... ``` [HttpPost] public ActionResult Update(Account a) { SessionManager sm = SessionManager.FromSessionState(HttpContext.Current.Session); if ( a.equals(sm.Account) ) sm.Account = a; return View("View", a); } ``` And the session manager serializes itself to session state ``` public class SessionManager { public static SessionManager FromSessionState(HttpSessionStateBase state) { return state["sessionmanager"] as SessionManager ?? new SessionManager(); } public Guid Id { get; set; } public Account Account { get; set; } public BusinessAssociate BusinessAssociate {get; set; } } ``` I'm thinking that there are two approaches to unit testing... 1. in the static instantiator pass in the session state reference and then restore from that. this would allow me to mock this parameter and everything would be golden. public static SessionManager FromSessionState(HttpSessionStateWrapper session) { return session["sessionmanager"] as SessionManager ?? new SessionManager(); } 2. create a mock for the SessionManager and use that for testing of the controller.
2010/09/17
[ "https://Stackoverflow.com/questions/3739753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69983/" ]
Here's an idea: Create a session manager "persistence" interface: ``` public interface ISessionManagerPersist { SessionManager Load(); void Save(SessionManager sessionManager); } ``` Create an HTTPSession-based implementation of your persistence: ``` public class SessionStatePersist : ISessionManagerPersist { public SessionManager Load() { return HttpContext.Current.Session["sessionmanager"] as SessionManager ?? new SessionManager(); } public void Save(SessionManager sessionManager) { HttpContext.Current.Session["sessionmanager"] = sessionManager; } } ``` Now make your controller have a dependency on `ISessionManagerPersist`. You can inject a stub `ISessionManagerPersist` during testing and use the session-based one during production. This also has the benefit of not needing changes if you decided to persist somewhere else (like a DB or something). Just implement a new `ISessionManagerPersist`.
653,858
I've just been wondering because I see this on ubiquity and want to know how this is better during the installation of Ubuntu.
2015/07/28
[ "https://askubuntu.com/questions/653858", "https://askubuntu.com", "https://askubuntu.com/users/409520/" ]
If you are not plugged, then your laptop battery may be dead before the installation is finished, if you have a laptop. **;)** The result can be a ruined or incomplete installation and you have to start over. Assuming your hard drive still functions.
2,477
Many people learn foreign languages at school, which often involves [learning vocabulary lists](https://languagelearning.stackexchange.com/q/2462/800). Others learn languages through [immersion](https://languagelearning.stackexchange.com/questions/tagged/immersion). Each method has its benefits and drawbacks. What are the **main benefits and drawbacks of learning vocabulary only through conversation**?
2016/12/09
[ "https://languagelearning.stackexchange.com/questions/2477", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/800/" ]
In a [YouTube video from September 2016](https://www.youtube.com/watch?v=A6IIH49dt-g), the British polyglot Olly Richards explains that he had been learning **Cantonese without learning to read and write**. He had been following the advice to focus on oral skills first, and he found that it kept the **momentum** going and that it kept him **motivated** to learn. But after a few years, he felt he got **stuck at an intermediate plateau**, with a limited vocabulary. When learning other languages, **breaking through that plateau always involved reading**. That's why he decided to start learning Chinese characters. (He also created a number of videos about this new learning project; see the playlist [Project: Learn To Write Chinese Characters](https://www.youtube.com/playlist?list=PLQJscr8iS4eEtoyzLvx_kw4BJXzRxfCuc) .)
24,080,285
I gave margin 20px for both the div inside sidebar div. But for some reason the gap between two div's us just 20px, which should be 40px. 20px from box1 and 20px from box2. Am I missing some minor thing. please point it out. **Fiddle:** <http://jsfiddle.net/3UJWf/> **HTML:** ``` <div class="sidebar"> <div class="box1 common"> <p>Text is here</p> </div> <div class="box2 common"> <p>Text is here</p> </div> </div> ``` **CSS:** ``` * { padding:0px; margin:0px; } .box1 { background:red; padding: 40px; width: 300px; } .box2 { background: green; padding: 40px; width: 300px; } .common { margin: 20px; } ```
2014/06/06
[ "https://Stackoverflow.com/questions/24080285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2177755/" ]
[Check Demo](http://jsfiddle.net/3UJWf/3/) [CSS Margin Collapsing](https://stackoverflow.com/questions/102640/css-margin-collapsing) `float:left;` or `display: inline-block` solves the above issue Let’s explore exactly what the consequences of collapsing margins are, and how they will affect elements on the page. *The W3C specification defines collapsing margins as follows:* “ > > In this specification, the expression collapsing margins means that > adjoining margins (no non-empty content, padding, or border areas, or > clearance separate them) of two or more boxes (which may be next to > one another or nested) combine to form a single margin. > > > ” **In simple terms, this definition indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero.1 In the case where one element has a negative margin, the margin values are added together to determine the final value. If both are negative, the greater negative value is used. This definition applies to adjacent elements and nested elements.** There are other situations where elements do not have their margins collapsed: 1. floated elements 2. absolutely positioned elements 3. inline-block elements 4. elements with overflow set to anything other than visible (They do not collapse margins with their children.) 5. cleared elements (They do not collapse their top margins with their parent block’s bottom margin.) the root element [This is a difficult concept to grasp, so let’s dive into some examples.](http://www.sitepoint.com/web-foundations/collapsing-margins/)
2,036,862
I have a mapping defined where a parent object has a collection of child objects. In my design, I'd like to be able to delete the child objects without having to remove them from the collection on the parent object and re-saving the parent object. However, when I try this, I get the "deleted object would be re-created on save" error. Is there a way to prevent this such that I could simply delete the child object and not worry about removing it from the parent's collection too? That feels like doing double the work. Ideally I'd like to treat the parent's collection as read-only from NHibernate's perspective.
2010/01/10
[ "https://Stackoverflow.com/questions/2036862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129648/" ]
It is doable, no problem. There is the `$_REQUEST` array that merges GET, POST, and COOKIE values but the better way would be to handle GET and POST manually in your script. Just have your engine check both `$_GET["variable"]` and `$_POST["variable"]` and use whichever is set. If a variable is set in both methods, you need to decide which one you want to give precedence. The only notable difference between the two methods is that a GET parameter has size limitations depending on browser and receiving web server (POST has limitations too, but they are usually in the range of several megabytes). I think the general rule is that a GET string should never exceed 1024 characters.