qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
2,332,712
Let $M$ , $N$, and $P$ be smooth manifolds with or without boundary. Every constant map $c: M\rightarrow N$ is smooth. **Proof:** Let $c: M \rightarrow N$ be a constant map. Let $p \in M$. Smoothness of $c$ means there are charts $(U,\phi)$ of $p$ and $(V,\psi)$ of $c(p)$ such that $c(U) \subseteq V$ and $\psi \circ c \ \circ \phi^{-1} $ is smooth. Since $c$ is a constant map we know that $c(p)=y$ for every $p \in M$. This is as far as I got with the proof. I'm a bit lost on how to finish the proof using the fact that c is a constant map to show that $c: M \rightarrow N$ is smooth. I'd appreciate hints or advice instead of a full solution to the problem that way it doesn't spoil the problem for me. I'm using Lee's Introduction to Smooth Manifolds.
2017/06/22
[ "https://math.stackexchange.com/questions/2332712", "https://math.stackexchange.com", "https://math.stackexchange.com/users/203845/" ]
We have chosen some chart $\phi \colon U \rightarrow \phi(U) \subseteq \mathbb{R}^n$ on $M$ and a chart $\psi \colon V \rightarrow \psi(V) \subseteq \mathbb{R}^m$ on $N$. We want to show that $\psi \circ c \circ \phi^{-1}$ is smooth given $c$ is constant. Hints: 1. What is the domain and codomain of the map $\psi \circ c \circ \phi^{-1}$ 2. Is a constant map $k \colon \mathbb{R}^n \rightarrow \mathbb{R}^m$ smooth?
Hint: You just need to write it down clearly. $c$ is smooth requires you to show that $\phi \circ c \circ \psi^-$ is smooth. Now as $c$ is constant,for all arguments, you are left with $\phi(y)$ in the end. Now this is just a constant. Use definition of smoothness now
2,332,712
Let $M$ , $N$, and $P$ be smooth manifolds with or without boundary. Every constant map $c: M\rightarrow N$ is smooth. **Proof:** Let $c: M \rightarrow N$ be a constant map. Let $p \in M$. Smoothness of $c$ means there are charts $(U,\phi)$ of $p$ and $(V,\psi)$ of $c(p)$ such that $c(U) \subseteq V$ and $\psi \circ c \ \circ \phi^{-1} $ is smooth. Since $c$ is a constant map we know that $c(p)=y$ for every $p \in M$. This is as far as I got with the proof. I'm a bit lost on how to finish the proof using the fact that c is a constant map to show that $c: M \rightarrow N$ is smooth. I'd appreciate hints or advice instead of a full solution to the problem that way it doesn't spoil the problem for me. I'm using Lee's Introduction to Smooth Manifolds.
2017/06/22
[ "https://math.stackexchange.com/questions/2332712", "https://math.stackexchange.com", "https://math.stackexchange.com/users/203845/" ]
We have chosen some chart $\phi \colon U \rightarrow \phi(U) \subseteq \mathbb{R}^n$ on $M$ and a chart $\psi \colon V \rightarrow \psi(V) \subseteq \mathbb{R}^m$ on $N$. We want to show that $\psi \circ c \circ \phi^{-1}$ is smooth given $c$ is constant. Hints: 1. What is the domain and codomain of the map $\psi \circ c \circ \phi^{-1}$ 2. Is a constant map $k \colon \mathbb{R}^n \rightarrow \mathbb{R}^m$ smooth?
***Every constant map is smooth.*** > > Say $f:M \rightarrow N $ is a constant map. Here $f$ is smooth because the coaordinate representation of $f$ i.e $\theta f\phi^{-1} :R^{m}\rightarrow R^n$ is a constant map as a map between 2 euclidean spaces where $(u,\phi)$ and $(v,\theta)$ are charts around $p$ and $q$ respectively where $f(p)=q$ $\forall$ $p \in$ $M$. Here dimension of $M$ and $N$ are assumed to be $m$ and $n$ respectively. We already know from multi variable calculus that any constant map between two euclidean spaces is always smooth. Hence by definiton of a smooth map between smooth manifolds $f$ is smooth. > > >
446,618
![enter image description here](https://i.stack.imgur.com/0CH4T.jpg) This was my grandfather’s and have no idea what it is only that it is some piece of physics equipment! The main black cylinder doesn’t seem like it wants to rotate but not sure if it should?
2018/12/11
[ "https://physics.stackexchange.com/questions/446618", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/37250/" ]
It looks like an [induction coil](https://en.wikipedia.org/wiki/Induction_coil) with the make and break device at the bottom and a switch right at the bottom. If you connect it up to an accumulator, be very, very careful as the output between the two balls, when separate, could be lethal. Also the electrical insulation elsewhere may be poor and you might get a shock just by touching the switch. **Use with very great care** and preferably have somebody who knows about such devices with you.
It is a spark radio transmitter. The first working radios. Video: <https://www.youtube.com/watch?v=YSf93g0heUA> Pics: <https://www.google.com/search?q=spark+radio+transmitter&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi-68m5vJjfAhXMx1kKHVuUASQQ_AUIDygC&biw=1920&bih=930> This one looks awfully similar and might give you some help finding out model and such: <http://www.samhallas.co.uk/bt_museum/radio.htm> Remember 300 baud modems that you put the handset into? This was the top of the line once upon a time too. It's why we have "SOS" in our language rather than relying upon a simple "Oh God, we need help!" And if Tesla'd ever realized be was using Morgan's money to succcessfully invent radio transmission rather than failing at wireless power transmission, we'd've never called these "Marconi Spark Gap Transmitters"... but he didn't.
35,287
hello. I am looking for tensor manipulation software that would allow me: * declare indices * declare results of contraction (or simplification rules) * allow algebraic simplifications and expansion * index renaming So far I have found Maxima to satisfy my requirement more or less, <http://maxima.sourceforge.net/docs/manual/en/maxima_27.html> one last thing I also want, (but not necessarily require), is interface with python. In principle I could use sage to interface with maxima. Is there some other Cas that has package with similar tensor manipulation properties? from links given below, I also found this, <http://cadabra.phi-sci.com/>, which looks geared specifically for tensor manipulations.
2010/08/11
[ "https://mathoverflow.net/questions/35287", "https://mathoverflow.net", "https://mathoverflow.net/users/5925/" ]
I think that everything in your list (except the Python interface) can be found in Kasper Peeters' [Cadabra](http://cadabra.phi-sci.com/). As for a Python interface, there are two directions: 1. [It is planned](http://cadabra.phi-sci.com/ideas.html) to add an interface layer to Cadabra to either Maxima or SymPy - in the latter case you'd probably get access to Python. 2. [There is talk](http://groups.google.com.au/group/sage-devel/browse_thread/thread/83182fbfc62cd0f6/3623f8d9d819c01c?q=Cadabra+interface#3623f8d9d819c01c) of adding a Cadabra interface to sage using the standard sage.interfaces.expect class. As an aside some of the index algorithms come from José Martin-Garcia's [xPerm](http://metric.iem.csic.es/Martin-Garcia/xAct/index.html), a Mathematica package. xPerm seems to be more suited to GR while Cadabra is focused on QFT. [FORM](http://www.nikhef.nl/~form/) (the successor of Schoonschip) is also very powerful and used in a lot of high energy physics computing.
I think your best bet is a physics oriented package which I think is just called R or maybe Reduce. Meanwhile, here is the msri page of documentation for most packages currently available there. <http://www.msri.org/about/computing/mathdocs> $$ $$ <http://en.wikipedia.org/wiki/FORM_(symbolic_manipulation_system)> $$ $$ <http://en.wikipedia.org/wiki/List_of_computer_algebra_systems>
46,934,653
we are facing an issue in production that the 'Content-Length' header is not being sent, even if we hard-code it in the headers properties, so we are receiving back from the server the 411 Length Required error. We are using: * Axios 0.16.2 * NodeJS 6.10 * Application deployed inside AWS Lambda environment The code that is causing the issue is the following: ``` let cookieJar; const postBody = "MyBody=MyBodyContentGoesHere"; const url = "https://my-url.com"; return axios .post(url, postBody, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 10000, jar: cookieJar, withCredentials: true } ); ``` I wrote an application in .NET and the header is sent properly (without to pass it manually). This .NET application was written just to test, it's not the real application. Do you have some idea? I open a issue in the axios github project, but I want to know from you guys some ideas. Thank you.
2017/10/25
[ "https://Stackoverflow.com/questions/46934653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/513808/" ]
You can specify the .py file form which you wish to import in the code itself by adding a statement `sc.addPyFile(Path)`. The path passed can be either a local file, a file in HDFS (or other Hadoop-supported filesystems), or an HTTP, HTTPS or FTP URI. Then use `from add_num import add_two_nos`
You need to include a zip containing add\_num.py in your spark-submit command. ``` ./bin/spark-submit --py-files sources.zip /Users/workflow/test_task.py ``` When submitting a python application to spark, all the source files imported by the main function/file(here test\_task.py) should be packed in a egg or zip format and supplied to spark using --py-files option. If the main function needs only one other file, you can supply it directly without zipping it. ``` ./bin/spark-submit --py-files add_num.py /Users/workflow/test_task.py ``` Above command should also work since there is only one other python source file required.
30,957,706
I am trying to modify Javascripts Array type with a method which will push a value to an array only if its is not already present. Here is my code: ``` // add a method conditionally Array.prototype.method = function (name, func){ if(!this.prototype[name]){ this.prototype[name] = func; return this; } }; // exclusive push Array.method('xadd', function(value){ if(this.indexOf(value) === -1){ this.push(value) }; return this; }); ``` However when I run the code the scratchpad in Firefox returns: ``` /* Exception: TypeError: Array.method is not a function @Scratchpad/3:19:1 */ ``` I want a vanilla way of doing this. Not a library as I am writing an open source library.
2015/06/20
[ "https://Stackoverflow.com/questions/30957706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1652010/" ]
When you're putting a method on `Array.prototype` the method will be available on the instances of Array. ``` // Add the custom method Array.prototype.method = function() { console.log('XXX'); } var foo = []; // prints XXX foo.method(); ```
Borrowing from Andy & Nihey I have arrived at the following solution which modifies the Array type making 'xadd' conditionally available to all instances of Array ``` if (!('xpush' in Array.prototype)) { Array.prototype.xpush = function(value){ if(this.indexOf(value) === -1){ this.push(value); }; return this }; } var a = [1,2,3]; console.log(a); // Array [ 1, 2, 3 ] a.xadd(5); console.log(a); // Array [ 1, 2, 3, 5 ] a.xadd(3); console.log(a); // Array [ 1, 2, 3, 5 ] '3' already present so not added ``` A better name would be xpush() as it's behaviour is a variant of push().
30,957,706
I am trying to modify Javascripts Array type with a method which will push a value to an array only if its is not already present. Here is my code: ``` // add a method conditionally Array.prototype.method = function (name, func){ if(!this.prototype[name]){ this.prototype[name] = func; return this; } }; // exclusive push Array.method('xadd', function(value){ if(this.indexOf(value) === -1){ this.push(value) }; return this; }); ``` However when I run the code the scratchpad in Firefox returns: ``` /* Exception: TypeError: Array.method is not a function @Scratchpad/3:19:1 */ ``` I want a vanilla way of doing this. Not a library as I am writing an open source library.
2015/06/20
[ "https://Stackoverflow.com/questions/30957706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1652010/" ]
First I would run a check to see if the method is already on the array. Don't go overridding existing prototype methods. In addition, you're not adding `func` to the prototype - you're adding it to the instances you'll be creating. ``` if (!('method' in Array.prototype)) { Array.prototype.method = function (name, func) { if (!this[name]) this[name] = func; } } ``` Then you need to actually create your array instance: ``` var arr = [1,2]; ``` At which point you can use the method you created to add the function. Note in your question your check was incorrect: ``` arr.method('xadd', function (value) { if (this.indexOf(value) === -1) { this.push(value) }; }); arr.xadd(3); // [1,2,3] ``` [DEMO](http://jsfiddle.net/057911v7/)
Borrowing from Andy & Nihey I have arrived at the following solution which modifies the Array type making 'xadd' conditionally available to all instances of Array ``` if (!('xpush' in Array.prototype)) { Array.prototype.xpush = function(value){ if(this.indexOf(value) === -1){ this.push(value); }; return this }; } var a = [1,2,3]; console.log(a); // Array [ 1, 2, 3 ] a.xadd(5); console.log(a); // Array [ 1, 2, 3, 5 ] a.xadd(3); console.log(a); // Array [ 1, 2, 3, 5 ] '3' already present so not added ``` A better name would be xpush() as it's behaviour is a variant of push().
18,380,463
Recently I'm working on a new project and `UTF-8` is a must. I don't know why I'm facing this, but it is really strange to me. I really tried everything I knew, but the problem remains. I'm sending a JSON string to my servlet and here is the servlet part: ``` protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); if (action.equals("startProcess")) { final String data = request.getParameter("mainData"); URLDecoder.decode(data, "UTF-8"); System.out.println("DATA \n" + URLDecoder.decode(data, "UTF-8")); JSONObject jsonObj = new JSONObject(); try { JSONArray jsonArr = new JSONArray(URLDecoder.decode(data, "UTF-8")); jsonObj.put("data", jsonArr); JSONArray array = jsonObj.getJSONArray("data"); System.out.println("insertDtls \n" + jsonObj.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` the `System.out.println("insertDtls \n" + jsonObj.toString());` returns: this result: `DATA [{"department":"1"},{"stampType":"кÑÑÐ³Ð»Ð°Ñ Ð¿ÐµÑаÑÑ"},{"headCompany":"да"},{"stampReason":"1"},{"textToPrint":"asd"},{"comments":"da"},{"other":"дÑÑгой"}]` I realy don't know what to do here. I'm sure that I'm missing something really small, but I'm not able to spot it. Is it possible to have this string double encoded somehow?
2013/08/22
[ "https://Stackoverflow.com/questions/18380463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1773265/" ]
`String data = request.getParameter("mainData");` request.getParameter() already decodes mainData parameter. No further decoding is necessary: `URLDecoder.decode(data, "UTF-8")` If you still want to get raw mainData parameter value use [request.getQueryString()](http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getQueryString%28%29) and then decode it: `URLDecoder.decode(request.getQueryString(), "UTF-8");` On client side make sure that when sending a GET request all URL parameters are correctly UTF-8 encoded. Also on server side make sure your GET parameters are UTF-8 decoded. For example to fix it in Tomcat you must configure *URIEncoding* attribute in server.xml: `<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" ...>`
Try running your java process with the -Dfile.encoding=UTF-8 parameter.
42,623
Every once in a while, my eighth-inch audio jack will slip loose and I'll seemingly lose only the voice part of a track -- leaving somewhat of a "karaoke" version. What I would guess about how audio plugs work suggests that I'd be making this up; however, I've asked and others tell me they've experienced this as well. What causes this stripped vocals from audio when a 1/8" audio jack is partially unplugged?
2012/10/02
[ "https://electronics.stackexchange.com/questions/42623", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/13714/" ]
When the plug starts to slip out of the jack, very often it's the ground contact (sleeve) that breaks its connection first, leaving the two "hot" leads (left and right, tip and ring) still connected. With the ground open like this, both earpieces still get a signal, but now it's the "difference" signal between the left and right channels; any signal that is in-phase in both channels cancels out. Recording engineers tend to place the lead vocal signal right in the middle of the stereo image, so that's just one example of an in-phase signal that disappears when you're listening to the difference signal.
If you look carefully at the jackplug, you'll likely see three (or more) contacts. These are ground (shared), left and right. I would guess that the vocals are on only one of the stereo tracks (ie. left or right but not both). When the plug comes partially out, you're getting mono.
42,623
Every once in a while, my eighth-inch audio jack will slip loose and I'll seemingly lose only the voice part of a track -- leaving somewhat of a "karaoke" version. What I would guess about how audio plugs work suggests that I'd be making this up; however, I've asked and others tell me they've experienced this as well. What causes this stripped vocals from audio when a 1/8" audio jack is partially unplugged?
2012/10/02
[ "https://electronics.stackexchange.com/questions/42623", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/13714/" ]
The vocal track, particularly if it is just one singer, is usually found in the centre. This means it is mixed equally into left and right. If you produce a difference signal, L-R or R-L, then this common mode material (anything mixed in equal proportions to left and right) will be attenuated. Such a situation can happen in headphones if you break the ground connection. Note that the headphone jack has only three conductors (tip, ring, sleeve). So the headphones share a common return path, or ground. If this ground is not properly connected to the player, it still remains properly connected to both headphones through the jack. The headphones then form a series circuit: left amplifier output, left headphone, common ground, right headphone, right amplifier output. What you're hearing in the headphones then is the voltage difference between the amps. Any component of the signal which is common mode (mixed into both channels equally) is suppressed. (If the amplifiers produced exactly the same signal, then the difference would be zero!) So vocals in the center, and other things that are panned in the center such as (typically) bass guitar and kick drum, are faintly audible or not at all. You hear a signal that lacks bass and in which the vocals are faint and distant. But the reverb on the vocals may sound huge, because it is a stereo effect with a differing left and right signal! It may sound like the reverb mix is much more "wet" with respect to a tiny "dry" vocal signal. Additional notes: Why can the amplifiers work without a ground? Because each amplifier can regard the other as a ground, so to speak. A voltage amplifier has a low output impedance. One amplifier's output can serve as the ground or return path for another amplifier's output and vice versa. This is the basis for amplifier bridging. The main point is that the connection from one amplifier to the other is a complete circuit; lifting the headphone ground does not interrupt the circuit. This type of connection between two amplifiers is exploited to bring about *bridging*. But bridging requires that one of the amplifiers receives an inverted signal, so that their difference is really addition! Bridging is a technique of using two weaker amplifiers to make a single more powerful amplifier. Bridging also allows an amplifier to be DC-coupled to the speaker, even if it is based on a single voltage supply (meaning that no coupling capacitor is required in series with the speaker to block DC). The technique is used in some small audio amplifier IC's that run off a single supply, but in the pro audio world, large stereo amplifiers sometimes support a bridging configuration. An important parameter of a stereo amp (to some users) is whether or not it can be easily "bridged mono" for more power, or driving of smaller impedance loads. So, what you've done with your jack is essentially bridged the left and right amps, except they have somewhat different signals, and one is not inverted with respect to the other!
If you look carefully at the jackplug, you'll likely see three (or more) contacts. These are ground (shared), left and right. I would guess that the vocals are on only one of the stereo tracks (ie. left or right but not both). When the plug comes partially out, you're getting mono.
42,623
Every once in a while, my eighth-inch audio jack will slip loose and I'll seemingly lose only the voice part of a track -- leaving somewhat of a "karaoke" version. What I would guess about how audio plugs work suggests that I'd be making this up; however, I've asked and others tell me they've experienced this as well. What causes this stripped vocals from audio when a 1/8" audio jack is partially unplugged?
2012/10/02
[ "https://electronics.stackexchange.com/questions/42623", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/13714/" ]
When the plug starts to slip out of the jack, very often it's the ground contact (sleeve) that breaks its connection first, leaving the two "hot" leads (left and right, tip and ring) still connected. With the ground open like this, both earpieces still get a signal, but now it's the "difference" signal between the left and right channels; any signal that is in-phase in both channels cancels out. Recording engineers tend to place the lead vocal signal right in the middle of the stereo image, so that's just one example of an in-phase signal that disappears when you're listening to the difference signal.
The vocal track, particularly if it is just one singer, is usually found in the centre. This means it is mixed equally into left and right. If you produce a difference signal, L-R or R-L, then this common mode material (anything mixed in equal proportions to left and right) will be attenuated. Such a situation can happen in headphones if you break the ground connection. Note that the headphone jack has only three conductors (tip, ring, sleeve). So the headphones share a common return path, or ground. If this ground is not properly connected to the player, it still remains properly connected to both headphones through the jack. The headphones then form a series circuit: left amplifier output, left headphone, common ground, right headphone, right amplifier output. What you're hearing in the headphones then is the voltage difference between the amps. Any component of the signal which is common mode (mixed into both channels equally) is suppressed. (If the amplifiers produced exactly the same signal, then the difference would be zero!) So vocals in the center, and other things that are panned in the center such as (typically) bass guitar and kick drum, are faintly audible or not at all. You hear a signal that lacks bass and in which the vocals are faint and distant. But the reverb on the vocals may sound huge, because it is a stereo effect with a differing left and right signal! It may sound like the reverb mix is much more "wet" with respect to a tiny "dry" vocal signal. Additional notes: Why can the amplifiers work without a ground? Because each amplifier can regard the other as a ground, so to speak. A voltage amplifier has a low output impedance. One amplifier's output can serve as the ground or return path for another amplifier's output and vice versa. This is the basis for amplifier bridging. The main point is that the connection from one amplifier to the other is a complete circuit; lifting the headphone ground does not interrupt the circuit. This type of connection between two amplifiers is exploited to bring about *bridging*. But bridging requires that one of the amplifiers receives an inverted signal, so that their difference is really addition! Bridging is a technique of using two weaker amplifiers to make a single more powerful amplifier. Bridging also allows an amplifier to be DC-coupled to the speaker, even if it is based on a single voltage supply (meaning that no coupling capacitor is required in series with the speaker to block DC). The technique is used in some small audio amplifier IC's that run off a single supply, but in the pro audio world, large stereo amplifiers sometimes support a bridging configuration. An important parameter of a stereo amp (to some users) is whether or not it can be easily "bridged mono" for more power, or driving of smaller impedance loads. So, what you've done with your jack is essentially bridged the left and right amps, except they have somewhat different signals, and one is not inverted with respect to the other!
37,590,244
I am using laravel 5 and having following array: ``` array:3 [▼ 0 => 3, 1 => 4, 2 => 5 ] ``` Now i wanted to get all values/rows from table say 'X' having id's 3,4,5
2016/06/02
[ "https://Stackoverflow.com/questions/37590244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2305113/" ]
Try this query ``` $array = [ 0 => 3,1 => 4, 2 => 5]; $results = DB::table('x') ->whereIn('id',$array) ->get(); ```
**You can see the query sample for Laravel 5** ``` $result=DB::table('x')->whereIn('id',[3,4,5])->get(); ```
114,936
Say every container and the host itself has its own dedicated, external IP. Is it possible to do this without any problems? And is this really a good plan? Instead of hosting a database per container, hosting a database per host, for all containers to share? This question is sort of related to this one: <https://unix.stackexchange.com/questions/114786/giving-ovz-containers-their-own-ip>
2014/02/12
[ "https://unix.stackexchange.com/questions/114936", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/56196/" ]
I do this exact same thing, I have ~10+ OpenVZ guests and a single instance of MySQL running in one of the 10. This is a good approach if the following things are true: * All the VM's using this DB won't overload it * Running multiple individual MySQL instances in their own VMs would be more resource intensive * All the guest VMs that are talking to the single instance of MySQL can be coordinated to have it (MySQL) down when doing maintenance, backups, etc. From a technology standpoint OpenVZ can definitely do this, it really comes down to what expectations the applications and other VMs are expecting the database "service" to be available. I think you're confusing the situation due to the technology being used. There is nothing inherent in OpenVZ that will disallow you from setting up this kind of architecture. OpenVZ will allow you to loosely "wall off" instances of applications and allow you to create multiple hostnames for the varying services, if you so choose, but otherwise it's no different then if you were to spin up 10 machines with 10 instances of Apache running on them, with a single host running MySQL.
OK, the question is: is it a good plan to have one MySQL-Database on a hardware node to server all VM, or is it better to have the MySQL-Database on a VM. As always it depends on what are your requirements. If you are paranoid enough and security is most important, then have your DB on a VM. If performance is most important, than it would be better to put your DB on the hardware node.
6,533,242
I want to add the ability to see the server exception on the client side. If the server got some exception => i want to show some MessageBox on the client side that will show the exception message .. How can i do it ?
2011/06/30
[ "https://Stackoverflow.com/questions/6533242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465558/" ]
First of all, you need to enable your WCF service to return detailed error information. This is OFF by default, for security reasons (you don't want to tell your attackers all the details of your system in your error messages...) For that, you need to create a new or amend an existing service behavior with the `<ServiceDebug>` behavior: ``` <behaviors> <serviceBehaviors> <behavior name="ServiceWithDetailedErrors"> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> ``` Secondly, you need to change your `<service>` tag to reference this new service behavior: ``` <service name="YourNamespace.YourServiceClassName" behaviorConfiguration="ServiceWithDetailedErrors"> ...... </service> ``` And third: you need to adapt your SL solution to look at the details of the errors you're getting back now. And lastly: while this setting is very useful in development and testing, you **should** turn those error details OFF for production - see above, for security reasons.
In addition to the things Marc mentioned you will also want to switch to the HTTP Client Stack in order to avoid the dreaded generic "Not Found" error. ``` bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp); ```
6,533,242
I want to add the ability to see the server exception on the client side. If the server got some exception => i want to show some MessageBox on the client side that will show the exception message .. How can i do it ?
2011/06/30
[ "https://Stackoverflow.com/questions/6533242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465558/" ]
First of all, you need to enable your WCF service to return detailed error information. This is OFF by default, for security reasons (you don't want to tell your attackers all the details of your system in your error messages...) For that, you need to create a new or amend an existing service behavior with the `<ServiceDebug>` behavior: ``` <behaviors> <serviceBehaviors> <behavior name="ServiceWithDetailedErrors"> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> ``` Secondly, you need to change your `<service>` tag to reference this new service behavior: ``` <service name="YourNamespace.YourServiceClassName" behaviorConfiguration="ServiceWithDetailedErrors"> ...... </service> ``` And third: you need to adapt your SL solution to look at the details of the errors you're getting back now. And lastly: while this setting is very useful in development and testing, you **should** turn those error details OFF for production - see above, for security reasons.
If you are passing the errors to the client you can use a Fault Contract: Add this attribute to your service contract: ``` [OperationContract] [FaultContract(typeof(MyCustomException))] void MyServiceMethod(); ``` Create the class for "MyCustomException" containing exactly the information you wish to pass to the client (in this case the full details of the exception from exception.ToString()). Then add a try/catch around the code in the implementation of your service method: ``` public void MyServiceMethod() { try { // Your code here } catch(Exception e) { MyCustomException exception= new MyCustomException(e.ToString()); throw new FaultException<MyCustomException>(exception); } } ``` On the client side you can put a try / catch(FaultException e) and display the details however you like. ``` try { // your call here } catch (FaultException<MyCustomException> faultException) { // general message displayed to user here MessageBox.Show((faultException.Detail as MyCustomException).Details); } catch (Exception) { // display generic message to the user here MessageBox.Show("There was a problem connecting to the server"); } ```
13,159,303
I'm creating dates from strings with the format 'yyyy-MM-dd' but they're always created on the previous day for some reason. If I set the date as '2012-10-31' the Date object with actually be 30 of October and not 31. For example, this: ``` var d1=new Date('2012-10-31'); ``` Will output this: ``` Tue Oct 30 2012 19:30:00 GMT-0430 (Venezuela Standard Time) ``` Can someone explain why this happens?
2012/10/31
[ "https://Stackoverflow.com/questions/13159303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/478108/" ]
Both are valid approaches. I tend to favour the first option, because it allows better modularity and quite clear boundaries for high level BC. The second option is the 'standard' way of doing this, it favours let's say a more technical layering, while the first option literally favours a more domain driven layering. Choose the one you feel more comfortable with.
do as you see fit. Each bounded context will have a different domain and surely a different application layer, but we may imagine a common Infrastructure layer ou presentation layer. It really depends on your architectural choices, and on the application you are trying to build. If you want a more precise answer, add some material to your question, so that we can get your context and your problematic.
13,159,303
I'm creating dates from strings with the format 'yyyy-MM-dd' but they're always created on the previous day for some reason. If I set the date as '2012-10-31' the Date object with actually be 30 of October and not 31. For example, this: ``` var d1=new Date('2012-10-31'); ``` Will output this: ``` Tue Oct 30 2012 19:30:00 GMT-0430 (Venezuela Standard Time) ``` Can someone explain why this happens?
2012/10/31
[ "https://Stackoverflow.com/questions/13159303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/478108/" ]
do as you see fit. Each bounded context will have a different domain and surely a different application layer, but we may imagine a common Infrastructure layer ou presentation layer. It really depends on your architectural choices, and on the application you are trying to build. If you want a more precise answer, add some material to your question, so that we can get your context and your problematic.
I think it is not a question about DDD precisely but about an architecture. What kind of coupling between bounded contexts is acceptable/desirable for you. If all your bounded contexts will: * be developed in one programming language * access the same database engine * be developed by a relatively small team (up to ~20 people) then probably you should go with the second approach - each bounded context contains its own domain and application layer and all the bounded contexts share the same infrastructure and application layer. In other cases, you should considering the microservces/SOA architecture.
13,159,303
I'm creating dates from strings with the format 'yyyy-MM-dd' but they're always created on the previous day for some reason. If I set the date as '2012-10-31' the Date object with actually be 30 of October and not 31. For example, this: ``` var d1=new Date('2012-10-31'); ``` Will output this: ``` Tue Oct 30 2012 19:30:00 GMT-0430 (Venezuela Standard Time) ``` Can someone explain why this happens?
2012/10/31
[ "https://Stackoverflow.com/questions/13159303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/478108/" ]
Both are valid approaches. I tend to favour the first option, because it allows better modularity and quite clear boundaries for high level BC. The second option is the 'standard' way of doing this, it favours let's say a more technical layering, while the first option literally favours a more domain driven layering. Choose the one you feel more comfortable with.
I think it is not a question about DDD precisely but about an architecture. What kind of coupling between bounded contexts is acceptable/desirable for you. If all your bounded contexts will: * be developed in one programming language * access the same database engine * be developed by a relatively small team (up to ~20 people) then probably you should go with the second approach - each bounded context contains its own domain and application layer and all the bounded contexts share the same infrastructure and application layer. In other cases, you should considering the microservces/SOA architecture.
23,406,727
I'm trying to simulate (very basic & simple) OS process manager subsystem, I have three "processes" (workers) writing something to console (this is an example): ``` public class Message { public Message() { } public void Show() { while (true) { Console.WriteLine("Something"); Thread.Sleep(100); } } } ``` Each worker is supposed to be run on a different thread. That's how I do it now: I have a Process class which constructor takes Action delegate and starts a thread from it and **suspends it**. ``` public class Process { Thread thrd; Action act; public Process(Action act) { this.act = act; thrd = new Thread(new ThreadStart(this.act)); thrd.Start(); thrd.Suspend(); } public void Suspend() { thrd.Suspend(); } public void Resume() { thrd.Resume(); } } ``` In that state it waits before my scheduler **resumes it, gives it a time slice to run, then suspends it again.** ``` public void Scheduler() { while (true) { //ProcessQueue is just FIFO queue for processes //MainQueue is FIFO queue for ProcessQueue's ProcessQueue currentQueue = mainQueue.Dequeue(); int count = currentQueue.Count; if (currentQueue.Count > 0) { while (count > 0) { Process currentProcess = currentQueue.GetNext(); currentProcess.Resume(); //this is the time slice given to the process Thread.Sleep(1000); currentProcess.Suspend(); Console.WriteLine(); currentQueue.Add(currentProcess); count--; } } mainQueue.Enqueue(currentQueue); } } ``` The problem is that it doesn't work consistently. It even doesn't work at all in this state, i have to add Thread.Sleep() before WriteLine in Show() method of the worker, like this. ``` public void Show() { while (true) { Thread.Sleep(100); //Without this line code doesn't work Console.WriteLine("Something"); Thread.Sleep(100); } } ``` I've been trying to use ManualResetEvent instead of suspend/resume, it works, but since that event is shared, all threads relying on it wake up simultaneously, while I need only one specific thread to be active at one time. If some could help me figure out how to pause/resume task/thread normally, that'd be great. What I'm doing is trying to simulate simple preemptive multitasking. Thanks.
2014/05/01
[ "https://Stackoverflow.com/questions/23406727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492726/" ]
`Thread.Suspend` is evil. It is about as evil as `Thread.Abort`. Almost no code is safe in the presence of being paused at arbitrary, unpredictable locations. It might hold a lock that causes other threads to pause as well. You quickly run into deadlocks or unpredictable stalls in other parts of the system. Imagine you were accidentally pausing the static constructor of `string`. Now all code that wants to use a `string` is halted as well. `Regex` internally uses a locked cache. If you pause while this lock is taken all `Regex` related code might pause. These are just two egregious examples. Probably, suspending some code deep inside the `Console` class is having unintended consequences. I'm not sure what to recommend to you. This seems to be an academic exercise so thankfully this is not a production problem for you. User-mode waiting and cancellation must be cooperative in practice.
I manage to solve this problem using static class with array of ManualResetEvent's, where each process is identified by it's unique ID. But I think it's pretty dirty way to do it. I'm open to other ways of accomplishing this. UPD: added locks to guarantee thread safety ``` public sealed class ControlEvent { private static ManualResetEvent[] control = new ManualResetEvent[100]; private static readonly object _locker = new object(); private ControlEvent() { } public static object Locker { get { return _locker; } } public static void Set(int PID) { control[PID].Set(); } public static void Reset(int PID) { control[PID].Reset(); } public static ManualResetEvent Init(int PID) { control[PID] = new ManualResetEvent(false); return control[PID]; } } ``` In worker class ``` public class RandomNumber { static Random R = new Random(); ManualResetEvent evt; public ManualResetEvent Event { get { return evt; } set { evt = value; } } public void Show() { while (true) { evt.WaitOne(); lock (ControlEvent.Locker) { Console.WriteLine("Random number: " + R.Next(1000)); } Thread.Sleep(100); } } } ``` At Process creation event ``` RandomNumber R = new RandomNumber(); Process proc = new Process(new Action(R.Show)); R.Event = ControlEvent.Init(proc.PID); ``` And, finally, in scheduler ``` public void Scheduler() { while (true) { ProcessQueue currentQueue = mainQueue.Dequeue(); int count = currentQueue.Count; if (currentQueue.Count > 0) { while (count > 0) { Process currentProcess = currentQueue.GetNext(); //this wakes the thread ControlEvent.Set(currentProcess.PID); Thread.Sleep(quant); //this makes it wait again ControlEvent.Reset(currentProcess.PID); currentQueue.Add(currentProcess); count--; } } mainQueue.Enqueue(currentQueue); } } ```
23,406,727
I'm trying to simulate (very basic & simple) OS process manager subsystem, I have three "processes" (workers) writing something to console (this is an example): ``` public class Message { public Message() { } public void Show() { while (true) { Console.WriteLine("Something"); Thread.Sleep(100); } } } ``` Each worker is supposed to be run on a different thread. That's how I do it now: I have a Process class which constructor takes Action delegate and starts a thread from it and **suspends it**. ``` public class Process { Thread thrd; Action act; public Process(Action act) { this.act = act; thrd = new Thread(new ThreadStart(this.act)); thrd.Start(); thrd.Suspend(); } public void Suspend() { thrd.Suspend(); } public void Resume() { thrd.Resume(); } } ``` In that state it waits before my scheduler **resumes it, gives it a time slice to run, then suspends it again.** ``` public void Scheduler() { while (true) { //ProcessQueue is just FIFO queue for processes //MainQueue is FIFO queue for ProcessQueue's ProcessQueue currentQueue = mainQueue.Dequeue(); int count = currentQueue.Count; if (currentQueue.Count > 0) { while (count > 0) { Process currentProcess = currentQueue.GetNext(); currentProcess.Resume(); //this is the time slice given to the process Thread.Sleep(1000); currentProcess.Suspend(); Console.WriteLine(); currentQueue.Add(currentProcess); count--; } } mainQueue.Enqueue(currentQueue); } } ``` The problem is that it doesn't work consistently. It even doesn't work at all in this state, i have to add Thread.Sleep() before WriteLine in Show() method of the worker, like this. ``` public void Show() { while (true) { Thread.Sleep(100); //Without this line code doesn't work Console.WriteLine("Something"); Thread.Sleep(100); } } ``` I've been trying to use ManualResetEvent instead of suspend/resume, it works, but since that event is shared, all threads relying on it wake up simultaneously, while I need only one specific thread to be active at one time. If some could help me figure out how to pause/resume task/thread normally, that'd be great. What I'm doing is trying to simulate simple preemptive multitasking. Thanks.
2014/05/01
[ "https://Stackoverflow.com/questions/23406727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492726/" ]
`Thread.Suspend` is evil. It is about as evil as `Thread.Abort`. Almost no code is safe in the presence of being paused at arbitrary, unpredictable locations. It might hold a lock that causes other threads to pause as well. You quickly run into deadlocks or unpredictable stalls in other parts of the system. Imagine you were accidentally pausing the static constructor of `string`. Now all code that wants to use a `string` is halted as well. `Regex` internally uses a locked cache. If you pause while this lock is taken all `Regex` related code might pause. These are just two egregious examples. Probably, suspending some code deep inside the `Console` class is having unintended consequences. I'm not sure what to recommend to you. This seems to be an academic exercise so thankfully this is not a production problem for you. User-mode waiting and cancellation must be cooperative in practice.
The single best advice I can give with regard to `Suspend()` and `Resume()`: Don't use it. You are doing it wrong™. Whenever you feel a temptation to use `Suspend()` and `Resume()` pairs to control your threads, you should step back immediately and ask yourself, what you are doing here. I understand, that programmers tend to think of the execution of code paths as of something that must be controlled, like some dumb zombie worker that needs permament command and control. That's probably a function of the stuff learned about computers in school and university: Computers do only what you tell them. **Ladies & Gentlemen, here's the bad news:** If you are doing it that way, this is called "micro management", and some even would call it "control freak thinking". Instead, I would strongly encorage you to think about it in a different way. Try to think of your threads as intelligent entities, that do no harm and the only thing they want is to be fed with enough work. They just need a little guidance, that's all. You may place a container full of work just in front of them (**work task queue**) and have them pulling the tasks from that container themselves, as soon as the finished their previous task. When the container is empty, all tasks are processed and there's nothing left to do, they are allowed to fall asleep and `WaitFor(alarm)` which will be signaled whenever new tasks arrive. So instead of command-and-controlling a herd of dumb zombie slaves that can't do anything right without you cracking the whip behind them, you deliberately guide a team of intelligent co-workers and just let it happen. That's the way a scalable architecture is built. You don't have to be a control freak, just have a little faith in your own code. Of course, as always, there are exceptions to that rule. But there aren't that many, and I would recommend to start with the work hypothesis, that your code is probably the rule, rather than the exception.
58,181,553
I have three columns in a pandas dataframe that I want to convert into a single date column. The problem is that one of the columns is day column. I am not able to convert into exact date of that month and year. Can anyone please help me to solve this issue. It looks something like this: ``` BirthMonth BirthYear Day 0 5 88 1st Monday 1 10 87 3rd Tuesday 2 12 87 2nd Saturday 3 1 88 1st Tuesday 4 2 88 1st Monday ```
2019/10/01
[ "https://Stackoverflow.com/questions/58181553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12061738/" ]
Based on your reply to my first comment I updated my answer as follows. I think this is what you are looking for: ``` import re import time import calendar import numpy as np days = ['1st Monday', '3rd Tuesday', '4th wednesday'] months = [2, 3, 5] years = [1990, 2000, 2019] def extract_numeric(text: str): return int(re.findall(r'\d+', text)[0]) def weekday_to_number(weekday: str): return time.strptime(weekday, "%A").tm_wday def get_date(number: int, weekday: int, month: int, year: int) -> str: """ 3rd Tuesday translates to number: 3, weekday: 1 """ firstday, n_days = calendar.monthrange(year, month) day_list = list(range(7)) * 6 month_days = day_list[firstday:][:n_days] day = (np.where(np.array(month_days) == weekday)[0] + 1)[number - 1] return '{}/{}/{}'.format(day, month, year) numbers = [] weekdays = [] for day in days: number, weekday = day.split() numbers.append(extract_numeric(number)) weekdays.append(weekday_to_number(weekday)) dates = [] for number, weekday, month, year in zip(numbers, weekdays, months, years): dates.append(get_date(number, weekday, month, year)) print(dates) # ['5/2/1990', '21/3/2000', '22/5/2019'] ```
**Edit** to match SO new dataframe My solution using pandas dayofweek function: ``` import numpy as np import pandas as pd from datetime import date from dateutil.relativedelta import relativedelta #generate dataframe df=pd.DataFrame({'BirthMonth':[5, 10, 12, 1 ,2], 'BirthYear':[88, 87, 87, 88, 88], 'Day':['1st Monday', '3rd Tuesday', '2nd Saturday','1st Tuesday','1st Monday']}) #Assuming the year refers to 19xx df.BirthYear=1900+df.BirthYear #list of day names weekday=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] #Identify day name in input df days_ex=[s.split()[1].title() for s in df.Day] #initialize output list dateout= ["" for x in range(len(days_ex))] for j in range(len(days_ex)): #Identify the day number in the week (Monday is 1, Sunday is 7) daynum=np.nonzero(np.char.rfind(weekday,days_ex[j])==0)[0][0] #create start and end date for the month date_start=date(df.BirthYear[j],df.BirthMonth[j],1) date_end=date_start+relativedelta(months=+1) #daily index range within month of interest idx=pd.date_range(date_start,date_end,freq='d').dayofweek # Find matching date based on input df realday=np.where(idx==daynum)[0][int(df.Day[j][0])-1]+1 #output list dateout[j]=str(realday)+'/'+str(df.BirthMonth[j])+'/'+str(df.BirthYear[j]) ``` the result i got is: ``` ['2/5/1988', '20/10/1987', '12/12/1987', '5/1/1988', '1/2/1988'] ```
58,181,553
I have three columns in a pandas dataframe that I want to convert into a single date column. The problem is that one of the columns is day column. I am not able to convert into exact date of that month and year. Can anyone please help me to solve this issue. It looks something like this: ``` BirthMonth BirthYear Day 0 5 88 1st Monday 1 10 87 3rd Tuesday 2 12 87 2nd Saturday 3 1 88 1st Tuesday 4 2 88 1st Monday ```
2019/10/01
[ "https://Stackoverflow.com/questions/58181553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12061738/" ]
Based on your reply to my first comment I updated my answer as follows. I think this is what you are looking for: ``` import re import time import calendar import numpy as np days = ['1st Monday', '3rd Tuesday', '4th wednesday'] months = [2, 3, 5] years = [1990, 2000, 2019] def extract_numeric(text: str): return int(re.findall(r'\d+', text)[0]) def weekday_to_number(weekday: str): return time.strptime(weekday, "%A").tm_wday def get_date(number: int, weekday: int, month: int, year: int) -> str: """ 3rd Tuesday translates to number: 3, weekday: 1 """ firstday, n_days = calendar.monthrange(year, month) day_list = list(range(7)) * 6 month_days = day_list[firstday:][:n_days] day = (np.where(np.array(month_days) == weekday)[0] + 1)[number - 1] return '{}/{}/{}'.format(day, month, year) numbers = [] weekdays = [] for day in days: number, weekday = day.split() numbers.append(extract_numeric(number)) weekdays.append(weekday_to_number(weekday)) dates = [] for number, weekday, month, year in zip(numbers, weekdays, months, years): dates.append(get_date(number, weekday, month, year)) print(dates) # ['5/2/1990', '21/3/2000', '22/5/2019'] ```
use the calendar module to get the `day` from days. then convert `day,monyh,year` to `DateTime` ``` import calendar import datetime def get_date(rows): day = {'monday':0,'tuesday':1,'wednesday':2,'thursday':3,'friday':4,'saturday':5,'sunday':6} day_num = day.get(rows.days.split()[1].lower()) weekday_num = [week[day_num] for week in calendar.monthcalendar(rows.years, rows.months) if week[day_num] >0][int(rows.days.split()[0][0])-1] return datetime.date(rows.years, rows.months, weekday_num) ``` apply the above function to all rows ``` df['date'] = df(lambda row: get_date(row), axis=1) df >> days months years date 0 1st Monday 8 2015 2015-08-03 1 3rd Tuesday 12 2017 2017-12-19 2 4th wednesday 5 2019 2019-05-22 ```
58,181,553
I have three columns in a pandas dataframe that I want to convert into a single date column. The problem is that one of the columns is day column. I am not able to convert into exact date of that month and year. Can anyone please help me to solve this issue. It looks something like this: ``` BirthMonth BirthYear Day 0 5 88 1st Monday 1 10 87 3rd Tuesday 2 12 87 2nd Saturday 3 1 88 1st Tuesday 4 2 88 1st Monday ```
2019/10/01
[ "https://Stackoverflow.com/questions/58181553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12061738/" ]
Based on your reply to my first comment I updated my answer as follows. I think this is what you are looking for: ``` import re import time import calendar import numpy as np days = ['1st Monday', '3rd Tuesday', '4th wednesday'] months = [2, 3, 5] years = [1990, 2000, 2019] def extract_numeric(text: str): return int(re.findall(r'\d+', text)[0]) def weekday_to_number(weekday: str): return time.strptime(weekday, "%A").tm_wday def get_date(number: int, weekday: int, month: int, year: int) -> str: """ 3rd Tuesday translates to number: 3, weekday: 1 """ firstday, n_days = calendar.monthrange(year, month) day_list = list(range(7)) * 6 month_days = day_list[firstday:][:n_days] day = (np.where(np.array(month_days) == weekday)[0] + 1)[number - 1] return '{}/{}/{}'.format(day, month, year) numbers = [] weekdays = [] for day in days: number, weekday = day.split() numbers.append(extract_numeric(number)) weekdays.append(weekday_to_number(weekday)) dates = [] for number, weekday, month, year in zip(numbers, weekdays, months, years): dates.append(get_date(number, weekday, month, year)) print(dates) # ['5/2/1990', '21/3/2000', '22/5/2019'] ```
Not very fast solution(since it involves 2 nested loops) but I hope this solves your question ``` import pandas as pd import datetime import calendar pd.set_option('display.max_rows', 100) cols = ['day', 'month', 'year'] data = [ ['1st Monday', 8, 2015], ['3rd Tuesday', 12, 2017], ['4th Wednesday', 5, 2019] ] df = pd.DataFrame(data=data, columns=cols) df['week_number'] = df['day'].str.slice(0, 1) df['week_number'] = df['week_number'].astype('int') df['day_name'] = df['day'].str.slice(4) def generate_dates(input_df, index_num): _, days = calendar.monthrange(input_df.loc[index_num, 'year'], input_df.loc[index_num, 'month']) df_dates = pd.DataFrame() for i in range(1, days + 1): df_dates.loc[i - 1, 'date'] = datetime.date(input_df.loc[index_num, 'year'], input_df.loc[index_num, 'month'], i) df_dates.loc[i - 1, 'year'] = input_df.loc[index_num, 'year'] df_dates.loc[i - 1, 'days'] = calendar.weekday(input_df.loc[index_num, 'year'], input_df.loc[index_num, 'month'], i) df_dates.loc[i - 1, 'day_name'] = df_dates.loc[i - 1, 'date'].strftime("%A") df_dates['week_number'] = 1 df_dates['week_number'] = df_dates.groupby('day_name')['week_number'].cumsum() return df_dates dates = pd.DataFrame(columns=['date', 'year', 'days', 'day_name', 'week_number']) for row in df.index: dates = pd.concat([dates, generate_dates(df, row)]) df2 = df.merge(dates, on=['year', 'day_name', 'week_number']) print(df2) ```
58,181,553
I have three columns in a pandas dataframe that I want to convert into a single date column. The problem is that one of the columns is day column. I am not able to convert into exact date of that month and year. Can anyone please help me to solve this issue. It looks something like this: ``` BirthMonth BirthYear Day 0 5 88 1st Monday 1 10 87 3rd Tuesday 2 12 87 2nd Saturday 3 1 88 1st Tuesday 4 2 88 1st Monday ```
2019/10/01
[ "https://Stackoverflow.com/questions/58181553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12061738/" ]
use the calendar module to get the `day` from days. then convert `day,monyh,year` to `DateTime` ``` import calendar import datetime def get_date(rows): day = {'monday':0,'tuesday':1,'wednesday':2,'thursday':3,'friday':4,'saturday':5,'sunday':6} day_num = day.get(rows.days.split()[1].lower()) weekday_num = [week[day_num] for week in calendar.monthcalendar(rows.years, rows.months) if week[day_num] >0][int(rows.days.split()[0][0])-1] return datetime.date(rows.years, rows.months, weekday_num) ``` apply the above function to all rows ``` df['date'] = df(lambda row: get_date(row), axis=1) df >> days months years date 0 1st Monday 8 2015 2015-08-03 1 3rd Tuesday 12 2017 2017-12-19 2 4th wednesday 5 2019 2019-05-22 ```
**Edit** to match SO new dataframe My solution using pandas dayofweek function: ``` import numpy as np import pandas as pd from datetime import date from dateutil.relativedelta import relativedelta #generate dataframe df=pd.DataFrame({'BirthMonth':[5, 10, 12, 1 ,2], 'BirthYear':[88, 87, 87, 88, 88], 'Day':['1st Monday', '3rd Tuesday', '2nd Saturday','1st Tuesday','1st Monday']}) #Assuming the year refers to 19xx df.BirthYear=1900+df.BirthYear #list of day names weekday=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] #Identify day name in input df days_ex=[s.split()[1].title() for s in df.Day] #initialize output list dateout= ["" for x in range(len(days_ex))] for j in range(len(days_ex)): #Identify the day number in the week (Monday is 1, Sunday is 7) daynum=np.nonzero(np.char.rfind(weekday,days_ex[j])==0)[0][0] #create start and end date for the month date_start=date(df.BirthYear[j],df.BirthMonth[j],1) date_end=date_start+relativedelta(months=+1) #daily index range within month of interest idx=pd.date_range(date_start,date_end,freq='d').dayofweek # Find matching date based on input df realday=np.where(idx==daynum)[0][int(df.Day[j][0])-1]+1 #output list dateout[j]=str(realday)+'/'+str(df.BirthMonth[j])+'/'+str(df.BirthYear[j]) ``` the result i got is: ``` ['2/5/1988', '20/10/1987', '12/12/1987', '5/1/1988', '1/2/1988'] ```
58,181,553
I have three columns in a pandas dataframe that I want to convert into a single date column. The problem is that one of the columns is day column. I am not able to convert into exact date of that month and year. Can anyone please help me to solve this issue. It looks something like this: ``` BirthMonth BirthYear Day 0 5 88 1st Monday 1 10 87 3rd Tuesday 2 12 87 2nd Saturday 3 1 88 1st Tuesday 4 2 88 1st Monday ```
2019/10/01
[ "https://Stackoverflow.com/questions/58181553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12061738/" ]
use the calendar module to get the `day` from days. then convert `day,monyh,year` to `DateTime` ``` import calendar import datetime def get_date(rows): day = {'monday':0,'tuesday':1,'wednesday':2,'thursday':3,'friday':4,'saturday':5,'sunday':6} day_num = day.get(rows.days.split()[1].lower()) weekday_num = [week[day_num] for week in calendar.monthcalendar(rows.years, rows.months) if week[day_num] >0][int(rows.days.split()[0][0])-1] return datetime.date(rows.years, rows.months, weekday_num) ``` apply the above function to all rows ``` df['date'] = df(lambda row: get_date(row), axis=1) df >> days months years date 0 1st Monday 8 2015 2015-08-03 1 3rd Tuesday 12 2017 2017-12-19 2 4th wednesday 5 2019 2019-05-22 ```
Not very fast solution(since it involves 2 nested loops) but I hope this solves your question ``` import pandas as pd import datetime import calendar pd.set_option('display.max_rows', 100) cols = ['day', 'month', 'year'] data = [ ['1st Monday', 8, 2015], ['3rd Tuesday', 12, 2017], ['4th Wednesday', 5, 2019] ] df = pd.DataFrame(data=data, columns=cols) df['week_number'] = df['day'].str.slice(0, 1) df['week_number'] = df['week_number'].astype('int') df['day_name'] = df['day'].str.slice(4) def generate_dates(input_df, index_num): _, days = calendar.monthrange(input_df.loc[index_num, 'year'], input_df.loc[index_num, 'month']) df_dates = pd.DataFrame() for i in range(1, days + 1): df_dates.loc[i - 1, 'date'] = datetime.date(input_df.loc[index_num, 'year'], input_df.loc[index_num, 'month'], i) df_dates.loc[i - 1, 'year'] = input_df.loc[index_num, 'year'] df_dates.loc[i - 1, 'days'] = calendar.weekday(input_df.loc[index_num, 'year'], input_df.loc[index_num, 'month'], i) df_dates.loc[i - 1, 'day_name'] = df_dates.loc[i - 1, 'date'].strftime("%A") df_dates['week_number'] = 1 df_dates['week_number'] = df_dates.groupby('day_name')['week_number'].cumsum() return df_dates dates = pd.DataFrame(columns=['date', 'year', 'days', 'day_name', 'week_number']) for row in df.index: dates = pd.concat([dates, generate_dates(df, row)]) df2 = df.merge(dates, on=['year', 'day_name', 'week_number']) print(df2) ```
152,286
I have a genuine question, I am a noob at stocks. from what I have been reading value investors get higher returns than growth investors but then how come the growth etf IVW gets much higher returns than the value index fund VTV. I've looked at other value ETF's but they sucked even more. Is value investing worth the hype or are these ETF's just bad. If professionals can't do good value investing what chance do we have? Is this a skill worth spending my time in? [![enter image description here](https://i.stack.imgur.com/XMJfI.png)](https://i.stack.imgur.com/XMJfI.png)
2022/08/23
[ "https://money.stackexchange.com/questions/152286", "https://money.stackexchange.com", "https://money.stackexchange.com/users/118279/" ]
"Value investing" is essentially looking for stocks that are cheaper than they "should be" by some measure. That ETF tracks an index of *large cap* value stocks, which may skew the results somewhat, since there may be more smaller "value" stocks that perform better than larger ones. Also note that the two were largely in sync until mid-2018 and mid-2020, where large tech stocks (which are more "growth" than value) dominated from COVID lockdowns (there are many other factors, but that's a significant one). And note that *this year*, VTV has outperformed IVW - the value fund is only down 5% while the growth fund is down 18%. So it may be an anomaly that growth has outperformed over the period you're looking at. If you're a "noob at stocks" then it's best to stick with very broad index funds until you understand more the risks associated with different styles of funds, and slowly move to individual stocks. There's no way to ensure that you pick the "best fund" or even the best strategy going forward. As a young kid, you have plenty of time to make mistakes and learn from them. Don't try to "get rich young" (you might get lucky and do that, but more than likely you'll lose more than you win). Play the long game, save as much as you can, watch it grow, and as you grow you can set aside portions of your portfolio (say 10%) to experiment with individual stocks or other strategies.
Value investing and value stocks are somewhat different. Value investing is, like D Stanley says, figuring out what stocks are cheaper than they should be. Warren Buffet does this by reading public financial statements / disclosures that are required to be made available by law. Value stocks are stocks that make more consistent income, often have dividends, but aren't growing or innovating that much compared to growth stocks. Over the past decade or two, value stocks haven't done that well compared to growth stocks. This may or may not change in the future. At least part of the reason is extremely low interest rates set by the Fed. When borrowing money is cheap, companies that have growth potential can borrow to expand / capture the market and then have time to make a profit. If people believe the Fed will continue raising rates, growth stocks will go down. Once they think the Fed is going to start lowering rates, growth stocks will go back up. This is assuming other factors stay the same. If I were you, I'd start investing mostly in a broad index fund like VOO and I would leave a bit that I could afford to lose and experiment with value investing (which doesn't have to be investing in value stocks) while learning about it. The Intelligent Investor and Security Analysis are two well respected books about how to do value investing.
9,130
Is it scientifically possible to briefly walk on the moon bare footed? What possible side effects could there be? Are these side effects mild enough to make it worth it?
2015/05/16
[ "https://space.stackexchange.com/questions/9130", "https://space.stackexchange.com", "https://space.stackexchange.com/users/10160/" ]
There are 3 main threats you'd have to account for: 1. Vacuum. This is discussed in the questions @Forgemonkey linked to. Conclusion: brief exposure of the feet only is survivable. 2. Temperature. Surface temperatures on the Moon swing between + 120 and - 150 °C, so you'd have to pick your spot carefully to have a survivable temperature. 3. Cuts and abrasion. Lunar [regolith](http://www.airspacemag.com/space/stronger-than-dirt-8944228/?no-ist) is [very sharp](http://www.universetoday.com/96208/the-moon-is-toxic/). It'd be like walking across glass shards. On Earth, dust and sand are subject to erosion from wind and water, which tends to make everything smooth. On the Moon these forces are absent, so e.g. the debris from a meteorite impact all keeps its sharp edges indefinitely. All in all, not a pleasant experience, I'd think.
For the record here's a direct quote, from the [same article](http://www.universetoday.com/96208/the-moon-is-toxic/) Hobbes discovered: > > “The dust was so abrasive that it actually wore through three layers > of Kevlar-like material on Jack [Schmitt’s] boot.” > > > – Professor Larry Taylor, Director of the Planetary Geosciences Institute, University of Tennessee (2008) I observe that the "ground" on Earth is soil, which is an organic substance and (even in the driest places) **very wet and springy**. What we think of as "very dry, hard" earth (in the "outback") is nothing compared to, say, imagine a try with an inch of tiny and large metal filings. I suggest the issue of what the lunar "soil" feels like is somewhat unknown. We do know it wore-through three layers of kevlar, even in the low gravity, in about 20 hours.
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
The syntax issue is – that it requires syntax. Whatever syntax your language has, people using the language have to learn it. Otherwise they run the risk of seeing code and not knowing what it does. Thus it's generally considered a good thing if a language has a simple syntax that cleanly handles a lot of cases. In your specific example, you are trying to take an infix operator (a function that takes two arguments but is written `Argument1 Operator Argument2`) and trying to extend it to multiple arguments. That doesn't work very cleanly because the whole point of infix operators, to the extent that there is one, is to put the operator right in between the 2 arguments. Extending to `(Argument1 Operator Argument2 MagicallyClearSymbol Argument3...)` doesn't seem to add a lot of clarity over `Equals(Arg1,Arg2,...)`. Infix is also typically used to emulate mathematical conventions that people are familiar with, which wouldn't be true of an alternate syntax. There would not be any particular performance issues associated with your idea, other than that the parser would have to deal with a grammar with another production rule or two, which might have a slight effect on the speed of parsing. This might make some difference for an interpreted or JIT compiled language, but probably not a big difference. The bigger problem with the idea is just that making **lots of special cases** in a language tends to be a **bad idea**.
The indexOf method, used on an Array, that quite all languages have, allows to compare a value to several others, so i guess a special operator doesn't make much sense. In javascript that would write : ``` if ( [b, c].indexOf(a) != -1 ) { .... } ```
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
In most languages, this should be trivially achievable by writing an `In` function, so why make it a part of the actual language? Linq, for example, has `Contains()`. Alright, for all you pedants, here's my implementation in C#: ``` public static bool In<T>(this T obj, params T[] values) { for(int i=0; i < values.Length; i++) { if (object.Equals(obj, values[i])) return true; } return false; } ```
Usually, you want to keep your syntax at a minimum and instead allow such constructs to be defined in the language itself. For example, in Haskell you can convert any function with two or more arguments into an infix operator using backticks. This allows you to write: ``` if a `elem` [b, c] then ... else ... ``` where `elem` is just a normal function taking two arguments - a value and a list of values - and checks whether the first is an element of the second. What if you want to use `and` instead of `or`? In Haskell, you can just use the following instead of waiting for the compiler vendor to implement a new feature: ``` if all (== a) [b, c] then ... else ... ```
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
Because it's a non-problem, and solving it brings basically zero benefit, but implementing it brings non-zero cost. Existing range-based functions and such that practically every language does offer can work perfectly well in this situation if it scales to a size where `a == b || a == c` won't cut it.
In most languages, this should be trivially achievable by writing an `In` function, so why make it a part of the actual language? Linq, for example, has `Contains()`. Alright, for all you pedants, here's my implementation in C#: ``` public static bool In<T>(this T obj, params T[] values) { for(int i=0; i < values.Length; i++) { if (object.Equals(obj, values[i])) return true; } return false; } ```
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
Some languages do have such features. E.g. in Perl6 we can use [Junctions](http://perlcabal.org/syn/S03.html#Junctive_operators), which are “superpositions” of two values: ```perl if $a == any($b, $c) { say "yes"; } # syntactic sugar for the above if $a == $b | $c { say "yes"; } ``` Junctions allow us to express operations on a set of data quite succinctly, similar to the way scalar operations distribute over collections in some languages. E.g. using Python with numpy, the comparison can be distribute over all values: ```py import numpy as np 2 == np.array([1, 2, 3]) #=> np.array([False, True, False], dtype=np.bool) (2 == np.array([1, 2, 3])).any() #=> True ``` However, this only works for selected primitive types. Why are junctions problematic? Because operations on a junction distribute over the contained values, the junction object itself behaves like a proxy for method calls – something few type systems aside from duck typing can handle. Type system problems can be avoided if such junctions are only allowed as special *syntax* around comparison operators. But in this case, they are limited so much that they don't add sufficient value to be added to any sane language. The same behavior could be expressed using set operations or spelling out all comparisons manually, and most languages do not believe in adding redundant syntax if there is already a perfectly fine solution.
The indexOf method, used on an Array, that quite all languages have, allows to compare a value to several others, so i guess a special operator doesn't make much sense. In javascript that would write : ``` if ( [b, c].indexOf(a) != -1 ) { .... } ```
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
In some (popular) languages `==` operator is not transitive. For instance in JavaScript `0` is equal to both `''` and `'0'`, but then `''` and `'0'` are not equal to eachother. More of such quirks in PHP. It means that `a == b == c` would add another ambiguity, because it could yield a different result depending on whether it's interpreted as `(a == b) & (a == c)` or `(a == b) & (a == c) & (b == c)`.
The indexOf method, used on an Array, that quite all languages have, allows to compare a value to several others, so i guess a special operator doesn't make much sense. In javascript that would write : ``` if ( [b, c].indexOf(a) != -1 ) { .... } ```
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
Some languages do have such features. E.g. in Perl6 we can use [Junctions](http://perlcabal.org/syn/S03.html#Junctive_operators), which are “superpositions” of two values: ```perl if $a == any($b, $c) { say "yes"; } # syntactic sugar for the above if $a == $b | $c { say "yes"; } ``` Junctions allow us to express operations on a set of data quite succinctly, similar to the way scalar operations distribute over collections in some languages. E.g. using Python with numpy, the comparison can be distribute over all values: ```py import numpy as np 2 == np.array([1, 2, 3]) #=> np.array([False, True, False], dtype=np.bool) (2 == np.array([1, 2, 3])).any() #=> True ``` However, this only works for selected primitive types. Why are junctions problematic? Because operations on a junction distribute over the contained values, the junction object itself behaves like a proxy for method calls – something few type systems aside from duck typing can handle. Type system problems can be avoided if such junctions are only allowed as special *syntax* around comparison operators. But in this case, they are limited so much that they don't add sufficient value to be added to any sane language. The same behavior could be expressed using set operations or spelling out all comparisons manually, and most languages do not believe in adding redundant syntax if there is already a perfectly fine solution.
Some languages do offer this -- to an extent. Maybe not as your *specific* example, but take for example a Python line: ``` def minmax(min, max): def answer(value): return max > value > min return answer inbounds = minmax(5, 15) inbounds(7) ##returns True inbounds(3) ##returns False inbounds(18) ##returns False ``` So, some languages are fine with multiple comparisons, as long as you're expressing it correctly. Unfortunately, it doesn't work quite like you'd expect it to for comparisons. ``` >>> def foo(a, b): ... def answer(value): ... return value == a or b ... return answer ... >>> tester = foo(2, 4) >>> tester(3) 4 >>> tester(2) True >>> tester(4) 4 >>> ``` *"What do you **mean** it returns either True or 4?" -- the hire after you* One solution in this case, at least with Python, is to use it slightly differently: ``` >>> def bar(a, b): ... def ans(val): ... return val == a or val == b ... return ans ... >>> this = bar(4, 10) >>> this(5) False >>> this(4) True >>> this(10) True >>> this(9) False >>> ``` EDIT: The following would also do something similar, again in Python... ``` >>> def bar(a, b): ... def answer(val): ... return val in (a, b) ... return answer ... >>> this = bar(3, 5) >>> this(3) True >>> this(4) False >>> this(5) True >>> ``` So, whichever language you're using, it may not be that you *cannot* do it, just that you must first take a closer look at how the logic actually works. Typically it's just a matter of knowing what you're 'actually asking' the language to tell you.
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
The indexOf method, used on an Array, that quite all languages have, allows to compare a value to several others, so i guess a special operator doesn't make much sense. In javascript that would write : ``` if ( [b, c].indexOf(a) != -1 ) { .... } ```
You ask why can't we do this: `if(a == b or c)` Python does this very efficiently, in fact, most efficiently with `set`: ``` if a in set([b, c]): then_do_this() ``` For membership testing, 'set' checks that the element's hashes are the same and only then compares for equality, so the elements, b and c, must be hashable, otherwise a list directly compares for equality: ``` if a in [b, c]: then_do_this() ```
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
The syntax issue is – that it requires syntax. Whatever syntax your language has, people using the language have to learn it. Otherwise they run the risk of seeing code and not knowing what it does. Thus it's generally considered a good thing if a language has a simple syntax that cleanly handles a lot of cases. In your specific example, you are trying to take an infix operator (a function that takes two arguments but is written `Argument1 Operator Argument2`) and trying to extend it to multiple arguments. That doesn't work very cleanly because the whole point of infix operators, to the extent that there is one, is to put the operator right in between the 2 arguments. Extending to `(Argument1 Operator Argument2 MagicallyClearSymbol Argument3...)` doesn't seem to add a lot of clarity over `Equals(Arg1,Arg2,...)`. Infix is also typically used to emulate mathematical conventions that people are familiar with, which wouldn't be true of an alternate syntax. There would not be any particular performance issues associated with your idea, other than that the parser would have to deal with a grammar with another production rule or two, which might have a slight effect on the speed of parsing. This might make some difference for an interpreted or JIT compiled language, but probably not a big difference. The bigger problem with the idea is just that making **lots of special cases** in a language tends to be a **bad idea**.
Because it's a non-problem, and solving it brings basically zero benefit, but implementing it brings non-zero cost. Existing range-based functions and such that practically every language does offer can work perfectly well in this situation if it scales to a size where `a == b || a == c` won't cut it.
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
Because it's a non-problem, and solving it brings basically zero benefit, but implementing it brings non-zero cost. Existing range-based functions and such that practically every language does offer can work perfectly well in this situation if it scales to a size where `a == b || a == c` won't cut it.
Usually, you want to keep your syntax at a minimum and instead allow such constructs to be defined in the language itself. For example, in Haskell you can convert any function with two or more arguments into an infix operator using backticks. This allows you to write: ``` if a `elem` [b, c] then ... else ... ``` where `elem` is just a normal function taking two arguments - a value and a list of values - and checks whether the first is an element of the second. What if you want to use `and` instead of `or`? In Haskell, you can just use the following instead of waiting for the compiler vendor to implement a new feature: ``` if all (== a) [b, c] then ... else ... ```
237,609
Consider the following: ``` if(a == b or c) ``` In most languages, this would need to be written as: ``` if(a == b or a == c) ``` which is slightly cumbersome and repeats information. I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea. Why don't more languages offer it? Is there performance or syntax issues?
2014/05/01
[ "https://softwareengineering.stackexchange.com/questions/237609", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/97416/" ]
Some languages do have such features. E.g. in Perl6 we can use [Junctions](http://perlcabal.org/syn/S03.html#Junctive_operators), which are “superpositions” of two values: ```perl if $a == any($b, $c) { say "yes"; } # syntactic sugar for the above if $a == $b | $c { say "yes"; } ``` Junctions allow us to express operations on a set of data quite succinctly, similar to the way scalar operations distribute over collections in some languages. E.g. using Python with numpy, the comparison can be distribute over all values: ```py import numpy as np 2 == np.array([1, 2, 3]) #=> np.array([False, True, False], dtype=np.bool) (2 == np.array([1, 2, 3])).any() #=> True ``` However, this only works for selected primitive types. Why are junctions problematic? Because operations on a junction distribute over the contained values, the junction object itself behaves like a proxy for method calls – something few type systems aside from duck typing can handle. Type system problems can be avoided if such junctions are only allowed as special *syntax* around comparison operators. But in this case, they are limited so much that they don't add sufficient value to be added to any sane language. The same behavior could be expressed using set operations or spelling out all comparisons manually, and most languages do not believe in adding redundant syntax if there is already a perfectly fine solution.
"if(a == b or c)" works in most languages: if a == b or if c is not negative, null, or zero. Complaining that it's verbose misses the point: you shouldn't be piling a dozen things into a conditional. If you need to compare one value to an arbitrary number of other values, then build a subroutine.
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
Here is a RxSwift/RxCocoa answer I put together after looking at the other replies. ``` let pages = Variable<[UIViewController]>([]) let currentPageIndex = Variable<Int>(0) let pendingPageIndex = Variable<(Int, Bool)>(0, false) let db = DisposeBag() override func viewDidLoad() { super.viewDidLoad() pendingPageIndex .asDriver() .filter { $0.1 } .map { $0.0 } .drive(currentPageIndex) .addDisposableTo(db) currentPageIndex.asDriver() .drive(pageControl.rx.currentPage) .addDisposableTo(db) } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { if let index = pages.value.index(of: pendingViewControllers.first!) { pendingPageIndex.value = (index, false) } } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { pendingPageIndex.value = (pendingPageIndex.value.0, completed) } ```
Here's the Swifty 2 answer very much based on @zerotool's answer above. Just subclass UIPageViewController and then add this override to find the scrollview and resize it. Then grab the page control and move it to the top of everything else. You also need to set the page controls background color to clear. Those last two lines could go in your app delegate. ``` override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var sv:UIScrollView? var pc:UIPageControl? for v in self.view.subviews{ if v.isKindOfClass(UIScrollView) { sv = v as? UIScrollView }else if v.isKindOfClass(UIPageControl) { pc = v as? UIPageControl } } if let newSv = sv { newSv.frame = self.view.bounds } if let newPc = pc { self.view.bringSubviewToFront(newPc) } } let pageControlAppearance = UIPageControl.appearance() pageControlAppearance.backgroundColor = UIColor.clearColor() ``` btw - I'm not noticing any infinite loops, as mentioned above.
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
After further investigation and searching [I found a solution](https://stackoverflow.com/a/19140401/66414), also on stackoverflow. The key is the following message to send to a custom `UIPageControl` element: ``` [self.view bringSubviewToFront:self.pageControl]; ``` [The AppCoda tutorial is the foundation for this solution](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/): Add a `UIPageControl` element on top of the `RootViewController` - the view controller with the arrow. Create a related `IBOutlet` element in your `ViewController.m`. In the `viewDidLoad` method you should then add the following code as the last method you call after adding all subviews. ``` [self.view bringSubviewToFront:self.pageControl]; ``` To assign the current page based on the pageIndex of the current content view you can add the following to the `UIPageViewControllerDataSource` methods: ``` - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { // ... index--; [self.pageControl setCurrentPage:index]; return [self viewControllerAtIndex:index]; } - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { // ... index++; [self.pageControl setCurrentPage:index]; // ... return [self viewControllerAtIndex:index]; } ```
The same effect can be achieved simply by subclassing UIPageViewController and overriding viewDidLayoutSubviews as follows: ``` -(void)viewDidLayoutSubviews { UIView* v = self.view; NSArray* subviews = v.subviews; if( [subviews count] == 2 ) { UIScrollView* sv = nil; UIPageControl* pc = nil; for( UIView* t in subviews ) { if( [t isKindOfClass:[UIScrollView class]] ) { sv = (UIScrollView*)t; } else if( [t isKindOfClass:[UIPageControl class]] ) { pc = (UIPageControl*)t; } } if( sv != nil && pc != nil ) { // expand scroll view to fit entire view sv.frame = v.bounds; // put page control in front [v bringSubviewToFront:pc]; } } [super viewDidLayoutSubviews]; } ``` Then there is no need to maintain a seperate UIPageControl and such.
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
I didn't have the rep to comment on the answer that originated this, but I really like it. I improved the code and converted it to swift for the below subclass of UIPageViewController: ``` class UIPageViewControllerWithOverlayIndicator: UIPageViewController { override func viewDidLayoutSubviews() { for subView in self.view.subviews as! [UIView] { if subView is UIScrollView { subView.frame = self.view.bounds } else if subView is UIPageControl { self.view.bringSubviewToFront(subView) } } super.viewDidLayoutSubviews() } } ``` Clean and it works well. No need to maintain anything, just make your page view controller an instance of this class in storyboard, or make your custom page view controller class inherit from this class instead.
You have to implement a custom `UIPageControl` and add it to the view. As others have mentioned, `view.bringSubviewToFront(pageControl)` must be called. I have an [example](http://samwize.com/2016/03/08/using-uipageviewcontroller-with-custom-uipagecontrol/) of a view controller with all the code on setting up a custom `UIPageControl` (in storyboard) with `UIPageViewController` There are 2 methods which you need to implement to set the current page indicator. ``` func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) { pendingIndex = pages.indexOf(pendingViewControllers.first!) } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { currentIndex = pendingIndex if let index = currentIndex { pageControl.currentPage = index } } } ```
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
The same effect can be achieved simply by subclassing UIPageViewController and overriding viewDidLayoutSubviews as follows: ``` -(void)viewDidLayoutSubviews { UIView* v = self.view; NSArray* subviews = v.subviews; if( [subviews count] == 2 ) { UIScrollView* sv = nil; UIPageControl* pc = nil; for( UIView* t in subviews ) { if( [t isKindOfClass:[UIScrollView class]] ) { sv = (UIScrollView*)t; } else if( [t isKindOfClass:[UIPageControl class]] ) { pc = (UIPageControl*)t; } } if( sv != nil && pc != nil ) { // expand scroll view to fit entire view sv.frame = v.bounds; // put page control in front [v bringSubviewToFront:pc]; } } [super viewDidLayoutSubviews]; } ``` Then there is no need to maintain a seperate UIPageControl and such.
Here is a RxSwift/RxCocoa answer I put together after looking at the other replies. ``` let pages = Variable<[UIViewController]>([]) let currentPageIndex = Variable<Int>(0) let pendingPageIndex = Variable<(Int, Bool)>(0, false) let db = DisposeBag() override func viewDidLoad() { super.viewDidLoad() pendingPageIndex .asDriver() .filter { $0.1 } .map { $0.0 } .drive(currentPageIndex) .addDisposableTo(db) currentPageIndex.asDriver() .drive(pageControl.rx.currentPage) .addDisposableTo(db) } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { if let index = pages.value.index(of: pendingViewControllers.first!) { pendingPageIndex.value = (index, false) } } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { pendingPageIndex.value = (pendingPageIndex.value.0, completed) } ```
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
The same effect can be achieved simply by subclassing UIPageViewController and overriding viewDidLayoutSubviews as follows: ``` -(void)viewDidLayoutSubviews { UIView* v = self.view; NSArray* subviews = v.subviews; if( [subviews count] == 2 ) { UIScrollView* sv = nil; UIPageControl* pc = nil; for( UIView* t in subviews ) { if( [t isKindOfClass:[UIScrollView class]] ) { sv = (UIScrollView*)t; } else if( [t isKindOfClass:[UIPageControl class]] ) { pc = (UIPageControl*)t; } } if( sv != nil && pc != nil ) { // expand scroll view to fit entire view sv.frame = v.bounds; // put page control in front [v bringSubviewToFront:pc]; } } [super viewDidLayoutSubviews]; } ``` Then there is no need to maintain a seperate UIPageControl and such.
Here's the Swifty 2 answer very much based on @zerotool's answer above. Just subclass UIPageViewController and then add this override to find the scrollview and resize it. Then grab the page control and move it to the top of everything else. You also need to set the page controls background color to clear. Those last two lines could go in your app delegate. ``` override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var sv:UIScrollView? var pc:UIPageControl? for v in self.view.subviews{ if v.isKindOfClass(UIScrollView) { sv = v as? UIScrollView }else if v.isKindOfClass(UIPageControl) { pc = v as? UIPageControl } } if let newSv = sv { newSv.frame = self.view.bounds } if let newPc = pc { self.view.bringSubviewToFront(newPc) } } let pageControlAppearance = UIPageControl.appearance() pageControlAppearance.backgroundColor = UIColor.clearColor() ``` btw - I'm not noticing any infinite loops, as mentioned above.
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
After further investigation and searching [I found a solution](https://stackoverflow.com/a/19140401/66414), also on stackoverflow. The key is the following message to send to a custom `UIPageControl` element: ``` [self.view bringSubviewToFront:self.pageControl]; ``` [The AppCoda tutorial is the foundation for this solution](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/): Add a `UIPageControl` element on top of the `RootViewController` - the view controller with the arrow. Create a related `IBOutlet` element in your `ViewController.m`. In the `viewDidLoad` method you should then add the following code as the last method you call after adding all subviews. ``` [self.view bringSubviewToFront:self.pageControl]; ``` To assign the current page based on the pageIndex of the current content view you can add the following to the `UIPageViewControllerDataSource` methods: ``` - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { // ... index--; [self.pageControl setCurrentPage:index]; return [self viewControllerAtIndex:index]; } - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { // ... index++; [self.pageControl setCurrentPage:index]; // ... return [self viewControllerAtIndex:index]; } ```
You have to implement a custom `UIPageControl` and add it to the view. As others have mentioned, `view.bringSubviewToFront(pageControl)` must be called. I have an [example](http://samwize.com/2016/03/08/using-uipageviewcontroller-with-custom-uipagecontrol/) of a view controller with all the code on setting up a custom `UIPageControl` (in storyboard) with `UIPageViewController` There are 2 methods which you need to implement to set the current page indicator. ``` func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) { pendingIndex = pages.indexOf(pendingViewControllers.first!) } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { currentIndex = pendingIndex if let index = currentIndex { pageControl.currentPage = index } } } ```
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
After further investigation and searching [I found a solution](https://stackoverflow.com/a/19140401/66414), also on stackoverflow. The key is the following message to send to a custom `UIPageControl` element: ``` [self.view bringSubviewToFront:self.pageControl]; ``` [The AppCoda tutorial is the foundation for this solution](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/): Add a `UIPageControl` element on top of the `RootViewController` - the view controller with the arrow. Create a related `IBOutlet` element in your `ViewController.m`. In the `viewDidLoad` method you should then add the following code as the last method you call after adding all subviews. ``` [self.view bringSubviewToFront:self.pageControl]; ``` To assign the current page based on the pageIndex of the current content view you can add the following to the `UIPageViewControllerDataSource` methods: ``` - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { // ... index--; [self.pageControl setCurrentPage:index]; return [self viewControllerAtIndex:index]; } - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { // ... index++; [self.pageControl setCurrentPage:index]; // ... return [self viewControllerAtIndex:index]; } ```
Here's the Swifty 2 answer very much based on @zerotool's answer above. Just subclass UIPageViewController and then add this override to find the scrollview and resize it. Then grab the page control and move it to the top of everything else. You also need to set the page controls background color to clear. Those last two lines could go in your app delegate. ``` override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var sv:UIScrollView? var pc:UIPageControl? for v in self.view.subviews{ if v.isKindOfClass(UIScrollView) { sv = v as? UIScrollView }else if v.isKindOfClass(UIPageControl) { pc = v as? UIPageControl } } if let newSv = sv { newSv.frame = self.view.bounds } if let newPc = pc { self.view.bringSubviewToFront(newPc) } } let pageControlAppearance = UIPageControl.appearance() pageControlAppearance.backgroundColor = UIColor.clearColor() ``` btw - I'm not noticing any infinite loops, as mentioned above.
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
sn3ek Your answer got me most of the way there. I didn't set the current page using the `viewControllerCreation` methods though. I made my `ViewController also` the delegate of the `UIPageViewController`. Then I set the `PageControl`'s `CurrentPage` in that method. Using the `pageIndex` maintained I'm the `ContentViewController` mention in the original article. ``` - (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed { APPChildViewController *currentViewController = pageViewController.viewControllers[0]; [self.pageControl setCurrentPage:currentViewController.pageIndex]; } ``` don't forget to add this to `viewDidLoad` ``` self.pageViewController.delegate = self; ``` To follow up on PropellerHead's comment the interface for the `ViewController` will have the form ``` @interface ViewController : UIViewController <UIPageViewControllerDataSource, UIPageViewControllerDelegate> ```
You have to implement a custom `UIPageControl` and add it to the view. As others have mentioned, `view.bringSubviewToFront(pageControl)` must be called. I have an [example](http://samwize.com/2016/03/08/using-uipageviewcontroller-with-custom-uipagecontrol/) of a view controller with all the code on setting up a custom `UIPageControl` (in storyboard) with `UIPageViewController` There are 2 methods which you need to implement to set the current page indicator. ``` func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) { pendingIndex = pages.indexOf(pendingViewControllers.first!) } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { currentIndex = pendingIndex if let index = currentIndex { pageControl.currentPage = index } } } ```
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
After further investigation and searching [I found a solution](https://stackoverflow.com/a/19140401/66414), also on stackoverflow. The key is the following message to send to a custom `UIPageControl` element: ``` [self.view bringSubviewToFront:self.pageControl]; ``` [The AppCoda tutorial is the foundation for this solution](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/): Add a `UIPageControl` element on top of the `RootViewController` - the view controller with the arrow. Create a related `IBOutlet` element in your `ViewController.m`. In the `viewDidLoad` method you should then add the following code as the last method you call after adding all subviews. ``` [self.view bringSubviewToFront:self.pageControl]; ``` To assign the current page based on the pageIndex of the current content view you can add the following to the `UIPageViewControllerDataSource` methods: ``` - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { // ... index--; [self.pageControl setCurrentPage:index]; return [self viewControllerAtIndex:index]; } - (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { // ... index++; [self.pageControl setCurrentPage:index]; // ... return [self viewControllerAtIndex:index]; } ```
sn3ek Your answer got me most of the way there. I didn't set the current page using the `viewControllerCreation` methods though. I made my `ViewController also` the delegate of the `UIPageViewController`. Then I set the `PageControl`'s `CurrentPage` in that method. Using the `pageIndex` maintained I'm the `ContentViewController` mention in the original article. ``` - (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed { APPChildViewController *currentViewController = pageViewController.viewControllers[0]; [self.pageControl setCurrentPage:currentViewController.pageIndex]; } ``` don't forget to add this to `viewDidLoad` ``` self.pageViewController.delegate = self; ``` To follow up on PropellerHead's comment the interface for the `ViewController` will have the form ``` @interface ViewController : UIViewController <UIPageViewControllerDataSource, UIPageViewControllerDelegate> ```
21,045,630
Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom. When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen. How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element? I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/): ![enter image description here](https://i.stack.imgur.com/pR5KH.jpg)
2014/01/10
[ "https://Stackoverflow.com/questions/21045630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66414/" ]
I didn't have the rep to comment on the answer that originated this, but I really like it. I improved the code and converted it to swift for the below subclass of UIPageViewController: ``` class UIPageViewControllerWithOverlayIndicator: UIPageViewController { override func viewDidLayoutSubviews() { for subView in self.view.subviews as! [UIView] { if subView is UIScrollView { subView.frame = self.view.bounds } else if subView is UIPageControl { self.view.bringSubviewToFront(subView) } } super.viewDidLayoutSubviews() } } ``` Clean and it works well. No need to maintain anything, just make your page view controller an instance of this class in storyboard, or make your custom page view controller class inherit from this class instead.
The same effect can be achieved simply by subclassing UIPageViewController and overriding viewDidLayoutSubviews as follows: ``` -(void)viewDidLayoutSubviews { UIView* v = self.view; NSArray* subviews = v.subviews; if( [subviews count] == 2 ) { UIScrollView* sv = nil; UIPageControl* pc = nil; for( UIView* t in subviews ) { if( [t isKindOfClass:[UIScrollView class]] ) { sv = (UIScrollView*)t; } else if( [t isKindOfClass:[UIPageControl class]] ) { pc = (UIPageControl*)t; } } if( sv != nil && pc != nil ) { // expand scroll view to fit entire view sv.frame = v.bounds; // put page control in front [v bringSubviewToFront:pc]; } } [super viewDidLayoutSubviews]; } ``` Then there is no need to maintain a seperate UIPageControl and such.
69,089,637
I'm using React Native, and I have a functional component that has a function in it. This child component is located inside another component, on that another component I have a button. So, When the user clicks the button, I want to execute the function in the child component. I read about forwardRef (as I saw few questions about this that suggested this solution): <https://reactjs.org/docs/forwarding-refs.html> But it does not seems to fit my problem. I don't need to access an element in my child component, only to execute the function. This is my child component: ``` const Popup = () => { const opacity = useRef(new Animated.Value(1)).current; const translationY = useRef(new Animated.Value(-120)).current; const {theme} = useContext(ThemeContext); const displayPopup = () => { Animated.spring(translationY, { toValue: 100, useNativeDriver: true, }).start(); }; return ( <Animated.View style={[ styles.container, { backgroundColor: theme.popup, opacity: opacity, transform: [{translateY: translationY}], }, ]}> ... </Animated.View> ); }; ``` Inside the parent component: ``` <SafeAreaView> // Other components <Popup /> <Button onPress={() => {//NEEDS TO CALL displayPopup}}/> </SafeAreaView> ```
2021/09/07
[ "https://Stackoverflow.com/questions/69089637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7868565/" ]
Using a forward ref to give access to a child function can be a solution, but it's not the React way to do it (See [useImperativeHandle hook](https://reactjs.org/docs/hooks-reference.html#useimperativehandle)) Instead, I would change a props of the Popup component to trigger the animation you want to use: ``` import { useEffect } from "react"; const Popup = ({display = false}) => { const opacity = useRef(new Animated.Value(1)).current; const translationY = useRef(new Animated.Value(-120)).current; const {theme} = useContext(ThemeContext); useEffect(() => { if(display){ Animated.spring(translationY, { toValue: 100, useNativeDriver: true, }).start(); } }, [display]) return ( <Animated.View style={[ styles.container, { backgroundColor: theme.popup, opacity: opacity, transform: [{translateY: translationY}], }, ]}> ... </Animated.View> ); }; ``` Parent component: ``` const [display, setDisplay] = useState(false); return( <SafeAreaView> // Other components <Popup display={display} /> <Button onPress={() => {setDisplay(true)}}/> </SafeAreaView> ) ```
You can define `Animated.value` in the parent component and put it in the props of child component: ```jsx const Parent = () => { const translationY = useRef(new Animated.Value(-120)).current; const displayPopup = useCallback(() => { Animated.spring(translationY, { toValue: 100, useNativeDriver: true, }).start(); }, [translationY]); return ( <SafeAreaView> <Popup translationY={translationY}/> <Button onPress={displayPopup}/> </SafeAreaView> ); }; const Popup = ({translationY}) => { const opacity = useRef(new Animated.Value(1)).current; const {theme} = useContext(ThemeContext); return ( <Animated.View style={[ styles.container, { backgroundColor: theme.popup, opacity: opacity, transform: [{translateY: translationY}], }, ]}> ... </Animated.View> ); }; ```
69,089,637
I'm using React Native, and I have a functional component that has a function in it. This child component is located inside another component, on that another component I have a button. So, When the user clicks the button, I want to execute the function in the child component. I read about forwardRef (as I saw few questions about this that suggested this solution): <https://reactjs.org/docs/forwarding-refs.html> But it does not seems to fit my problem. I don't need to access an element in my child component, only to execute the function. This is my child component: ``` const Popup = () => { const opacity = useRef(new Animated.Value(1)).current; const translationY = useRef(new Animated.Value(-120)).current; const {theme} = useContext(ThemeContext); const displayPopup = () => { Animated.spring(translationY, { toValue: 100, useNativeDriver: true, }).start(); }; return ( <Animated.View style={[ styles.container, { backgroundColor: theme.popup, opacity: opacity, transform: [{translateY: translationY}], }, ]}> ... </Animated.View> ); }; ``` Inside the parent component: ``` <SafeAreaView> // Other components <Popup /> <Button onPress={() => {//NEEDS TO CALL displayPopup}}/> </SafeAreaView> ```
2021/09/07
[ "https://Stackoverflow.com/questions/69089637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7868565/" ]
Using a forward ref to give access to a child function can be a solution, but it's not the React way to do it (See [useImperativeHandle hook](https://reactjs.org/docs/hooks-reference.html#useimperativehandle)) Instead, I would change a props of the Popup component to trigger the animation you want to use: ``` import { useEffect } from "react"; const Popup = ({display = false}) => { const opacity = useRef(new Animated.Value(1)).current; const translationY = useRef(new Animated.Value(-120)).current; const {theme} = useContext(ThemeContext); useEffect(() => { if(display){ Animated.spring(translationY, { toValue: 100, useNativeDriver: true, }).start(); } }, [display]) return ( <Animated.View style={[ styles.container, { backgroundColor: theme.popup, opacity: opacity, transform: [{translateY: translationY}], }, ]}> ... </Animated.View> ); }; ``` Parent component: ``` const [display, setDisplay] = useState(false); return( <SafeAreaView> // Other components <Popup display={display} /> <Button onPress={() => {setDisplay(true)}}/> </SafeAreaView> ) ```
You can use a `ref` forward it to the child component and use [`useImparativeHandle`](https://reactjs.org/docs/hooks-reference.html#useimperativehandle) in the child to augment the ref so that the parent can invoke it. Just run this code snippet: ```js const { useState, useRef, createRef, forwardRef, useImperativeHandle } = React; const TextInput = forwardRef(({value, otherProps}, ref) => { const [text, setText] = useState(value || ""); const clearText = () => setText(""); // augment the ref by adding the clearText function useImperativeHandle(ref, () => ({ clearText })); return ( <input ref={ref} type="text" onChange={(e) => setText(e.target.value)} value={text} {...otherProps} /> ); }); const Parent = () => { const textRef = createRef(); const onClickButton = () => textRef.current.clearText(); return ( <div> <TextInput ref={textRef} value="Enter Text" /> <button onClick={() => onClickButton()}>Clear Text</button> </div> ); }; ReactDOM.render(<Parent />, document.getElementById("root")); ``` ```html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="root"></div> ``` As the [React docs](https://reactjs.org/docs/hooks-reference.html#useimperativehandle) states > > As always, imperative code using refs should be avoided in most cases. > > > and later they say > > In this example, a parent component that renders would be able to call inputRef.current.focus(). > > > It's up to you to decide if your code is one of the few cases in which it makes sense.
31,030,780
I have an xaml page with 40 rectangles, (4x10 grid), all named in the format r1-1 through to r10-4. I would like to iterate through these in code: ``` for (int row = 1; row < 10; row++) { for (int col = 1; col < 4; col++) { ...// what do I need here } } ``` Any help please?
2015/06/24
[ "https://Stackoverflow.com/questions/31030780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954884/" ]
Although I wouldn't recommend doing this, you can simply iterate through all of the items in the `Grid Panel` if you have a reference to it. Try something like this: ``` foreach (UIElement element in YourGrid.Children) { // do something with each element here } ```
You can find your control by type or by name: *By type*: ``` public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject { if (depObj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject child = VisualTreeHelper.GetChild(depObj, i); if (child != null && child is T) { yield return (T)child; } foreach (T childOfChild in FindVisualChildren<T>(child)) { yield return childOfChild; } } } } ``` Then you can iterate through the Visual Tree: ``` foreach (Rectangle r in FindVisualChildren<Rectangle>(window)) { // do something with r here } ``` *By name*: ``` for (int row = 1; row < 10; row++) { for (int col = 1; col < 4; col++) { var control = this.FindName(string.Format("r{0}-r{1}", row.ToString(), col.ToString())); } } ```
31,030,780
I have an xaml page with 40 rectangles, (4x10 grid), all named in the format r1-1 through to r10-4. I would like to iterate through these in code: ``` for (int row = 1; row < 10; row++) { for (int col = 1; col < 4; col++) { ...// what do I need here } } ``` Any help please?
2015/06/24
[ "https://Stackoverflow.com/questions/31030780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954884/" ]
You can get dynamically an element by its name using the following : ``` for (int row = 1; row < 10; row++) { for (int col = 1; col < 4; col++) { var elt = this.FindName("r" + row + "-" + col); // do some stuff } } ```
You can find your control by type or by name: *By type*: ``` public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject { if (depObj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject child = VisualTreeHelper.GetChild(depObj, i); if (child != null && child is T) { yield return (T)child; } foreach (T childOfChild in FindVisualChildren<T>(child)) { yield return childOfChild; } } } } ``` Then you can iterate through the Visual Tree: ``` foreach (Rectangle r in FindVisualChildren<Rectangle>(window)) { // do something with r here } ``` *By name*: ``` for (int row = 1; row < 10; row++) { for (int col = 1; col < 4; col++) { var control = this.FindName(string.Format("r{0}-r{1}", row.ToString(), col.ToString())); } } ```
37,810,011
So at the moment I am doing some iPhone and iPad testing and noticed a very annoying bug in relation to scrolling. So at the moment I have my basic page like so: ``` <body> <div> Content of my website... <button>This button uses jQuery to add a class to the fixed-form div</button> </div> <div class="fixed-form"> <form> </form> </div> </body> ``` This is a very basic HTML example that show my basic content area inside the body however I also have a div called `fixed-form`, when the button is pressed in the content area this then adds a class with the following styling to the `fixed-form` div: ``` z-index:0; color:#fff; position: fixed; height: 100% !important; overflow-y:auto; -webkit-overflow-scrolling: touch; overflow-x:hidden; top:0; width:100%; z-index:999 !important; ``` The `fixed-form` div then covers the viewport. The issue is that the content/body behind the `fixed-form` is still scrollable and elements are still clickable. Surely the z-index would have stopped this from happening however it has not. Any idea why this might be happening? I would just like to completely disable all of the content that is not the `fixed-form` div to be disabled from scrolling and clickable. UPDATE: So far I have tried adding overflow:hidden to the content div however this does stop horizontal scrolling but does not effect the vertical scrolling issue. Thanks
2016/06/14
[ "https://Stackoverflow.com/questions/37810011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5929529/" ]
Is your image too large? Try uploading smaller images (a few 100 KBs in size). If that works, try compressing, or reducing the resolution of the image before encoding it. Here is an example: <https://stackoverflow.com/a/20382559/1237117> Another option is to increase the json size limit at your Web API. ``` <configuration> <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="50000000"/> </webServices> </scripting> </system.web.extensions> </configuration> ```
Try doing a request first to get an empty object from the backend. Set the properties of the object in javascript, and send the modified object back to the server. ``` $scope.model = {}; $http.get(apiPath).then(function(result){ $scope.model = result.data; }); $scope.model.EncodedImage = base64ImageString; $scope.model.Name = "Rajiv"; $http.post(apiPath, $scope.model).then(function(result){ // ... }); ``` Also remove `[FromBody]` in the backend, and `string` in your `UserInfo` class should be written with a small letter.
37,810,011
So at the moment I am doing some iPhone and iPad testing and noticed a very annoying bug in relation to scrolling. So at the moment I have my basic page like so: ``` <body> <div> Content of my website... <button>This button uses jQuery to add a class to the fixed-form div</button> </div> <div class="fixed-form"> <form> </form> </div> </body> ``` This is a very basic HTML example that show my basic content area inside the body however I also have a div called `fixed-form`, when the button is pressed in the content area this then adds a class with the following styling to the `fixed-form` div: ``` z-index:0; color:#fff; position: fixed; height: 100% !important; overflow-y:auto; -webkit-overflow-scrolling: touch; overflow-x:hidden; top:0; width:100%; z-index:999 !important; ``` The `fixed-form` div then covers the viewport. The issue is that the content/body behind the `fixed-form` is still scrollable and elements are still clickable. Surely the z-index would have stopped this from happening however it has not. Any idea why this might be happening? I would just like to completely disable all of the content that is not the `fixed-form` div to be disabled from scrolling and clickable. UPDATE: So far I have tried adding overflow:hidden to the content div however this does stop horizontal scrolling but does not effect the vertical scrolling issue. Thanks
2016/06/14
[ "https://Stackoverflow.com/questions/37810011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5929529/" ]
Is your image too large? Try uploading smaller images (a few 100 KBs in size). If that works, try compressing, or reducing the resolution of the image before encoding it. Here is an example: <https://stackoverflow.com/a/20382559/1237117> Another option is to increase the json size limit at your Web API. ``` <configuration> <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="50000000"/> </webServices> </scripting> </system.web.extensions> </configuration> ```
You must incresase maxRequestLength under in <httpRuntime ... I got the answer from [forumAsp net](https://forums.asp.net/t/1999382.aspx?WEB%20API%20Not%20able%20to%20post%20JSON%20file%20larger%20than%207%20MB%20)
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
Proportionally, it's probably fair to say that very few programmers sufficiently understand synchronization and concurrency. Who knows how many server applications there are out there right now managing financial transactions, medical records, police records, telephony etc etc that are full of synchronization bugs and essentially work by accident, or very very occasionally fail (never heard of anybody get a phantom phone call added to their telephone bill?) for reasons that are never really looked into or gotten to the bottom of. Object publication is a particular problem because it's often overlooked, and it's a place where it's quite reasonable for compilers to make optimisations that could result in unexpected behaviour if you don't know about it: in the JIT-compiled code, storing a pointer, then incrementing it and storing the data is a very reasonable thing to do. You might think it's "evil", but at a low level, it's really how you'd expect the JVM spec to be. (Incidentally, I've heard of real-life programs running in JRockit suffering from this problem-- it's not purely theoretical.) If you know that your application has synchronization bugs but isn't misbehaving in your current JVM on your current hardware, then (a) congratulations; and (b), now is the time to start "walking calmly towards the fire exit", fixing your code and educating your programmers before you need to upgrade too many components.
I would say very few programmers are away of this issue. When was the last code example you have seen that used the volatile keyword? However, most of the other conditioned mentioned - I just took for granted as best practices. If a developer completely neglects those conditions, they will quickly encounter multi-threading errors.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
It's not a matter of being "evil". It **is** a real problem, and will become much more apparent with the rise of multicore architectures in the coming years. I have seen very real production bugs due to improper synchronization. And to answer your other question, I would say that very few programmers are aware of the issue, even among otherwise "good" developers.
My experience (short-terming and consulting in lots of different kinds of environments Most applications I've seen) agrees with this intuition - I've never seen an entire system clearly architected to manage this problem carefully (well, I've also almost never seen an entire system clearly architected) . I've worked with very, very few developers with a good knowledge of threading issues. Especially with web apps, you can often get away with this, or at least seem to get away with it. If you have spring-based instantiations managing your object creation and stateless servlets, you can often pretend that there's no such thing as synchronization, and this is sort where lots of applications end up. Eventually someone starts putting some shared state where it doesn't belong and 3 months later someone notices some wierd intermittent errors. This is often "good enough" for many people (as long as you're not writing banking transactions). How many java developer are aware of this problem? Hard to say, as it depends heavily on where you work.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
Proportionally, it's probably fair to say that very few programmers sufficiently understand synchronization and concurrency. Who knows how many server applications there are out there right now managing financial transactions, medical records, police records, telephony etc etc that are full of synchronization bugs and essentially work by accident, or very very occasionally fail (never heard of anybody get a phantom phone call added to their telephone bill?) for reasons that are never really looked into or gotten to the bottom of. Object publication is a particular problem because it's often overlooked, and it's a place where it's quite reasonable for compilers to make optimisations that could result in unexpected behaviour if you don't know about it: in the JIT-compiled code, storing a pointer, then incrementing it and storing the data is a very reasonable thing to do. You might think it's "evil", but at a low level, it's really how you'd expect the JVM spec to be. (Incidentally, I've heard of real-life programs running in JRockit suffering from this problem-- it's not purely theoretical.) If you know that your application has synchronization bugs but isn't misbehaving in your current JVM on your current hardware, then (a) congratulations; and (b), now is the time to start "walking calmly towards the fire exit", fixing your code and educating your programmers before you need to upgrade too many components.
"is this really a real problem?" Yes absolutely. Even the most trivial web application has to confront issues surrounding concurrency. Servlets are accessed by multiple threads, for example. The other issue is that threading and concurrency is very hard to handle correctly. It is almost too hard. That is why we are seeing trends emerge like transactional memory, and languages like Clojure that hopefully make concurrency easier to deal with. But we have a ways to go before these become main stream. Thus we have to do the best with what we have. Reading JCiP is a very good start.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
It's not a matter of being "evil". It **is** a real problem, and will become much more apparent with the rise of multicore architectures in the coming years. I have seen very real production bugs due to improper synchronization. And to answer your other question, I would say that very few programmers are aware of the issue, even among otherwise "good" developers.
I would say very few programmers are away of this issue. When was the last code example you have seen that used the volatile keyword? However, most of the other conditioned mentioned - I just took for granted as best practices. If a developer completely neglects those conditions, they will quickly encounter multi-threading errors.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
"is this really a real problem?" Yes absolutely. Even the most trivial web application has to confront issues surrounding concurrency. Servlets are accessed by multiple threads, for example. The other issue is that threading and concurrency is very hard to handle correctly. It is almost too hard. That is why we are seeing trends emerge like transactional memory, and languages like Clojure that hopefully make concurrency easier to deal with. But we have a ways to go before these become main stream. Thus we have to do the best with what we have. Reading JCiP is a very good start.
My experience (short-terming and consulting in lots of different kinds of environments Most applications I've seen) agrees with this intuition - I've never seen an entire system clearly architected to manage this problem carefully (well, I've also almost never seen an entire system clearly architected) . I've worked with very, very few developers with a good knowledge of threading issues. Especially with web apps, you can often get away with this, or at least seem to get away with it. If you have spring-based instantiations managing your object creation and stateless servlets, you can often pretend that there's no such thing as synchronization, and this is sort where lots of applications end up. Eventually someone starts putting some shared state where it doesn't belong and 3 months later someone notices some wierd intermittent errors. This is often "good enough" for many people (as long as you're not writing banking transactions). How many java developer are aware of this problem? Hard to say, as it depends heavily on where you work.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
"is this really a real problem?" Yes absolutely. Even the most trivial web application has to confront issues surrounding concurrency. Servlets are accessed by multiple threads, for example. The other issue is that threading and concurrency is very hard to handle correctly. It is almost too hard. That is why we are seeing trends emerge like transactional memory, and languages like Clojure that hopefully make concurrency easier to deal with. But we have a ways to go before these become main stream. Thus we have to do the best with what we have. Reading JCiP is a very good start.
Firstly "safe publication" is not really an idiom (IMO). It comes straight from the language. There have been cases of problems with unsafe publication, with use of NIO for instance. Most Java code is very badly written. Threaded code is obviously more difficult than average line-of-business code.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
Proportionally, it's probably fair to say that very few programmers sufficiently understand synchronization and concurrency. Who knows how many server applications there are out there right now managing financial transactions, medical records, police records, telephony etc etc that are full of synchronization bugs and essentially work by accident, or very very occasionally fail (never heard of anybody get a phantom phone call added to their telephone bill?) for reasons that are never really looked into or gotten to the bottom of. Object publication is a particular problem because it's often overlooked, and it's a place where it's quite reasonable for compilers to make optimisations that could result in unexpected behaviour if you don't know about it: in the JIT-compiled code, storing a pointer, then incrementing it and storing the data is a very reasonable thing to do. You might think it's "evil", but at a low level, it's really how you'd expect the JVM spec to be. (Incidentally, I've heard of real-life programs running in JRockit suffering from this problem-- it's not purely theoretical.) If you know that your application has synchronization bugs but isn't misbehaving in your current JVM on your current hardware, then (a) congratulations; and (b), now is the time to start "walking calmly towards the fire exit", fixing your code and educating your programmers before you need to upgrade too many components.
It's not a matter of being "evil". It **is** a real problem, and will become much more apparent with the rise of multicore architectures in the coming years. I have seen very real production bugs due to improper synchronization. And to answer your other question, I would say that very few programmers are aware of the issue, even among otherwise "good" developers.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
Firstly "safe publication" is not really an idiom (IMO). It comes straight from the language. There have been cases of problems with unsafe publication, with use of NIO for instance. Most Java code is very badly written. Threaded code is obviously more difficult than average line-of-business code.
I would say very few programmers are away of this issue. When was the last code example you have seen that used the volatile keyword? However, most of the other conditioned mentioned - I just took for granted as best practices. If a developer completely neglects those conditions, they will quickly encounter multi-threading errors.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
Proportionally, it's probably fair to say that very few programmers sufficiently understand synchronization and concurrency. Who knows how many server applications there are out there right now managing financial transactions, medical records, police records, telephony etc etc that are full of synchronization bugs and essentially work by accident, or very very occasionally fail (never heard of anybody get a phantom phone call added to their telephone bill?) for reasons that are never really looked into or gotten to the bottom of. Object publication is a particular problem because it's often overlooked, and it's a place where it's quite reasonable for compilers to make optimisations that could result in unexpected behaviour if you don't know about it: in the JIT-compiled code, storing a pointer, then incrementing it and storing the data is a very reasonable thing to do. You might think it's "evil", but at a low level, it's really how you'd expect the JVM spec to be. (Incidentally, I've heard of real-life programs running in JRockit suffering from this problem-- it's not purely theoretical.) If you know that your application has synchronization bugs but isn't misbehaving in your current JVM on your current hardware, then (a) congratulations; and (b), now is the time to start "walking calmly towards the fire exit", fixing your code and educating your programmers before you need to upgrade too many components.
My experience (short-terming and consulting in lots of different kinds of environments Most applications I've seen) agrees with this intuition - I've never seen an entire system clearly architected to manage this problem carefully (well, I've also almost never seen an entire system clearly architected) . I've worked with very, very few developers with a good knowledge of threading issues. Especially with web apps, you can often get away with this, or at least seem to get away with it. If you have spring-based instantiations managing your object creation and stateless servlets, you can often pretend that there's no such thing as synchronization, and this is sort where lots of applications end up. Eventually someone starts putting some shared state where it doesn't belong and 3 months later someone notices some wierd intermittent errors. This is often "good enough" for many people (as long as you're not writing banking transactions). How many java developer are aware of this problem? Hard to say, as it depends heavily on where you work.
801,993
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. > > > My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
2009/04/29
[ "https://Stackoverflow.com/questions/801993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148909/" ]
Proportionally, it's probably fair to say that very few programmers sufficiently understand synchronization and concurrency. Who knows how many server applications there are out there right now managing financial transactions, medical records, police records, telephony etc etc that are full of synchronization bugs and essentially work by accident, or very very occasionally fail (never heard of anybody get a phantom phone call added to their telephone bill?) for reasons that are never really looked into or gotten to the bottom of. Object publication is a particular problem because it's often overlooked, and it's a place where it's quite reasonable for compilers to make optimisations that could result in unexpected behaviour if you don't know about it: in the JIT-compiled code, storing a pointer, then incrementing it and storing the data is a very reasonable thing to do. You might think it's "evil", but at a low level, it's really how you'd expect the JVM spec to be. (Incidentally, I've heard of real-life programs running in JRockit suffering from this problem-- it's not purely theoretical.) If you know that your application has synchronization bugs but isn't misbehaving in your current JVM on your current hardware, then (a) congratulations; and (b), now is the time to start "walking calmly towards the fire exit", fixing your code and educating your programmers before you need to upgrade too many components.
Firstly "safe publication" is not really an idiom (IMO). It comes straight from the language. There have been cases of problems with unsafe publication, with use of NIO for instance. Most Java code is very badly written. Threaded code is obviously more difficult than average line-of-business code.
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
Try ``` foreach ($array as $val) { $indexes .= "[$val]"; } ${'output'.$indexes} = 'something'; ``` Or ``` $indexes = ''; foreach ($array as $val) { $indexes .= "[$val]"; } $output = 'values'.$indexes; $$output = 'something'; ```
Are you trying to provide a new value for the title of book 0 in library 1? If so, you will have to search for library "1", with book "0" and then change the value of the "title". So if all your values in the array have the same six entries, start with loc = 0 look at the values at loc+1 (library id), loc+3 (book id) and loc+5 .. change title) .. if not increment loc by 6 and continue searching. [sounds like homework, so no code provided. Pardon me if I am wrong.]
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
Are you trying to provide a new value for the title of book 0 in library 1? If so, you will have to search for library "1", with book "0" and then change the value of the "title". So if all your values in the array have the same six entries, start with loc = 0 look at the values at loc+1 (library id), loc+3 (book id) and loc+5 .. change title) .. if not increment loc by 6 and continue searching. [sounds like homework, so no code provided. Pardon me if I am wrong.]
Just in case you weren't aware of it, the key $values["library"][1]["book"][0]["title"][1] Is not the same as the array example in your post. Presuming the array is $values, it has five elements: ``` $values = Array ( [0] => "library" [1] => 1 [2] => "book" [3] => 0 [4] => "title" [5] => 1 ) $values[0] = "Library"; $values[1] = "1"; $values[2] = "book"; $values[3] = "0"; etc... ``` Is this array structure what you intended? If not, post back with a more complete structure so we can help. Also, you need quotes around the strings - I have included for clarity You could take a look at the following [link](http://php.net/manual/en/function.array-search.php) for array\_search. Some of the posters have included examples of a multidimensional array search and there are other examples. Do a google search on "multidimensional array search" and you will likely find a solution. If you need more direction, post back your details.
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
It makes sense to create a function that does this, so: ``` function array_path_set(array & $array, array $path, $newValue) { $aux =& $array; foreach ($path as $key) { if (isset($aux[$key])) { $aux =& $aux[$key]; } else { return false; } } $aux = $newValue; return true; } $values = array( 'library' => array( 1 => array( 'book' => array( 0 => array( 'title' => array( 1 => 'MAGIC VALUE!', ), ), ), ), ), ); $path = array('library', 1, 'book', 0, 'title', 1); $newValue = 'ANOTHER MAGIC VALUE!'; var_dump($values); var_dump(array_path_set($values, $path, $newValue)); var_dump($values); ```
Are you trying to provide a new value for the title of book 0 in library 1? If so, you will have to search for library "1", with book "0" and then change the value of the "title". So if all your values in the array have the same six entries, start with loc = 0 look at the values at loc+1 (library id), loc+3 (book id) and loc+5 .. change title) .. if not increment loc by 6 and continue searching. [sounds like homework, so no code provided. Pardon me if I am wrong.]
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
Are you trying to provide a new value for the title of book 0 in library 1? If so, you will have to search for library "1", with book "0" and then change the value of the "title". So if all your values in the array have the same six entries, start with loc = 0 look at the values at loc+1 (library id), loc+3 (book id) and loc+5 .. change title) .. if not increment loc by 6 and continue searching. [sounds like homework, so no code provided. Pardon me if I am wrong.]
try this -> ``` $keys = array('0'=>'for','1'=>'test','2'=>'only'); $value='ok'; function addArrayPathWithValue($keys,$value,$array = array(),$current = array()) { $function = __FUNCTION__; if (count($current)==0) { $keys = array_reverse($keys); $current = $value; } if (count($keys)==0) { return $current; } $array[array_shift($keys)]=$current; return $function($keys,$value,NULL,$array); } $array = addArrayPathWithValue($keys,$value); print_r($array); //output: Array ( [for] => Array ( [test] => Array ( [only] => ok ) ) ) ```
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
Try ``` foreach ($array as $val) { $indexes .= "[$val]"; } ${'output'.$indexes} = 'something'; ``` Or ``` $indexes = ''; foreach ($array as $val) { $indexes .= "[$val]"; } $output = 'values'.$indexes; $$output = 'something'; ```
Just in case you weren't aware of it, the key $values["library"][1]["book"][0]["title"][1] Is not the same as the array example in your post. Presuming the array is $values, it has five elements: ``` $values = Array ( [0] => "library" [1] => 1 [2] => "book" [3] => 0 [4] => "title" [5] => 1 ) $values[0] = "Library"; $values[1] = "1"; $values[2] = "book"; $values[3] = "0"; etc... ``` Is this array structure what you intended? If not, post back with a more complete structure so we can help. Also, you need quotes around the strings - I have included for clarity You could take a look at the following [link](http://php.net/manual/en/function.array-search.php) for array\_search. Some of the posters have included examples of a multidimensional array search and there are other examples. Do a google search on "multidimensional array search" and you will likely find a solution. If you need more direction, post back your details.
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
It makes sense to create a function that does this, so: ``` function array_path_set(array & $array, array $path, $newValue) { $aux =& $array; foreach ($path as $key) { if (isset($aux[$key])) { $aux =& $aux[$key]; } else { return false; } } $aux = $newValue; return true; } $values = array( 'library' => array( 1 => array( 'book' => array( 0 => array( 'title' => array( 1 => 'MAGIC VALUE!', ), ), ), ), ), ); $path = array('library', 1, 'book', 0, 'title', 1); $newValue = 'ANOTHER MAGIC VALUE!'; var_dump($values); var_dump(array_path_set($values, $path, $newValue)); var_dump($values); ```
Try ``` foreach ($array as $val) { $indexes .= "[$val]"; } ${'output'.$indexes} = 'something'; ``` Or ``` $indexes = ''; foreach ($array as $val) { $indexes .= "[$val]"; } $output = 'values'.$indexes; $$output = 'something'; ```
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
Try ``` foreach ($array as $val) { $indexes .= "[$val]"; } ${'output'.$indexes} = 'something'; ``` Or ``` $indexes = ''; foreach ($array as $val) { $indexes .= "[$val]"; } $output = 'values'.$indexes; $$output = 'something'; ```
try this -> ``` $keys = array('0'=>'for','1'=>'test','2'=>'only'); $value='ok'; function addArrayPathWithValue($keys,$value,$array = array(),$current = array()) { $function = __FUNCTION__; if (count($current)==0) { $keys = array_reverse($keys); $current = $value; } if (count($keys)==0) { return $current; } $array[array_shift($keys)]=$current; return $function($keys,$value,NULL,$array); } $array = addArrayPathWithValue($keys,$value); print_r($array); //output: Array ( [for] => Array ( [test] => Array ( [only] => ok ) ) ) ```
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
It makes sense to create a function that does this, so: ``` function array_path_set(array & $array, array $path, $newValue) { $aux =& $array; foreach ($path as $key) { if (isset($aux[$key])) { $aux =& $aux[$key]; } else { return false; } } $aux = $newValue; return true; } $values = array( 'library' => array( 1 => array( 'book' => array( 0 => array( 'title' => array( 1 => 'MAGIC VALUE!', ), ), ), ), ), ); $path = array('library', 1, 'book', 0, 'title', 1); $newValue = 'ANOTHER MAGIC VALUE!'; var_dump($values); var_dump(array_path_set($values, $path, $newValue)); var_dump($values); ```
Just in case you weren't aware of it, the key $values["library"][1]["book"][0]["title"][1] Is not the same as the array example in your post. Presuming the array is $values, it has five elements: ``` $values = Array ( [0] => "library" [1] => 1 [2] => "book" [3] => 0 [4] => "title" [5] => 1 ) $values[0] = "Library"; $values[1] = "1"; $values[2] = "book"; $values[3] = "0"; etc... ``` Is this array structure what you intended? If not, post back with a more complete structure so we can help. Also, you need quotes around the strings - I have included for clarity You could take a look at the following [link](http://php.net/manual/en/function.array-search.php) for array\_search. Some of the posters have included examples of a multidimensional array search and there are other examples. Do a google search on "multidimensional array search" and you will likely find a solution. If you need more direction, post back your details.
22,445,382
I have this exath path saved somewhere: ``` Array ( [0] => library [1] => 1 [2] => book [3] => 0 [4] => title [5] => 1 ) ``` I have some array and I want to change the value on this index: ``` $values[library][1][book][0][title][1] = "new value"; ``` I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
2014/03/17
[ "https://Stackoverflow.com/questions/22445382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757937/" ]
It makes sense to create a function that does this, so: ``` function array_path_set(array & $array, array $path, $newValue) { $aux =& $array; foreach ($path as $key) { if (isset($aux[$key])) { $aux =& $aux[$key]; } else { return false; } } $aux = $newValue; return true; } $values = array( 'library' => array( 1 => array( 'book' => array( 0 => array( 'title' => array( 1 => 'MAGIC VALUE!', ), ), ), ), ), ); $path = array('library', 1, 'book', 0, 'title', 1); $newValue = 'ANOTHER MAGIC VALUE!'; var_dump($values); var_dump(array_path_set($values, $path, $newValue)); var_dump($values); ```
try this -> ``` $keys = array('0'=>'for','1'=>'test','2'=>'only'); $value='ok'; function addArrayPathWithValue($keys,$value,$array = array(),$current = array()) { $function = __FUNCTION__; if (count($current)==0) { $keys = array_reverse($keys); $current = $value; } if (count($keys)==0) { return $current; } $array[array_shift($keys)]=$current; return $function($keys,$value,NULL,$array); } $array = addArrayPathWithValue($keys,$value); print_r($array); //output: Array ( [for] => Array ( [test] => Array ( [only] => ok ) ) ) ```
32,207
I have been taking 2-3gm of creatine per day mixed extremely well with 16-17oz lukewarm water, that too on workout days (i.e. I avoid the non-workout days) for at least 2.5 months now. However, I feel that the paunch/belly fat I had, as mentioned in [this post of mine](https://fitness.stackexchange.com/questions/32030/how-much-cardio-is-advisable-for-an-overweight-person-who-is-new-to-bodybuilding), has increased considerably. Now, if I start taking whey protein, would the cons (from the pov of fat in belly/waist) overweigh the pros significantly? --- Edit: I linked a wrong thread instead of the one I intended to, earlier. The correction has been made.
2016/09/19
[ "https://fitness.stackexchange.com/questions/32207", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/22139/" ]
To answer the valid question here: ### Does Creatine cause bloating? Yes, the water retention usually seen with higher (>10g) loading doses can exceed five pounds (more than two kilograms). Lower doses may cause less water retention. While water mass is not muscle mass (though both count as lean mass), prolonged creatine supplementation is met with an increased rate of muscle growth. <https://examine.com/supplements/creatine/#hem-weight> Do you need to load creatine? No. <http://examine.com/nutrition/do-i-need-to-load-creatine/> However: **you are retaining more water, not more fat**. Your weight is going up as a result of supplementing creatine increasing water retention but that weight is **not fat**. Some bodybuilders cycle off creatine for competitions but it varies from person-to-person. Note: Some body-fat measuring scales (using electrical resistance) which claim to tell you your body-fat percentage are affected massively by your hydration/water level. Taking creatine may make it read falsely that your body-fat has gone up. --- If that first post was from you I'd say that personally it sounds like you are trying to cut to show abs you probably don't have. Based on the original questions statistics (weigh/height) my personal recommendation would be to focus your main effort on your strength training, following a structured barbell program will help a lot. Consistency is key here.
It can, but I can't tell for sure it's causing the problem in your case, or the other part of your diet is. The fact is, different diet plans work differently on different people. You may be allergic or intolerant to certain components of your diet, or the supplement you are taking. You get yourself checked by a doctor if the issue persists. Why not to go off it for a few weeks, and see how it works? If you just want to look good, you don't need those, but that's just my opinion.
32,207
I have been taking 2-3gm of creatine per day mixed extremely well with 16-17oz lukewarm water, that too on workout days (i.e. I avoid the non-workout days) for at least 2.5 months now. However, I feel that the paunch/belly fat I had, as mentioned in [this post of mine](https://fitness.stackexchange.com/questions/32030/how-much-cardio-is-advisable-for-an-overweight-person-who-is-new-to-bodybuilding), has increased considerably. Now, if I start taking whey protein, would the cons (from the pov of fat in belly/waist) overweigh the pros significantly? --- Edit: I linked a wrong thread instead of the one I intended to, earlier. The correction has been made.
2016/09/19
[ "https://fitness.stackexchange.com/questions/32207", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/22139/" ]
To answer the valid question here: ### Does Creatine cause bloating? Yes, the water retention usually seen with higher (>10g) loading doses can exceed five pounds (more than two kilograms). Lower doses may cause less water retention. While water mass is not muscle mass (though both count as lean mass), prolonged creatine supplementation is met with an increased rate of muscle growth. <https://examine.com/supplements/creatine/#hem-weight> Do you need to load creatine? No. <http://examine.com/nutrition/do-i-need-to-load-creatine/> However: **you are retaining more water, not more fat**. Your weight is going up as a result of supplementing creatine increasing water retention but that weight is **not fat**. Some bodybuilders cycle off creatine for competitions but it varies from person-to-person. Note: Some body-fat measuring scales (using electrical resistance) which claim to tell you your body-fat percentage are affected massively by your hydration/water level. Taking creatine may make it read falsely that your body-fat has gone up. --- If that first post was from you I'd say that personally it sounds like you are trying to cut to show abs you probably don't have. Based on the original questions statistics (weigh/height) my personal recommendation would be to focus your main effort on your strength training, following a structured barbell program will help a lot. Consistency is key here.
@JJosaur's answer is correct. Creatine will slightly increase the amount of water your muscles hold. It will not, and in fact, it can not, increase body fat. That is literally impossible. The amount of water bloat that you get will largely depend on your genetic muscle fiber makeup. Since creatine works better with fast-twitch muscle fibers, individuals with a higher percentage of these fibres will see more effects. Moreover, the recommended dose is generally 5mg, not 2-3...so I can even argue that your body is barely saturated with creatine enough to cause any effect. I'm not sure what you mean by "would taking whey outweigh the cons"... All whey will do is supply you with protein that you couldn't get through your diet. In terms of muscle building, this helps insure proper protein synthesis and recovery. In terms of weight loss, this helps insure you minimize muscle loss. I can confidently say your issues have absolutely nothing to do with creatine/protein or any supplements, work on your diet.
57,172,077
This spreadsheet I am working on tracks trainings. I'm having issues with this because one training counts for itself and fills the requirement for the other. I am trying to apply conditional formatting on column G that turns the cell red if the dates in; * Column F and G are not within 3 years * Column G are blank * Column F = 0 and Column G are not within 3 years Here is my best effort at the formula ``` =OR(AND(TODAY()-$F1>1095,TODAY()-$G1>1095),$G1=0,AND($F1=0,TODAY()-$G1>1095)) ```
2019/07/23
[ "https://Stackoverflow.com/questions/57172077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11826815/" ]
When you build your APK, you will sign the app with a key-store. Once you create a key-store, you will need to get a `sha256 fingerprint`. To get the sha256 you will need to run: `keytool -list -v -keystore /keystore-location/pwa-keystore.ks` Then, make sure the following route available on your web app, containing your sha256 fingerprint generated above. www.example.com/.well-known/assetlinks.json ``` { "relation": ["delegate_permission/common.handle_all_urls"], "target": { "namespace": "scapeq", "package_name": "org.electrobooth.twa.scapeq", "sha256_cert_fingerprints": ["sha256_FINGER_PRINT_GOES_HERE"] } } ] ```
Add this to your manifest before u port to android: ``` "display": "standalone" ```
57,172,077
This spreadsheet I am working on tracks trainings. I'm having issues with this because one training counts for itself and fills the requirement for the other. I am trying to apply conditional formatting on column G that turns the cell red if the dates in; * Column F and G are not within 3 years * Column G are blank * Column F = 0 and Column G are not within 3 years Here is my best effort at the formula ``` =OR(AND(TODAY()-$F1>1095,TODAY()-$G1>1095),$G1=0,AND($F1=0,TODAY()-$G1>1095)) ```
2019/07/23
[ "https://Stackoverflow.com/questions/57172077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11826815/" ]
The domain `toastmasterstimer.tk` seems to be missing the Digital Asset Links file, necessary to validate ownership and enable fullscreen. The file needs to be available at `https://toastmasterstimer.tk/.well-known/assetlinks.json`. You can use the [Statement List Generator and Tester](https://developers.google.com/digital-asset-links/tools/generator) to generate the `assetlinks.json` file. This [section](https://developers.google.com/web/updates/2019/02/using-twa#link-site-to-app) of the documentation provides more information, including how to extract the SHA-256 fingerprint from your signing key.
Add this to your manifest before u port to android: ``` "display": "standalone" ```
57,172,077
This spreadsheet I am working on tracks trainings. I'm having issues with this because one training counts for itself and fills the requirement for the other. I am trying to apply conditional formatting on column G that turns the cell red if the dates in; * Column F and G are not within 3 years * Column G are blank * Column F = 0 and Column G are not within 3 years Here is my best effort at the formula ``` =OR(AND(TODAY()-$F1>1095,TODAY()-$G1>1095),$G1=0,AND($F1=0,TODAY()-$G1>1095)) ```
2019/07/23
[ "https://Stackoverflow.com/questions/57172077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11826815/" ]
Is the sha256 fingerprint you entered in your web/.well-known/assetlinks.json is the same as the one entered in google play console? (On "Release Management" / "App signing" "App signing certificate") ``` [{ "relation": ["delegate_permission/common.handle_all_urls"], "target" : { "namespace": "android_app", "package_name": "package.name", "sha256_cert_fingerprints": ["**this:one**"] } }] ``` [![google play console screenshot](https://i.stack.imgur.com/3q1ep.png)](https://i.stack.imgur.com/3q1ep.png)
Add this to your manifest before u port to android: ``` "display": "standalone" ```
57,172,077
This spreadsheet I am working on tracks trainings. I'm having issues with this because one training counts for itself and fills the requirement for the other. I am trying to apply conditional formatting on column G that turns the cell red if the dates in; * Column F and G are not within 3 years * Column G are blank * Column F = 0 and Column G are not within 3 years Here is my best effort at the formula ``` =OR(AND(TODAY()-$F1>1095,TODAY()-$G1>1095),$G1=0,AND($F1=0,TODAY()-$G1>1095)) ```
2019/07/23
[ "https://Stackoverflow.com/questions/57172077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11826815/" ]
The domain `toastmasterstimer.tk` seems to be missing the Digital Asset Links file, necessary to validate ownership and enable fullscreen. The file needs to be available at `https://toastmasterstimer.tk/.well-known/assetlinks.json`. You can use the [Statement List Generator and Tester](https://developers.google.com/digital-asset-links/tools/generator) to generate the `assetlinks.json` file. This [section](https://developers.google.com/web/updates/2019/02/using-twa#link-site-to-app) of the documentation provides more information, including how to extract the SHA-256 fingerprint from your signing key.
When you build your APK, you will sign the app with a key-store. Once you create a key-store, you will need to get a `sha256 fingerprint`. To get the sha256 you will need to run: `keytool -list -v -keystore /keystore-location/pwa-keystore.ks` Then, make sure the following route available on your web app, containing your sha256 fingerprint generated above. www.example.com/.well-known/assetlinks.json ``` { "relation": ["delegate_permission/common.handle_all_urls"], "target": { "namespace": "scapeq", "package_name": "org.electrobooth.twa.scapeq", "sha256_cert_fingerprints": ["sha256_FINGER_PRINT_GOES_HERE"] } } ] ```
57,172,077
This spreadsheet I am working on tracks trainings. I'm having issues with this because one training counts for itself and fills the requirement for the other. I am trying to apply conditional formatting on column G that turns the cell red if the dates in; * Column F and G are not within 3 years * Column G are blank * Column F = 0 and Column G are not within 3 years Here is my best effort at the formula ``` =OR(AND(TODAY()-$F1>1095,TODAY()-$G1>1095),$G1=0,AND($F1=0,TODAY()-$G1>1095)) ```
2019/07/23
[ "https://Stackoverflow.com/questions/57172077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11826815/" ]
The domain `toastmasterstimer.tk` seems to be missing the Digital Asset Links file, necessary to validate ownership and enable fullscreen. The file needs to be available at `https://toastmasterstimer.tk/.well-known/assetlinks.json`. You can use the [Statement List Generator and Tester](https://developers.google.com/digital-asset-links/tools/generator) to generate the `assetlinks.json` file. This [section](https://developers.google.com/web/updates/2019/02/using-twa#link-site-to-app) of the documentation provides more information, including how to extract the SHA-256 fingerprint from your signing key.
Is the sha256 fingerprint you entered in your web/.well-known/assetlinks.json is the same as the one entered in google play console? (On "Release Management" / "App signing" "App signing certificate") ``` [{ "relation": ["delegate_permission/common.handle_all_urls"], "target" : { "namespace": "android_app", "package_name": "package.name", "sha256_cert_fingerprints": ["**this:one**"] } }] ``` [![google play console screenshot](https://i.stack.imgur.com/3q1ep.png)](https://i.stack.imgur.com/3q1ep.png)
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
Listeners, in general, are a way for the container to notify your app of events, instead of just web requests. For example, to be notified when a session is going to time out, you'd extend HttpSessionListener and implement the sessionDestroyed() method. The container would then call that on expiration of the session and you could log it alongside the login time for that user. For ContextLoaderListener, this lets you kick off non-web related parts of your app, that you want on container startup, instead of waiting on someone to hit one of your spring components. It is using the context-param contextConfigLocation set earlier in your web.xml to know what to start. For RequestContextListener, you get notified of request creation and deletion . Whether they're necessary depends on the architecture of your app.
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>
Create another index for voucher\_date
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).)
Thank's to everyone, I think I did it. Let me know if you find some mistake. Let $X$ locally compact, Hausdorff and non-compact. Prove that if $X$ has only one end, then $X^{\*} - X$ for any compactification $X^{\*}$ (Hausdorff) of $X$ is a continuum (=compact, connected). Solution Since $X^{\*}$ is a Hausdorff compactification of $X$, $X^{\*}$ is compact Hausdorff. Now, since $X$ is locally compact, $X$ is open in $X^{\*}$, so $X^{c}$ is closed in $X^{\*}$, therefore, $K=X^{\*}-X= X^{\*} \cap X^{c}$ is closed in $X^{\*}$ and thereby compact. Assume that $K$ is disconnected, then there exists an $(U,V)$ separation of $K$ such that $U$ y $V$ are closed, $K=U \cup V$ and $U \cap V=\emptyset$. But $X^{\*}$ is normal, since it is compact Hausdorff, so there exists $C$ y $D$ opens of $X^{\*}$ such that $U \subseteq C$, $V \subseteq D$ and $C \cap D =\emptyset$. Let $W=X^{\*}-(C\cup D)$. We observe that $W \subseteq X$ since, \ $W=X^{\*}-(C\cup D) \subseteq X^{\*} \cap (U \cup V)^{c}= X^{\*} \cap K^{c}=X^{\*} \cap (X^{\*}-X)^{c}=X^{\*} \cap X =X$.\ On the other hand $W=X^{\*} -(C \cup D)= X^{\*} \cap (C \cup D)^{c}$ is closed, since $(C \cup D)^{c}$ is closed. $X$ is Hausdorff and $W$ is closed, then $W$ is compact in $X$. \ Define $U\_{X} = C \cap X$ and $V\_{X} = D \cap X$, and observe that they are open in $X^{\*}$, (since $X$ is open in $X^{\*}$), so they are open in $X$ and therfore $U\_{X} \cap V\_{X}=\emptyset$. Now let us calculate the complement of $W$ in $X$. We have that \begin{align\*} X-W & = X-(X^{\*}-(C \cup D))\\ & = X \cap (X^{\*} \cap (C \cup D)^{c})^{c}\\ & = X \cap ((X^{\*})^{c} \cup (C \cup D))\\ & = (X \cap (X^{\*})^{c}) \cup (X \cap (C \cup D))\\ & = (X \cap C) \cup (X \cap D)\\ & = U\_{X} \cup V\_{X}\\ \end{align\*} So, the complement of $W$ are two disjoint connected components, which contradicts the fact that $X$ has only one end.. Therefore $X^{\*} - X$ is a continuum.
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; ```
The problem seems to have been caused by dependencies not having been well updated to support null-safety. I used [this guide](https://dart.dev/null-safety/migration-guide) to make sure that everything was migrated properly, and then it worked again. So basically it wasn't working because I updated Flutter and Dart, but didn't make sure that all the packages were updated to support null safety. For future reference: not all of your previously used packages will support null safety(unless they have been updated to do so), but for some reason unknown, you can still use them in your project regardless. I also noticed there's quite a few packages that have not been updated, but users have created new versions of them called "another\_[packageNameHere]" and it will usually work the same way. If you don't update your packages to use null safety you will get a rain of deprecation warnings.
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.
In addition to @RonMaupin's answer: if the defined gateway is unreachable (and even not configured on the network) there's no way that command can be relevant anymore. It can't be used, so it can safely be removed.
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.
When you get the `getImageData()`, you have an object with `data`, `width` and `height`. You can loop over `data`, which contains the pixel data. It's available in chunks of 4, which are red, green, blue and alpha respectively. Therefore, your code could look for *red* pixels (you have to decide what makes a red pixel) and set the red, green and blue all on (to change it to white). You can then use `putImageData()` to replace the `canvas` with the updated pixel data. ``` // You will need to do this with an image that doesn't violate Same Origin Policy. var imgSrc = "image.png"; var image = new Image; image.addEventListener("load", function() { var canvas = document.getElementsByTagName("canvas")[0]; var ctx = canvas.getContext("2d"); canvas.width = image.width; canvas.height = image.height; ctx.drawImage(image, 0, 0); var imageData = ctx.getImageData(0, 0, image.width, image.height); var pixels = imageData.data; var i; for (i = 0; i < pixels.length; i += 4) { // Is this pixel *red* ? if (pixels[i] > 100) { pixels[i] = 255; pixels[i + 1] = 255; pixels[i + 2] = 255; } } ctx.putImageData(pixels); }); image.src = imgSrc;​ ```
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.
the layer is available from the event; in your case `e.layer` returns the layer alternatively, you save the layer to a variable when you construct it with L.geoJson, then bind your click event later: ```js var streets = L.geoJson(data.streets, { onEachFeature: function(feature, featureLayer) { featureLayer.bindPopup(feature.properties.name); }) )} streets.on('click', function(e) { console.log(e.layer) }); ``` This might be better; as it is now, I think you are binding a click event to the layer for every feature, which is probably not what you want to do.
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.
As per @jessehouwing I used the fiddler and figured out that below file was blocking by the SonicWALL Gateway Antivirus Service. **<http://.../tfs/.../VersionControl/v1.0/upload.ashx>** **<http://.../tfs>** [![enter image description here](https://i.stack.imgur.com/EIgwg.jpg)](https://i.stack.imgur.com/EIgwg.jpg) and all TFS paths are allowed from firewall and now its working perfectly.
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.
For this you can use ``` Symfony\Component\HttpFoundation\File\UploadedFile ``` But please be aware that you can not use the `move()` function, because on move() it will check, if this file has been uploaded via HTTP. If you want to bypass this mechanism, you need to do it on your own. In my application i did it the following way: ``` public static function uploadFile($file, $client, $fromServer = false){ //... unimportant stuff if($file->isValid()){ $upload_success = $file->move($media->path, $media->original_name); } else if($fromServer){ rename($file->getPathname(), $media->path . $media->original_name); $upload_success = true; } else { $upload_success = false; } if(!$upload_success){ throw new \Exception("Upload failed"); } ``` Its also an issue for testing, which you will find here: <https://laracasts.com/discuss/channels/testing/file-upload-unkown-error-with-phpunit> Currently I didnt find an optimal (global) solution to this. But i guess its good the way it is, since you dont want anybody to move files on your server, that are not uploaded via HTTP.
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)
Or you could group `df_winter_start` by type and month, counting up the events, and then use seaborn for plotting: ```py df_counts = df_winter_start[['Disaster_Type', 'month']].value_counts().reset_index(name='count') df_counts ``` ``` Disaster_Type month count 0 Ice 2 21 1 Snow 4 9 2 Ice 3 7 3 Winter 3 6 4 Ice 4 5 5 Winter 6 2 ``` ```py import seaborn as sns cmap = {'Ice': '#1f77b4', 'Snow': '#aec7e8', 'Winter': '#ff7f0e'} sns.barplot(data=df_counts, x='month', y='count', hue='Disaster_Type', palette=cmap); ``` [![winter plot](https://i.stack.imgur.com/sDj4j.png)](https://i.stack.imgur.com/sDj4j.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 ```
For the actual *under-the-hood* stuff, you'll need to grab the Apt source. Fairly simple if you have source repositories enabled: ``` apt-get source apt ``` The `apt-get` command itself lives in `cmdline/apt-get.cc`. It's a pain to read through but most of `apt-get`'s actions are spelled out quite extensively in there. Installation however, is mapped through a `DoInstall` function which lives in `apt-private/private-install.{cc,h}`. You have to remember that apt-get is merely one side of the coin. `dpkg` is handling the actual installation but `DoInstall` doesn't know about `dpkg` directly. `apt-get` is actually surprisingly package-manager agnostic. All the functionality is abstracted through `apt-pkg/package-manager.cc` I'm only looking briefly but even there I can't see where this actually attaches to the `dpkg` systems. Some of this seems to be autoconfigured through `apt-pkg/aptconfiguration.cc` but this is a deep well. You could spend days unravelling this. The source documentation is good though. You could do worse things than to go through each file and read the header to work out what's actually happening.
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 ```
**In short**: `apt-get install` does everything that is needed that your system can successfully execute the new installed software application. **Longer:** **Preliminaries:** From the [manpage](http://manpages.ubuntu.com/manpages/trusty/en/man8/apt-get.8.html): > > All packages required by the package(s) specified for installation > will also be retrieved and installed. > > > Those packages are stored on a repository in the network. So, `apt-get` downloads all the needed ones into a temporary directory (`/var/cache/apt/archives/`). They will be downloaded from a web- or a ftp-server. They are specified in the so called `sources.list`; a list of repositories. From then on they get installed one by one procedurally. The first ones are the ones, that have no further dependencies; so no other package has to be installed for them. Through that, other packages (that had dependencies previously) have now no dependencies anymore. The system keeps doing that process over and over until the specified packages are installed. Each package undergoes an installation procedure. **Package installation:** In Debian-based Linux distributions, as Ubuntu, those packages are in a specified standardized format called: deb - [The Debian binary package format](http://en.wikipedia.org/wiki/Deb_%28file_format%29). Such a package contains the files to be installed on the system. Also they contain a [control file](https://www.debian.org/doc/debian-policy/ch-controlfields.html). That file contains scripts that the packaging system should execute in a specific situation; the so called [maintainer scripts](https://wiki.debian.org/MaintainerScripts). Those scripts are split in: * `preinst`: before the installation of the files into the systems filehierarchy * `postinst`: after the installation * `prerm`: before the uninstallation * `postrm`: after the uninstallation There is an interesting picture, showing the procedure of an installation of a new package: ![installation](https://i.stack.imgur.com/yp41b.png) There are also more control-files, the most important are as follows: * `control`: A [list](https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-sourcecontrolfiles) of the dependencies, and other useful information to identify the package * `conffiles`: A [list](https://www.debian.org/doc/manuals/maint-guide/dother.en.html#conffiles) of config files (usually those in `/etc`) * `debian-binary`: contains the deb-package version, [currently 2.0](http://tldp.org/HOWTO/Debian-Binary-Package-Building-HOWTO/x60.html#AEN66) * `md5sums`: A list of md5sums of each file in the package for verifying * `templates`: A file with [error descriptions and dialogs](https://www.debian.org/doc/packaging-manuals/debconf_specification.html#AEN45) during installation
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 ```
There are some fantastic answers here which are better than this short one, but something you might consider to help you get a better understanding of the changes made by a package manager is [Docker](https://www.docker.com). You can diff the changes made in a container using `docker diff <container>` and it will show you all of the changes. This is especially useful for taking a look under the hood to see what `apt-get install` does to a system. A quick search will get you [several](http://www.scriptrock.com/blog/comparing-containers-generating-dockerfiles-guardrail) [resources](https://stackoverflow.com/questions/21200304/docker-how-to-show-the-diffs-between-2-images) to help implement this.
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/" ]
**In short**: `apt-get install` does everything that is needed that your system can successfully execute the new installed software application. **Longer:** **Preliminaries:** From the [manpage](http://manpages.ubuntu.com/manpages/trusty/en/man8/apt-get.8.html): > > All packages required by the package(s) specified for installation > will also be retrieved and installed. > > > Those packages are stored on a repository in the network. So, `apt-get` downloads all the needed ones into a temporary directory (`/var/cache/apt/archives/`). They will be downloaded from a web- or a ftp-server. They are specified in the so called `sources.list`; a list of repositories. From then on they get installed one by one procedurally. The first ones are the ones, that have no further dependencies; so no other package has to be installed for them. Through that, other packages (that had dependencies previously) have now no dependencies anymore. The system keeps doing that process over and over until the specified packages are installed. Each package undergoes an installation procedure. **Package installation:** In Debian-based Linux distributions, as Ubuntu, those packages are in a specified standardized format called: deb - [The Debian binary package format](http://en.wikipedia.org/wiki/Deb_%28file_format%29). Such a package contains the files to be installed on the system. Also they contain a [control file](https://www.debian.org/doc/debian-policy/ch-controlfields.html). That file contains scripts that the packaging system should execute in a specific situation; the so called [maintainer scripts](https://wiki.debian.org/MaintainerScripts). Those scripts are split in: * `preinst`: before the installation of the files into the systems filehierarchy * `postinst`: after the installation * `prerm`: before the uninstallation * `postrm`: after the uninstallation There is an interesting picture, showing the procedure of an installation of a new package: ![installation](https://i.stack.imgur.com/yp41b.png) There are also more control-files, the most important are as follows: * `control`: A [list](https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-sourcecontrolfiles) of the dependencies, and other useful information to identify the package * `conffiles`: A [list](https://www.debian.org/doc/manuals/maint-guide/dother.en.html#conffiles) of config files (usually those in `/etc`) * `debian-binary`: contains the deb-package version, [currently 2.0](http://tldp.org/HOWTO/Debian-Binary-Package-Building-HOWTO/x60.html#AEN66) * `md5sums`: A list of md5sums of each file in the package for verifying * `templates`: A file with [error descriptions and dialogs](https://www.debian.org/doc/packaging-manuals/debconf_specification.html#AEN45) during installation
For the actual *under-the-hood* stuff, you'll need to grab the Apt source. Fairly simple if you have source repositories enabled: ``` apt-get source apt ``` The `apt-get` command itself lives in `cmdline/apt-get.cc`. It's a pain to read through but most of `apt-get`'s actions are spelled out quite extensively in there. Installation however, is mapped through a `DoInstall` function which lives in `apt-private/private-install.{cc,h}`. You have to remember that apt-get is merely one side of the coin. `dpkg` is handling the actual installation but `DoInstall` doesn't know about `dpkg` directly. `apt-get` is actually surprisingly package-manager agnostic. All the functionality is abstracted through `apt-pkg/package-manager.cc` I'm only looking briefly but even there I can't see where this actually attaches to the `dpkg` systems. Some of this seems to be autoconfigured through `apt-pkg/aptconfiguration.cc` but this is a deep well. You could spend days unravelling this. The source documentation is good though. You could do worse things than to go through each file and read the header to work out what's actually happening.
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/" ]
For the actual *under-the-hood* stuff, you'll need to grab the Apt source. Fairly simple if you have source repositories enabled: ``` apt-get source apt ``` The `apt-get` command itself lives in `cmdline/apt-get.cc`. It's a pain to read through but most of `apt-get`'s actions are spelled out quite extensively in there. Installation however, is mapped through a `DoInstall` function which lives in `apt-private/private-install.{cc,h}`. You have to remember that apt-get is merely one side of the coin. `dpkg` is handling the actual installation but `DoInstall` doesn't know about `dpkg` directly. `apt-get` is actually surprisingly package-manager agnostic. All the functionality is abstracted through `apt-pkg/package-manager.cc` I'm only looking briefly but even there I can't see where this actually attaches to the `dpkg` systems. Some of this seems to be autoconfigured through `apt-pkg/aptconfiguration.cc` but this is a deep well. You could spend days unravelling this. The source documentation is good though. You could do worse things than to go through each file and read the header to work out what's actually happening.
There are some fantastic answers here which are better than this short one, but something you might consider to help you get a better understanding of the changes made by a package manager is [Docker](https://www.docker.com). You can diff the changes made in a container using `docker diff <container>` and it will show you all of the changes. This is especially useful for taking a look under the hood to see what `apt-get install` does to a system. A quick search will get you [several](http://www.scriptrock.com/blog/comparing-containers-generating-dockerfiles-guardrail) [resources](https://stackoverflow.com/questions/21200304/docker-how-to-show-the-diffs-between-2-images) to help implement this.
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/" ]
**In short**: `apt-get install` does everything that is needed that your system can successfully execute the new installed software application. **Longer:** **Preliminaries:** From the [manpage](http://manpages.ubuntu.com/manpages/trusty/en/man8/apt-get.8.html): > > All packages required by the package(s) specified for installation > will also be retrieved and installed. > > > Those packages are stored on a repository in the network. So, `apt-get` downloads all the needed ones into a temporary directory (`/var/cache/apt/archives/`). They will be downloaded from a web- or a ftp-server. They are specified in the so called `sources.list`; a list of repositories. From then on they get installed one by one procedurally. The first ones are the ones, that have no further dependencies; so no other package has to be installed for them. Through that, other packages (that had dependencies previously) have now no dependencies anymore. The system keeps doing that process over and over until the specified packages are installed. Each package undergoes an installation procedure. **Package installation:** In Debian-based Linux distributions, as Ubuntu, those packages are in a specified standardized format called: deb - [The Debian binary package format](http://en.wikipedia.org/wiki/Deb_%28file_format%29). Such a package contains the files to be installed on the system. Also they contain a [control file](https://www.debian.org/doc/debian-policy/ch-controlfields.html). That file contains scripts that the packaging system should execute in a specific situation; the so called [maintainer scripts](https://wiki.debian.org/MaintainerScripts). Those scripts are split in: * `preinst`: before the installation of the files into the systems filehierarchy * `postinst`: after the installation * `prerm`: before the uninstallation * `postrm`: after the uninstallation There is an interesting picture, showing the procedure of an installation of a new package: ![installation](https://i.stack.imgur.com/yp41b.png) There are also more control-files, the most important are as follows: * `control`: A [list](https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-sourcecontrolfiles) of the dependencies, and other useful information to identify the package * `conffiles`: A [list](https://www.debian.org/doc/manuals/maint-guide/dother.en.html#conffiles) of config files (usually those in `/etc`) * `debian-binary`: contains the deb-package version, [currently 2.0](http://tldp.org/HOWTO/Debian-Binary-Package-Building-HOWTO/x60.html#AEN66) * `md5sums`: A list of md5sums of each file in the package for verifying * `templates`: A file with [error descriptions and dialogs](https://www.debian.org/doc/packaging-manuals/debconf_specification.html#AEN45) during installation
There are some fantastic answers here which are better than this short one, but something you might consider to help you get a better understanding of the changes made by a package manager is [Docker](https://www.docker.com). You can diff the changes made in a container using `docker diff <container>` and it will show you all of the changes. This is especially useful for taking a look under the hood to see what `apt-get install` does to a system. A quick search will get you [several](http://www.scriptrock.com/blog/comparing-containers-generating-dockerfiles-guardrail) [resources](https://stackoverflow.com/questions/21200304/docker-how-to-show-the-diffs-between-2-images) to help implement this.
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.
It's possible to reach Jhanic states while not formal sitting, yet can be certain "[dangerous](https://www.youtube.com/watch?v=W8hgPSwHnM8)". (while not serious, actually serious warning). Walking is perfect, but one should not train such in a "dangerous" environment for one self and others but only when already walking renouncing ways. A will of change (sitting, walking, standing, lying), how ever, requires to leave the state, but if good trained, quick may continue. It might occur, but would not be prompted by one knowing what he is doing, while doing other things concentrated. *[Note: not for trade, exchange, stacks and gains binding to world but liberation given]*
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.
According to Sutta Jhana formula, you have to sit cross-legged and keeping your body erects, keeping your mindfulness to the front when you are in first Jhana. In first Jhana you have abandoned five hindrances and acquired five Jhana factors vitakka, vicara, pithi, sukha and ekagata. your speech has ceased and no body pain. Hence walking, talking and eating do not satisfy the Jhana formula.
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.
Perhaps you can stay in Arahattaphla Samadhi while you are walking, talking and eating.
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.
No, it's impossible. That isn't to say that you can't practice walking meditation (or any other technique) in a way that develops the five jhana factors, however. These can be cultivated to quite a significant degree especially if they are done as a supplement to seated meditation. Unfortunately, it's simply not possible to develop one-pointedness to the degree required by full jhana when one's attention has to be split between the object of meditation and the act of walking. By definition, one-pointedness cannot coexist in the midst of multiple objects of attention.
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.
The First Jhana is just sustained thought and attention on the object, with some sukkha (pleasure, bliss), and some piiti (rapture, ecstacy) which are "First dhyāna: the first dhyana can be entered when one is secluded from sensuality and unskillful qualities, due to withdrawal and right effort. There is pīti ("rapture") and non-sensual sukha ("pleasure") as the result of seclusion, while vitarka-vicara ("discursive thought") continues" <https://en.wikipedia.org/wiki/Dhy%C4%81na_in_Buddhism> "you will be overcome with rapture, euphoria, ecstasy, delight. These are all English words that are used to translate the Pali word piti. Perhaps the best English word for piti is “glee.” Piti is a primarily physical sensation that sweeps you powerfully into an altered state. But piti is not solely physical; as the suttas say, “On account of the presence of piti, there is mental exhilaration.” In addition to the physical energy and mental exhilaration, the piti will be accompanied by an emotional sensation of joy and happiness. The Pali word for this joy/happiness is sukha, the opposite of dukkha (pain, suffering). And if you can remain undistractedly focused on this experience of piti and sukha, that is the first jhana." Leigh Brasington - <https://www.lionsroar.com/entering-the-jhanas/> It must be possible to experience these during sitting, standing, lying down, and walking, because they are standard positions for meditation. Eating is also used for meditation so that also. Conversing activates the discrimination mind, rather than the mind moving towards equanimity, so it will diminish the effect of the First Jhana. It is excellent to stabilize samadhi by doing these things, whilst in jhana, but preferably with Noble Silence. "Huisi taught two different forms of the lotus samadhi. The "practice devoid of characteristics", or the practice of ease and bliss, is based on the fourteenth chapter of the Lotus Sutra.[22][23] Huisi explains, "While in the very midst of phenomena [the practitioner discerns that] mental characteristics are quiescent and extinguished and ultimately do not arise. (...) He is constantly immersed in all the profound and wonderful dhyana absorptions because in all activities - walking, standing, sitting, lying down, eating or speaking - his mind is always settled [in samadhi]." <https://en.wikipedia.org/wiki/Nanyue_Huisi>