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
42,853,292
Is there a way to add buttons from a specific wrappanel to an array or list in code? I tried the code below, but it doesn't work: ``` foreach(Button b in nameOfWrappanel) { list.Add(b); } ```
2017/03/17
[ "https://Stackoverflow.com/questions/42853292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790802/" ]
You have to specify wrappanel.children to access its child. ``` foreach (Button b in nameOfWrappanel.Children) { list.Add(b); } ```
You could use Linq: ``` var buttons = myWrapPanel.Children.OfType<Button>().ToList(); ```
42,853,292
Is there a way to add buttons from a specific wrappanel to an array or list in code? I tried the code below, but it doesn't work: ``` foreach(Button b in nameOfWrappanel) { list.Add(b); } ```
2017/03/17
[ "https://Stackoverflow.com/questions/42853292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790802/" ]
You have to specify wrappanel.children to access its child. ``` foreach (Button b in nameOfWrappanel.Children) { list.Add(b); } ```
Since the `Children` property of a `Panel` returns a `UIElementCollection` that may contain any type of `UIElement` objects, you could use the `OfType` LINQ extension method to only retrive the `Button` elements: ``` foreach (Button b in nameOfWrappanel.Children.OfType<Button>()) { list.Add(b); } ```
42,853,292
Is there a way to add buttons from a specific wrappanel to an array or list in code? I tried the code below, but it doesn't work: ``` foreach(Button b in nameOfWrappanel) { list.Add(b); } ```
2017/03/17
[ "https://Stackoverflow.com/questions/42853292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790802/" ]
You could use Linq: ``` var buttons = myWrapPanel.Children.OfType<Button>().ToList(); ```
Since the `Children` property of a `Panel` returns a `UIElementCollection` that may contain any type of `UIElement` objects, you could use the `OfType` LINQ extension method to only retrive the `Button` elements: ``` foreach (Button b in nameOfWrappanel.Children.OfType<Button>()) { list.Add(b); } ```
37,907,105
this is my spring-security.xml: ``` <security:http pattern="/eklienci/**" authentication-manager-ref="authenticationManager" entry-point-ref="restAuthenticationEntryPoint" create-session="stateless"> <security:intercept-url pattern="/eklienci/**" access="hasAnyAuthority('ADMIN','USER','VIEWER')" /> <form-login authentication-success-handler-ref="mySuccessHandler" authentication-failure-handler-ref="myFailureHandler" /> <security:custom-filter ref="restServicesFilter" before="PRE_AUTH_FILTER" /> </security:http> <!-- other stuff --!> <beans:bean id="restAuthenticationEntryPoint" class="pl.aemon.smom.config.RestAuthenticationEntryPoint" /> <!-- Filter for REST services. --> <beans:bean id="restServicesFilter" class="pl.aemon.smom.config.RestUsernamePasswordAuthenticationFilter"> <beans:property name="postOnly" value="true" /> <beans:property name="authenticationManager" ref="authenticationManager" /> <beans:property name="authenticationSuccessHandler" ref="mySuccessHandler" /> </beans:bean> ``` This is my RestUsernamePasswordAuthenticationFilter: ``` public class RestUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { @Autowired private CustomAuthenticationProvider authenticationProvider; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { Enumeration<String> names = request.getHeaderNames(); while(names.hasMoreElements()) { System.out.println(names.nextElement()); } String username = obtainUsername(request); String password = obtainPassword(request); System.out.println("Username " + username + " password: " + password); if(username!=null) { username = username.trim(); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); // Allow subclasses to set the "details" property setDetails(request, authRequest); return authenticationProvider.authenticateRest(authRequest); // System.out.println(auth.toString()); // return auth; } @Override protected String obtainPassword(HttpServletRequest request) { return request.getHeader("password"); } @Override protected String obtainUsername(HttpServletRequest request) { return request.getHeader("username"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Authentication auth = attemptAuthentication(httpRequest, httpResponse); SecurityContextHolder.getContext().setAuthentication(auth); chain.doFilter(request, response); } } ``` And this is my RestController methods ``` @RestController @RequestMapping("/eklienci") public class EklientRestController { @RequestMapping(value="/get/{eklientid}") public Eklient get(@PathVariable String eklientid) { return userService.findById(eklientid); } @RequestMapping(value = "/add", method = RequestMethod.POST, produces="application/json", consumes="application/json") @ResponseBody public String add(@RequestBody String json) { System.out.println(json); Eklient pj = new Eklient(); ObjectMapper mapper = new ObjectMapper(); try { pj = mapper.readValue(json, Eklient.class); return mapper.writeValueAsString(pj); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "Error"; } } ``` When i try to call /get/{eklientid}, it always works fine. All GET calls always returns at least infomration about UNARTHORIZED access (401) and i see logs from RestUsernamePasswordAuthenticationFilter. But when i try any POST call (for example /eklienci /add} my application always returns 403 code and doesn't producde any log. What is the reason? How to fix it ?
2016/06/19
[ "https://Stackoverflow.com/questions/37907105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420030/" ]
[CSRF](http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html) is activated by default for the common non-GET methods like POST, PUT, DELETE causing 403s if you haven't placed the CSRF headers in your REST calls. You can (temporarily!) shut off CSRF in your security.xml to confirm that's the issue. Mainly you'll need to add the [CSRF headers](https://github.com/gmazza/tightblog/blob/b32c215e5c904070d02d6a837496819e05b953f4/app/src/main/webapp/tb-ui/scripts/commonjquery.js#L9-10) into your REST calls and [`<sec:csrfInput/>`](https://github.com/gmazza/tightblog/blob/b32c215e5c904070d02d6a837496819e05b953f4/app/src/main/webapp/WEB-INF/jsps/editor/EntryEdit.jsp#L78) JSPs tags for any client-server calls. FYI, additional classes I needed to implement in my open-source project, perhaps useful for you: 1. [CsrfSecurityRequestMatcher](https://github.com/gmazza/tightblog/blob/master/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CsrfSecurityRequestMatcher.java) to turn off CSRF for certain POSTs/PUTs, etc., that don't require authorization. As configured [here](https://github.com/gmazza/tightblog/blob/b32c215e5c904070d02d6a837496819e05b953f4/app/src/main/webapp/WEB-INF/security.xml#L50) in my security.xml. 2. [CustomAccessDeniedHandlerImpl](https://github.com/gmazza/tightblog/blob/master/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomAccessDeniedHandlerImpl.java) to route CSRF 403's resulting from session timeouts to a login page instead.
Turn off CSRF protection. It is not needed when you have `create-session="stateless"`. ```xml <security:http ...> <security:csrf disabled="true"/> <!-- the rest same as before --> </security:http> ```
18,488,096
Here's my table A ``` orderID groupID nameID 1 grade A foo 2 grade A bar 3 grade A rain 1 grade B rain 2 grade B foo 3 grade B bar 1 grade C rain 2 grade C bar 3 grade C foo ``` Desired result: ``` rain bar foo ``` I need `nameID` of `max(orderID)` from each grade. I can get right `orderID` from each grade, but `nameID` always stays as the first. Thanks a Lot! --- Praveen gave the right query! Extra question under his answer
2013/08/28
[ "https://Stackoverflow.com/questions/18488096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2689375/" ]
**edit:** I just fixed a mistake in my answer. You are looking for something quite like: ``` select orderID, groupID, nameID from A where concat(orderID,'-',groupId) in (select concat(max(orderID),'-',groupId) from A group by groupID) ``` **edit:** in regards to the extra question: To put the list in order of nameId, just add to the query: ``` order by nameID ```
``` SELECT * FROM (select max(`orderID`) as maxID, `groupID`, `nameID` from Table1 GROUP BY `groupID`, `nameID` ORDER BY maxID desc) abc GROUP BY GROUPID ``` **[Fiddle With my test data](http://www.sqlfiddle.com/#!2/e94e8f/5)** **[Fiddle with your data](http://www.sqlfiddle.com/#!2/afdc6/1)**
18,488,096
Here's my table A ``` orderID groupID nameID 1 grade A foo 2 grade A bar 3 grade A rain 1 grade B rain 2 grade B foo 3 grade B bar 1 grade C rain 2 grade C bar 3 grade C foo ``` Desired result: ``` rain bar foo ``` I need `nameID` of `max(orderID)` from each grade. I can get right `orderID` from each grade, but `nameID` always stays as the first. Thanks a Lot! --- Praveen gave the right query! Extra question under his answer
2013/08/28
[ "https://Stackoverflow.com/questions/18488096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2689375/" ]
Here is an appropriate query, using a correlated subquery: ``` select orderID, groupID, nameID from A where orderId = (select max(OrderId) from A a2 where A.groupId = a2.groupId); ``` If you want to do this with aggregation, you can use the `group_concat()`/`substring_index()` trick: ``` SELECT max(orderID) as orderID, groupId, substring_index(group_concat(nameId order by orderId desc), ',', 1) as nameID FROM A GROUP BY groupID; ```
``` SELECT * FROM (select max(`orderID`) as maxID, `groupID`, `nameID` from Table1 GROUP BY `groupID`, `nameID` ORDER BY maxID desc) abc GROUP BY GROUPID ``` **[Fiddle With my test data](http://www.sqlfiddle.com/#!2/e94e8f/5)** **[Fiddle with your data](http://www.sqlfiddle.com/#!2/afdc6/1)**
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
It sounds like your client is detecting loss of connectivity to the server (using Bonjour), but you don't have the corresponding capability in the other direction. You're certainly going to want some kind of timeout for inactive connections on the server side as well, otherwise dead connections will hang around forever. Beyond the problem of potential IP address/port # collisions you mention, there's also the fact that the dead connections are consuming OS and application resources (such as open file descriptors) Conversely, you might also want to consider not being **too** aggressive in closing a connection from the client side when Bonjour says the service is no longer visible. If you're in a wireless scenario, a transient loss of connectivity isn't that uncommon, and it's possible for a TCP connection to remain open and valid after connectivity is restored (assuming the client still has the same IP address). The optimum strategy depends on what kind of connection you're talking about. If it's a relatively stateless connection where the cost of discarding the connection and retrying is low (like HTTP), then it makes sense to toss the connection at the first sign of trouble. But if it's a long-lived connection with significant user state (like an SSH login session), it makes sense to try harder to keep the connection alive.
If you close server socket only in case of blocking socket then client socket will be closed but not vice versa. otherwise it would be better socket in both end. Because socket is a heavy weigt for you system. It will use a local port and a remote port of your system forever. Thanks Sunil Kumar Sahoo
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
A quick/ dirty illustration of why this can't happen (note the client forcibly uses the same local port in its connection): ``` public class Server{ public static void main(String[] args) throws Exception { new Thread(){ java.net.ServerSocket server = new java.net.ServerSocket(12345); java.util.ArrayList<java.net.Socket> l = new java.util.ArrayList<java.net.Socket>(); public void run() { try{ while(true){ java.net.Socket client = server.accept(); System.out.println("Connection Accepted: S: "+client.getLocalPort()+", C: "+client.getPort()); l.add(client); } }catch(Exception e){e.printStackTrace();} } }.start(); } ``` and a client (replace server address with something valid): ``` import java.net.InetAddress; import java.net.Socket; public class SocketTest { public static void main(String[] args) throws Exception { InetAddress server = InetAddress.getByName("192.168.0.256"); InetAddress localhost = InetAddress.getLocalHost(); Socket s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created socket"); s.close(); s = null; System.gc(); System.gc(); Thread.sleep(1000); s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created second socket"); s.close(); System.exit(55); } } ``` If you start the server and then try to run the client the first connection will succeed, but the second will fail with a "java.net.BindException: Address already in use: connect"
the client operating system will not allocate the same port to a new socket so soon. there are several mechanism that prevents it. one of which is the TIME\_WAIT state that reserves the port for some time after the connection is closed. I wouldn't worry about it. if you really need to detect disconnection you will have to implement ping/pong protocol, initiated by both the client and the server.
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
A quick/ dirty illustration of why this can't happen (note the client forcibly uses the same local port in its connection): ``` public class Server{ public static void main(String[] args) throws Exception { new Thread(){ java.net.ServerSocket server = new java.net.ServerSocket(12345); java.util.ArrayList<java.net.Socket> l = new java.util.ArrayList<java.net.Socket>(); public void run() { try{ while(true){ java.net.Socket client = server.accept(); System.out.println("Connection Accepted: S: "+client.getLocalPort()+", C: "+client.getPort()); l.add(client); } }catch(Exception e){e.printStackTrace();} } }.start(); } ``` and a client (replace server address with something valid): ``` import java.net.InetAddress; import java.net.Socket; public class SocketTest { public static void main(String[] args) throws Exception { InetAddress server = InetAddress.getByName("192.168.0.256"); InetAddress localhost = InetAddress.getLocalHost(); Socket s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created socket"); s.close(); s = null; System.gc(); System.gc(); Thread.sleep(1000); s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created second socket"); s.close(); System.exit(55); } } ``` If you start the server and then try to run the client the first connection will succeed, but the second will fail with a "java.net.BindException: Address already in use: connect"
Short answer: yes, you should close socket on both ends. Although the answer is simple, in reality it may be very hard to detect that the peer has stopped responding if you don't build some ACK/NACK scheme into your client-server protocol. Even with your protocol ACKs your processing thread may be hanging waiting for ACKs that will never come from the client or vice versa. If you use Blocking I/O, I would start by setting read timeouts on a socket. Unfortunately, if the peer becomes unresponsive, there is no corresponding time-out for the writes. One blunt instrument that I found has value in our environment is to create blocking Sockets through java.nio methods and then interrupt the processing thread at configurable intervals. Interrupting processing thread will close socket, but if you pick the timeout large enough you will know that there is a trouble. We chose this approach because application was written initially with blocking I/O and a cost to transition it to non-blocking was very high. With the non-blocking I/O, though, you may check at a finer-grained interval the status of your connection and react more intelligently to the slow/unresponsive connections. Though non-blocking I/O requires a higher upfront investment, I think it will pay better dividends in terms of reliability and better throughput later on.
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
Yes, close the socket, as soon as you detect a failure. The socket will be "stuck" in "close\_wait" if not closed properly. Even if the socket is closed, it's state will be in time\_wait for a short period. However, if You design the application to use a different local port for each new connection, there is no need to wait for the old socket to be closed. (As you are then creating a completly different socket, since a socket is identified by the remote-ip, remote port, local ip and local port.)
If you close server socket only in case of blocking socket then client socket will be closed but not vice versa. otherwise it would be better socket in both end. Because socket is a heavy weigt for you system. It will use a local port and a remote port of your system forever. Thanks Sunil Kumar Sahoo
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
Yes, close the socket, as soon as you detect a failure. The socket will be "stuck" in "close\_wait" if not closed properly. Even if the socket is closed, it's state will be in time\_wait for a short period. However, if You design the application to use a different local port for each new connection, there is no need to wait for the old socket to be closed. (As you are then creating a completly different socket, since a socket is identified by the remote-ip, remote port, local ip and local port.)
the client operating system will not allocate the same port to a new socket so soon. there are several mechanism that prevents it. one of which is the TIME\_WAIT state that reserves the port for some time after the connection is closed. I wouldn't worry about it. if you really need to detect disconnection you will have to implement ping/pong protocol, initiated by both the client and the server.
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
A quick/ dirty illustration of why this can't happen (note the client forcibly uses the same local port in its connection): ``` public class Server{ public static void main(String[] args) throws Exception { new Thread(){ java.net.ServerSocket server = new java.net.ServerSocket(12345); java.util.ArrayList<java.net.Socket> l = new java.util.ArrayList<java.net.Socket>(); public void run() { try{ while(true){ java.net.Socket client = server.accept(); System.out.println("Connection Accepted: S: "+client.getLocalPort()+", C: "+client.getPort()); l.add(client); } }catch(Exception e){e.printStackTrace();} } }.start(); } ``` and a client (replace server address with something valid): ``` import java.net.InetAddress; import java.net.Socket; public class SocketTest { public static void main(String[] args) throws Exception { InetAddress server = InetAddress.getByName("192.168.0.256"); InetAddress localhost = InetAddress.getLocalHost(); Socket s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created socket"); s.close(); s = null; System.gc(); System.gc(); Thread.sleep(1000); s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created second socket"); s.close(); System.exit(55); } } ``` If you start the server and then try to run the client the first connection will succeed, but the second will fail with a "java.net.BindException: Address already in use: connect"
It sounds like your client is detecting loss of connectivity to the server (using Bonjour), but you don't have the corresponding capability in the other direction. You're certainly going to want some kind of timeout for inactive connections on the server side as well, otherwise dead connections will hang around forever. Beyond the problem of potential IP address/port # collisions you mention, there's also the fact that the dead connections are consuming OS and application resources (such as open file descriptors) Conversely, you might also want to consider not being **too** aggressive in closing a connection from the client side when Bonjour says the service is no longer visible. If you're in a wireless scenario, a transient loss of connectivity isn't that uncommon, and it's possible for a TCP connection to remain open and valid after connectivity is restored (assuming the client still has the same IP address). The optimum strategy depends on what kind of connection you're talking about. If it's a relatively stateless connection where the cost of discarding the connection and retrying is low (like HTTP), then it makes sense to toss the connection at the first sign of trouble. But if it's a long-lived connection with significant user state (like an SSH login session), it makes sense to try harder to keep the connection alive.
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
Yes, close the socket, as soon as you detect a failure. The socket will be "stuck" in "close\_wait" if not closed properly. Even if the socket is closed, it's state will be in time\_wait for a short period. However, if You design the application to use a different local port for each new connection, there is no need to wait for the old socket to be closed. (As you are then creating a completly different socket, since a socket is identified by the remote-ip, remote port, local ip and local port.)
Short answer: yes, you should close socket on both ends. Although the answer is simple, in reality it may be very hard to detect that the peer has stopped responding if you don't build some ACK/NACK scheme into your client-server protocol. Even with your protocol ACKs your processing thread may be hanging waiting for ACKs that will never come from the client or vice versa. If you use Blocking I/O, I would start by setting read timeouts on a socket. Unfortunately, if the peer becomes unresponsive, there is no corresponding time-out for the writes. One blunt instrument that I found has value in our environment is to create blocking Sockets through java.nio methods and then interrupt the processing thread at configurable intervals. Interrupting processing thread will close socket, but if you pick the timeout large enough you will know that there is a trouble. We chose this approach because application was written initially with blocking I/O and a cost to transition it to non-blocking was very high. With the non-blocking I/O, though, you may check at a finer-grained interval the status of your connection and react more intelligently to the slow/unresponsive connections. Though non-blocking I/O requires a higher upfront investment, I think it will pay better dividends in terms of reliability and better throughput later on.
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
the client operating system will not allocate the same port to a new socket so soon. there are several mechanism that prevents it. one of which is the TIME\_WAIT state that reserves the port for some time after the connection is closed. I wouldn't worry about it. if you really need to detect disconnection you will have to implement ping/pong protocol, initiated by both the client and the server.
If you close server socket only in case of blocking socket then client socket will be closed but not vice versa. otherwise it would be better socket in both end. Because socket is a heavy weigt for you system. It will use a local port and a remote port of your system forever. Thanks Sunil Kumar Sahoo
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
Yes, close the socket, as soon as you detect a failure. The socket will be "stuck" in "close\_wait" if not closed properly. Even if the socket is closed, it's state will be in time\_wait for a short period. However, if You design the application to use a different local port for each new connection, there is no need to wait for the old socket to be closed. (As you are then creating a completly different socket, since a socket is identified by the remote-ip, remote port, local ip and local port.)
It sounds like your client is detecting loss of connectivity to the server (using Bonjour), but you don't have the corresponding capability in the other direction. You're certainly going to want some kind of timeout for inactive connections on the server side as well, otherwise dead connections will hang around forever. Beyond the problem of potential IP address/port # collisions you mention, there's also the fact that the dead connections are consuming OS and application resources (such as open file descriptors) Conversely, you might also want to consider not being **too** aggressive in closing a connection from the client side when Bonjour says the service is no longer visible. If you're in a wireless scenario, a transient loss of connectivity isn't that uncommon, and it's possible for a TCP connection to remain open and valid after connectivity is restored (assuming the client still has the same IP address). The optimum strategy depends on what kind of connection you're talking about. If it's a relatively stateless connection where the cost of discarding the connection and retrying is low (like HTTP), then it makes sense to toss the connection at the first sign of trouble. But if it's a long-lived connection with significant user state (like an SSH login session), it makes sense to try harder to keep the connection alive.
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
A quick/ dirty illustration of why this can't happen (note the client forcibly uses the same local port in its connection): ``` public class Server{ public static void main(String[] args) throws Exception { new Thread(){ java.net.ServerSocket server = new java.net.ServerSocket(12345); java.util.ArrayList<java.net.Socket> l = new java.util.ArrayList<java.net.Socket>(); public void run() { try{ while(true){ java.net.Socket client = server.accept(); System.out.println("Connection Accepted: S: "+client.getLocalPort()+", C: "+client.getPort()); l.add(client); } }catch(Exception e){e.printStackTrace();} } }.start(); } ``` and a client (replace server address with something valid): ``` import java.net.InetAddress; import java.net.Socket; public class SocketTest { public static void main(String[] args) throws Exception { InetAddress server = InetAddress.getByName("192.168.0.256"); InetAddress localhost = InetAddress.getLocalHost(); Socket s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created socket"); s.close(); s = null; System.gc(); System.gc(); Thread.sleep(1000); s = new Socket(server, 12345, localhost, 54321); System.out.println("Client created second socket"); s.close(); System.exit(55); } } ``` If you start the server and then try to run the client the first connection will succeed, but the second will fail with a "java.net.BindException: Address already in use: connect"
If you close server socket only in case of blocking socket then client socket will be closed but not vice versa. otherwise it would be better socket in both end. Because socket is a heavy weigt for you system. It will use a local port and a remote port of your system forever. Thanks Sunil Kumar Sahoo
69,727,847
So I'm making a voice assistant in Python and I want it to do math that I input. This code checks if it ends with an integer: ``` elif text[-1].isdigit() == True: basicmath() ``` Then the function basicmath(): ``` def basicmath(): split = text.split(" ") in1 = split[0] in2 = split[5] op = split[3] print(op) if op == "+": m = in1+in2 worked = "y" mathout = str(m) print(mathout) elif op == "-": m = in1-in2 worked = "y" mathout = str(m) print(mathout) elif op == "*": m = in1*in2 worked = "y" mathout = str(m) print(mathout) elif op == "/": m = in1/in2 worked = "y" mathout = str(m) print(mathout) ``` My terminal doesn't return any errors, it just doesn't run the lines where you assign the variables in1, in2, and op. I really just need to know how to pull lines from the list made by split(). Please keep in mind that I'm still learning Python. Thank you!
2021/10/26
[ "https://Stackoverflow.com/questions/69727847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17245368/" ]
Use `perl=TRUE` with [lookaround](https://www.regular-expressions.info/lookaround.html): ```r vec <- c("2 - 5-< 2", "6 - 10-< 2", "6 - 10-2 - 5", "> 15-2 - 5") strsplit(vec, "(?<! )-(?!= )", perl=TRUE) # [[1]] # [1] "2 - 5" "< 2" # [[2]] # [1] "6 - 10" "< 2" # [[3]] # [1] "6 - 10" "2 - 5" # [[4]] # [1] "> 15" "2 - 5" ```
I guess this is an easier-to-understand solution: ``` library(stringr) str_split(vec, "(?<=\\d)-(?=\\d)") [[1]] [1] "2 - 5" "< 2" [[2]] [1] "6 - 10" "< 2" [[3]] [1] "6 - 10" "2 - 5" [[4]] [1] "> 15" "2 - 5" ``` First off, no `perl = TRUE` needed (well, but a new package, `stringr`). But then, `(?<=\\d)` and `(?=\\d)` are **positive** lookarounds, which are inherently easier to process. The first means: if you see a digit on the left ...; the second says, if you see a digit on the right ... And `str_split`(with the underscore) says, if these two conditions are met, then split on the dash `-`.
29,043,922
I have an image in an HTML email template where the height is being cutoff. I'm using the Zurb Ink email framework. The setup is two images that are supposed to stack on top of each other. From what I can tell the image is being cutoff at 19px in height, while it's actual height is 47px; I'm using Email on Acid to preview the email. The CSS is being inlined before the email is sent using `premailer`. The 2nd image displays fine. Here's the relevant code and screenshots. **HTML** ``` <table class="row banner"> <tr> <td class="wrapper last"> <table class="four columns"> <tr> <td> <img class="hide-for-small" src="url-to-image.jpg" width="179" height="47" style="width:179px; height:47px; line-height:47px;" /> <br/> <img src="url-to-image.jpg" width="179" height="63" style="width:179px; height:63px; line-height:63px;" /> </td> <td class="expander"></td> </tr> </table> </td> </tr> </table> ``` **CSS** ``` img { outline:none; text-decoration:none; -ms-interpolation-mode: bicubic; width: auto; max-width: 100%; float: left; clear: both; display: block; } ``` **Inlined CSS** - after all the CSS is compiled and inlined. ``` td { word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 13px; margin: 0; padding: 0px 0px 10px; } img { width: 179px; height: 47px; line-height: 47px; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; max-width: 100%; float: left; clear: both; display: block; ``` **Screenshots** Outlook 2007/2010 ![enter image description here](https://i.stack.imgur.com/VEIpp.jpg) Normal Email Clients ![enter image description here](https://i.stack.imgur.com/Yp8dq.png) I've tried adding `height`, `style="height"` and `line-height` attributes to force the height but to no luck so far.
2015/03/14
[ "https://Stackoverflow.com/questions/29043922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438581/" ]
Floats don't work in Outlook. What you want is to use `<td align="left|right|center">` instead. You should use `td`'s `valign` and `height` attributes too. The width bit could be causing the problem too, you should set the width of the image via the `width` attribute and then set the style `max-width:100%` inline to accomplish what you want and keep it cross-client.
I ran into the same issue with the height being cut off in Outlook only. I solved this by removing the custom class(es) on my image.
29,043,922
I have an image in an HTML email template where the height is being cutoff. I'm using the Zurb Ink email framework. The setup is two images that are supposed to stack on top of each other. From what I can tell the image is being cutoff at 19px in height, while it's actual height is 47px; I'm using Email on Acid to preview the email. The CSS is being inlined before the email is sent using `premailer`. The 2nd image displays fine. Here's the relevant code and screenshots. **HTML** ``` <table class="row banner"> <tr> <td class="wrapper last"> <table class="four columns"> <tr> <td> <img class="hide-for-small" src="url-to-image.jpg" width="179" height="47" style="width:179px; height:47px; line-height:47px;" /> <br/> <img src="url-to-image.jpg" width="179" height="63" style="width:179px; height:63px; line-height:63px;" /> </td> <td class="expander"></td> </tr> </table> </td> </tr> </table> ``` **CSS** ``` img { outline:none; text-decoration:none; -ms-interpolation-mode: bicubic; width: auto; max-width: 100%; float: left; clear: both; display: block; } ``` **Inlined CSS** - after all the CSS is compiled and inlined. ``` td { word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 13px; margin: 0; padding: 0px 0px 10px; } img { width: 179px; height: 47px; line-height: 47px; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; max-width: 100%; float: left; clear: both; display: block; ``` **Screenshots** Outlook 2007/2010 ![enter image description here](https://i.stack.imgur.com/VEIpp.jpg) Normal Email Clients ![enter image description here](https://i.stack.imgur.com/Yp8dq.png) I've tried adding `height`, `style="height"` and `line-height` attributes to force the height but to no luck so far.
2015/03/14
[ "https://Stackoverflow.com/questions/29043922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438581/" ]
Try setting `mso-line-height-rule: at-least` on the TD that the image sits in. I've found issues with MSO email clients where it would crop images to the line-height unless this option is set correctly.
Floats don't work in Outlook. What you want is to use `<td align="left|right|center">` instead. You should use `td`'s `valign` and `height` attributes too. The width bit could be causing the problem too, you should set the width of the image via the `width` attribute and then set the style `max-width:100%` inline to accomplish what you want and keep it cross-client.
29,043,922
I have an image in an HTML email template where the height is being cutoff. I'm using the Zurb Ink email framework. The setup is two images that are supposed to stack on top of each other. From what I can tell the image is being cutoff at 19px in height, while it's actual height is 47px; I'm using Email on Acid to preview the email. The CSS is being inlined before the email is sent using `premailer`. The 2nd image displays fine. Here's the relevant code and screenshots. **HTML** ``` <table class="row banner"> <tr> <td class="wrapper last"> <table class="four columns"> <tr> <td> <img class="hide-for-small" src="url-to-image.jpg" width="179" height="47" style="width:179px; height:47px; line-height:47px;" /> <br/> <img src="url-to-image.jpg" width="179" height="63" style="width:179px; height:63px; line-height:63px;" /> </td> <td class="expander"></td> </tr> </table> </td> </tr> </table> ``` **CSS** ``` img { outline:none; text-decoration:none; -ms-interpolation-mode: bicubic; width: auto; max-width: 100%; float: left; clear: both; display: block; } ``` **Inlined CSS** - after all the CSS is compiled and inlined. ``` td { word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 13px; margin: 0; padding: 0px 0px 10px; } img { width: 179px; height: 47px; line-height: 47px; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; max-width: 100%; float: left; clear: both; display: block; ``` **Screenshots** Outlook 2007/2010 ![enter image description here](https://i.stack.imgur.com/VEIpp.jpg) Normal Email Clients ![enter image description here](https://i.stack.imgur.com/Yp8dq.png) I've tried adding `height`, `style="height"` and `line-height` attributes to force the height but to no luck so far.
2015/03/14
[ "https://Stackoverflow.com/questions/29043922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438581/" ]
Try setting `mso-line-height-rule: at-least` on the TD that the image sits in. I've found issues with MSO email clients where it would crop images to the line-height unless this option is set correctly.
I ran into the same issue with the height being cut off in Outlook only. I solved this by removing the custom class(es) on my image.
5,988,673
iam developing WPF product. I want to protect my .net source code from reverse enginering Please advice me
2011/05/13
[ "https://Stackoverflow.com/questions/5988673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714681/" ]
You would use an obfuscator. There are a lot of them on the market, just google. For example, Visual Studio used to ship with the [Dotfuscator Community Edition](http://www.preemptive.com/products/dotfuscator). I never used it, so I can't say anything about its quality. This blog post shows the possible ways to try to prevent reverse engineering: <http://blogs.msdn.com/b/ericgu/archive/2004/02/24/79236.aspx>
In the end it will always be possible to reverse engineer the code. Obfuscation can help but your code will never completely be protected. The only way to fully protect the code is by not deploying it but instead keeping it on a server.
5,988,673
iam developing WPF product. I want to protect my .net source code from reverse enginering Please advice me
2011/05/13
[ "https://Stackoverflow.com/questions/5988673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714681/" ]
You would use an obfuscator. There are a lot of them on the market, just google. For example, Visual Studio used to ship with the [Dotfuscator Community Edition](http://www.preemptive.com/products/dotfuscator). I never used it, so I can't say anything about its quality. This blog post shows the possible ways to try to prevent reverse engineering: <http://blogs.msdn.com/b/ericgu/archive/2004/02/24/79236.aspx>
Obfuscating your assemblies will ensure that it is difficult (if not impossible) to reverse-engineer your compiled assemblies. Obfuscators use techniques like symbol renaming, string encryption, control flow obfuscation to try to obfuscate the meaning of the original code. In some cases, it is even possible to totally hide the code from decompilers (however, decompilers are constantly evolving to overcome this). Take a look at [Crypto Obfuscator](http://www.ssware.com/cryptoobfuscator/obfuscator-net.htm). DISCLAIMER: I work for LogicNP, the developer of Crypto Obfuscator.
5,988,673
iam developing WPF product. I want to protect my .net source code from reverse enginering Please advice me
2011/05/13
[ "https://Stackoverflow.com/questions/5988673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714681/" ]
You would use an obfuscator. There are a lot of them on the market, just google. For example, Visual Studio used to ship with the [Dotfuscator Community Edition](http://www.preemptive.com/products/dotfuscator). I never used it, so I can't say anything about its quality. This blog post shows the possible ways to try to prevent reverse engineering: <http://blogs.msdn.com/b/ericgu/archive/2004/02/24/79236.aspx>
You can use FxProtect obfuscator. It successfully supports WPF and Silverlight obfuscation. You can try it... **[.NET Obfuscator](http://www.maycoms.net)**
5,988,673
iam developing WPF product. I want to protect my .net source code from reverse enginering Please advice me
2011/05/13
[ "https://Stackoverflow.com/questions/5988673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714681/" ]
In the end it will always be possible to reverse engineer the code. Obfuscation can help but your code will never completely be protected. The only way to fully protect the code is by not deploying it but instead keeping it on a server.
You can use FxProtect obfuscator. It successfully supports WPF and Silverlight obfuscation. You can try it... **[.NET Obfuscator](http://www.maycoms.net)**
5,988,673
iam developing WPF product. I want to protect my .net source code from reverse enginering Please advice me
2011/05/13
[ "https://Stackoverflow.com/questions/5988673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714681/" ]
Obfuscating your assemblies will ensure that it is difficult (if not impossible) to reverse-engineer your compiled assemblies. Obfuscators use techniques like symbol renaming, string encryption, control flow obfuscation to try to obfuscate the meaning of the original code. In some cases, it is even possible to totally hide the code from decompilers (however, decompilers are constantly evolving to overcome this). Take a look at [Crypto Obfuscator](http://www.ssware.com/cryptoobfuscator/obfuscator-net.htm). DISCLAIMER: I work for LogicNP, the developer of Crypto Obfuscator.
You can use FxProtect obfuscator. It successfully supports WPF and Silverlight obfuscation. You can try it... **[.NET Obfuscator](http://www.maycoms.net)**
48,727,346
Due to some odd reason, I cannot go with JPA vendor like Hibernate, etc and **I must use MyBatis.** Is there any implementation where we can enrich similar facility of CRUD operation in Mybatis? (Like GenericDAO save, persist, merge, etc) I have managed to come up with single interface implementation of CRUD type of operations (like Generic DAO) but still each table has to write it's own query in XML file (as table name, column names are different). Will that make sense to come up with generic implementation? Where I can give any table object for any CRUD operation through only 4 XML queries. (insert, update, read, delete) passing arguments of table name, column names, column values..etc. Does it look like re-inventing the wheel in MyBatis or does MyBatis has some similar support?
2018/02/11
[ "https://Stackoverflow.com/questions/48727346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1640241/" ]
The idea is still the same. Just that you will be looking for a specific attribute in the class object. For your card class, you could do something like this: ``` hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ] ``` Then you could do ``` sorted_cards = sorted(hand, key=lambda x: x.rank) ``` The output looks something like this: ``` >>> [card.number for card in sorted_cards] [2, 10, 12, 13, 14] ```
This is the object-oriented approach. At a minimum, you should specify `__eq__` and `__lt__` operations for this to work. Then just use `sorted(hand)`. ``` class Card(object): def __init__(self, rank, suit): self.rank = rank self.suit = suit def __eq__(self, other): return self.rank == other.rank and self.suit == other.suit def __lt__(self, other): return self.rank < other.rank hand = [Card(10, 'H'), Card(2, 'h'), Card(12, 'h'), Card(13, 'h'), Card(14, 'h')] hand_order = [c.rank for c in hand] # [10, 2, 12, 13, 14] hand_sorted = sorted(hand) hand_sorted_order = [c.rank for c in hand_sorted] # [2, 10, 12, 13, 14] ``` It's good practice to make object sorting logic, if applicable, a property of the class rather than incorporated in each instance the ordering is required. This way you can just call `sorted(list_of_objects)` each time.
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
I think you're looking for this: ``` from django.db.models.loading import get_model model = get_model('app_name', 'model_name') ``` There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.) **Update for Django 1.7+:** According to Django's [deprecation timeline](https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-9), `django.db.models.loading` has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in [Alasdair's answer](https://stackoverflow.com/a/28380435/996114), In Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model: ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
For Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model. ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
I think you're looking for this: ``` from django.db.models.loading import get_model model = get_model('app_name', 'model_name') ``` There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.) **Update for Django 1.7+:** According to Django's [deprecation timeline](https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-9), `django.db.models.loading` has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in [Alasdair's answer](https://stackoverflow.com/a/28380435/996114), In Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model: ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
``` from django.authx.models import User model = User model.objects.all() ```
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
Classes are "first class" objects in Python, meaning they can be passed around and manipulated just like all other objects. Models are classes -- you can tell from the fact that you create new models using class statements: ``` class Person(models.Model): last_name = models.CharField(max_length=64) class AnthropomorphicBear(models.Model): last_name = models.CharField(max_length=64) ``` Both the `Person` and `AnthropomorphicBear` identifiers are bound to Django classes, so you can pass them around. This can useful if you want to create helper functions that work at the model level (and share a common interface): ``` def print_obj_by_last_name(model, last_name): model_name = model.__name__ matches = model.objects.filter(last_name=last_name).all() print('{0}: {1!r}'.format(model_name, matches)) ``` So `print_obj_by_last_name` will work with either the `Person` or `AnthropomorphicBear` models. Just pass the model in like so: ``` print_obj_by_last_name(model=Person, last_name='Dole') print_obj_by_last_name(model=AnthropomorphicBear, last_name='Fozzy') ```
If you have the model name passed as a string I guess one way could be ``` modelname = "User" model = globals()[modelname] ``` But mucking about with globals() might be a bit dangerous in some contexts. So handle with care :)
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
I think you're looking for this: ``` from django.db.models.loading import get_model model = get_model('app_name', 'model_name') ``` There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.) **Update for Django 1.7+:** According to Django's [deprecation timeline](https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-9), `django.db.models.loading` has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in [Alasdair's answer](https://stackoverflow.com/a/28380435/996114), In Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model: ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
> > model = django.authx.models.User > > > ? Django returns an error, "global > name django is not defined." > > > Django does not return the error. Python does. First, you MUST import the model. You must import it with ``` from django.authx.models import User ``` Second, if you get an error that `django` is not defined, then Django is not installed correctly. You must have Django on your `PYTHONPATH` or installed in your Python lib/site-packages. To install Django correctly, see <http://docs.djangoproject.com/en/dev/intro/install/#intro-install>
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
``` from django.authx.models import User model = User model.objects.all() ```
If you have the model name passed as a string I guess one way could be ``` modelname = "User" model = globals()[modelname] ``` But mucking about with globals() might be a bit dangerous in some contexts. So handle with care :)
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
For Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model. ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
Classes are "first class" objects in Python, meaning they can be passed around and manipulated just like all other objects. Models are classes -- you can tell from the fact that you create new models using class statements: ``` class Person(models.Model): last_name = models.CharField(max_length=64) class AnthropomorphicBear(models.Model): last_name = models.CharField(max_length=64) ``` Both the `Person` and `AnthropomorphicBear` identifiers are bound to Django classes, so you can pass them around. This can useful if you want to create helper functions that work at the model level (and share a common interface): ``` def print_obj_by_last_name(model, last_name): model_name = model.__name__ matches = model.objects.filter(last_name=last_name).all() print('{0}: {1!r}'.format(model_name, matches)) ``` So `print_obj_by_last_name` will work with either the `Person` or `AnthropomorphicBear` models. Just pass the model in like so: ``` print_obj_by_last_name(model=Person, last_name='Dole') print_obj_by_last_name(model=AnthropomorphicBear, last_name='Fozzy') ```
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
I think you're looking for this: ``` from django.db.models.loading import get_model model = get_model('app_name', 'model_name') ``` There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.) **Update for Django 1.7+:** According to Django's [deprecation timeline](https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-9), `django.db.models.loading` has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in [Alasdair's answer](https://stackoverflow.com/a/28380435/996114), In Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model: ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
Classes are "first class" objects in Python, meaning they can be passed around and manipulated just like all other objects. Models are classes -- you can tell from the fact that you create new models using class statements: ``` class Person(models.Model): last_name = models.CharField(max_length=64) class AnthropomorphicBear(models.Model): last_name = models.CharField(max_length=64) ``` Both the `Person` and `AnthropomorphicBear` identifiers are bound to Django classes, so you can pass them around. This can useful if you want to create helper functions that work at the model level (and share a common interface): ``` def print_obj_by_last_name(model, last_name): model_name = model.__name__ matches = model.objects.filter(last_name=last_name).all() print('{0}: {1!r}'.format(model_name, matches)) ``` So `print_obj_by_last_name` will work with either the `Person` or `AnthropomorphicBear` models. Just pass the model in like so: ``` print_obj_by_last_name(model=Person, last_name='Dole') print_obj_by_last_name(model=AnthropomorphicBear, last_name='Fozzy') ```
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
For Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model. ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
``` from django.authx.models import User model = User model.objects.all() ```
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
Classes are "first class" objects in Python, meaning they can be passed around and manipulated just like all other objects. Models are classes -- you can tell from the fact that you create new models using class statements: ``` class Person(models.Model): last_name = models.CharField(max_length=64) class AnthropomorphicBear(models.Model): last_name = models.CharField(max_length=64) ``` Both the `Person` and `AnthropomorphicBear` identifiers are bound to Django classes, so you can pass them around. This can useful if you want to create helper functions that work at the model level (and share a common interface): ``` def print_obj_by_last_name(model, last_name): model_name = model.__name__ matches = model.objects.filter(last_name=last_name).all() print('{0}: {1!r}'.format(model_name, matches)) ``` So `print_obj_by_last_name` will work with either the `Person` or `AnthropomorphicBear` models. Just pass the model in like so: ``` print_obj_by_last_name(model=Person, last_name='Dole') print_obj_by_last_name(model=AnthropomorphicBear, last_name='Fozzy') ```
> > model = django.authx.models.User > > > ? Django returns an error, "global > name django is not defined." > > > Django does not return the error. Python does. First, you MUST import the model. You must import it with ``` from django.authx.models import User ``` Second, if you get an error that `django` is not defined, then Django is not installed correctly. You must have Django on your `PYTHONPATH` or installed in your Python lib/site-packages. To install Django correctly, see <http://docs.djangoproject.com/en/dev/intro/install/#intro-install>
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
For Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model. ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
If you have the model name passed as a string I guess one way could be ``` modelname = "User" model = globals()[modelname] ``` But mucking about with globals() might be a bit dangerous in some contexts. So handle with care :)
4,297,503
In continuation to my question asked [here](https://stackoverflow.com/questions/4212105/how-to-get-and-display-the-list-of-youtube-videos-using-javascript), i have created a test app to check the json parsing using jquery. It doesnt seem to work. I can append data in the click function. However getting data from that url and parsing seems to fail. Can someone provide some useful hints? ``` <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>"); $.getJSON("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?callback=function&alt=jsonc&v=2", function(data) { var dataContainer = $("#data ul"); $.each(data.data.items, function(i, val) { $("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>"); if (typeof(val.player) !== 'undefined' && typeof(val.title) !== 'undefined') { dataContainer.append("<li><a href = "+val.player.default+" target = '_blank'>"+val.title+"</a></li>"); } }); }); }); }); </script> </head> <body> <h2>Header</h2> <p>Paragrapgh</p> <p>Paragraph.</p> <button>Click me</button> </body> </html> ``` TIA, Praveen S
2010/11/28
[ "https://Stackoverflow.com/questions/4297503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372026/" ]
The callback is provided so that you can bypass the same origin policy. Thus retrieved JSON data is enclosed within the function name and cannot be parsed directly. Details of doing this with jquery are given [here](http://api.jquery.com/jQuery.ajax/). Please refer the example given below ``` <script> $.ajax({ url:'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?alt=jsonc&v=2&callback=?', dataType: "jsonp", timeout: 5000, success: function(data){ alert(data.apiVersion); //add your JSON parsing code here } }); </script> ``` Please find the working example [here](http://tallymobile.com/test7.html).
the url does not return a json like you would like try without the `callback=function` with the callback it uses a method called jsonp: <http://ajaxian.com/archives/jsonp-json-with-padding>
43,066,698
I'm studying UWP by Windows 10 development for absolute beginners, and I meet some problems. Reflash my ObservableCollection<> data will cause the screen to flash. How do I fix it? The program details are in [UWP beginner](https://channel9.msdn.com/Series/Windows-10-development-for-absolute-beginners/UWP-044-Adeptly-Adaptive-Challenge) ``` //CS FILE CODE public sealed partial class FinancialPage : Page { ObservableCollection<NewsItem> NewsItems; public FinancialPage() { NewsItems = new ObservableCollection<NewsItem>(); this.InitializeComponent(); GetNewsItemManager.GetNewItemsByCategory(NewsItems, "Financial"); } } // XAML FILE CODE <GridView ItemsSource="{x:Bind NewsItems}" Background="LightGray"> <GridView.ItemTemplate> <DataTemplate x:DataType="data:NewsItem"> <local:NewsContentControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> </DataTemplate> </GridView.ItemTemplate> </GridView> //MODELS NEWSITEMS CLASS FILE public static void GetNewItemsByCategory(ObservableCollection<NewsItem> NewsItems, string Category) { var allnewsitems = getNewsItems(); var filteredNewsItems = allnewsitems.Where(p => p.Category == Category && IsExist(NewsItems, p.Id)).ToList(); filteredNewsItems.ForEach(p => NewsItems.Add(p)); } private static Boolean IsExist(ObservableCollection<NewsItem> NewsItems, int Id) { return NewsItems.ToList().TrueForAll(p => Id == p.Id); } private static List<NewsItem> getNewsItems() { var items = new List<NewsItem>(); items.Add(new NewsItem() { Id = 1, Category = "Financial", Headline = "Lorem Ipsum", Subhead = "doro sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Financial1.png" }); items.Add(new NewsItem() { Id = 2, Category = "Financial", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Financial2.png" }); items.Add(new NewsItem() { Id = 3, Category = "Financial", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Financial3.png" }); items.Add(new NewsItem() { Id = 4, Category = "Financial", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Financial4.png" }); items.Add(new NewsItem() { Id = 5, Category = "Financial", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Financial5.png" }); items.Add(new NewsItem() { Id = 6, Category = "Food", Headline = "Lorem ipsum", Subhead = "dolor sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Food1.png" }); items.Add(new NewsItem() { Id = 7, Category = "Food", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Food2.png" }); items.Add(new NewsItem() { Id = 8, Category = "Food", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Food3.png" }); items.Add(new NewsItem() { Id = 9, Category = "Food", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Food4.png" }); items.Add(new NewsItem() { Id = 10, Category = "Food", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Food5.png" }); return items; } ```
2017/03/28
[ "https://Stackoverflow.com/questions/43066698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7439395/" ]
Assuming ``` NewsItem.Clear(); filteredNewsItems.ForEach(p => NewsItem.Add(p)); ``` should be ``` NewsItems.Clear(); filteredNewsItems.ForEach(p => NewsItems.Add(p)); ``` I assume the "flash" you are seeing (can't be certain as you haven't provided a full repro) is due to what you're doing to show the updated list. Yes, removing everything and then adding a new (mostly similar) list back can create what some people describe as a "flash". A better approach would be to remove the items you don't want displayed any more and then add in any extra ones you do. Something like this: ``` foreach (var newsItem in NewsItems.Reverse()) { if (newsItem.Category != Category) { NewsItems.Remove(newsItem); } } foreach (var fni in filteredNewsItems) { if (!NewsItems.Contains(fni)) { NewsItems.Add(fni); } } ```
OK... I think I've found a solution for you. Instead of updating the bindings in your user control with the lambda expression, try it this way: ``` public NewsContentControl() { this.InitializeComponent(); this.DataContextChanged += OnDataCtxChanged; //+= (s, e) => Bindings.Update(); } private void OnDataCtxChanged(FrameworkElement sender, DataContextChangedEventArgs args) { System.Diagnostics.Debug.WriteLine("context 'changed'"); if(NewsItem != args.NewValue as NewsItem) { Bindings.Update(); } } ``` This triggers the update only if the value is actually different. Additionally, you can use "Binding" instead of x:Bind. None of this answers for me why the datacontext is changing... but this should get rid of your flicker.
128,817
I am new to Ubuntu, and I have just installed Ubuntu 12.04 on a computer. I am using an automatic proxy server. When I select a software package to install and input my password, the progress icon displays for a few seconds, and then it stops. I tried to install different programs, and I always had the same problem. I can browse the web with Firefox, so I know I have a network connection. I do not see any errors or anything. What should I do?
2012/04/30
[ "https://askubuntu.com/questions/128817", "https://askubuntu.com", "https://askubuntu.com/users/58882/" ]
Here is a work around. Once you find a game you want to install, you can search for it in the terminal with (for example \*\* Super Tux): ``` apt-cache search Super Tux ``` Then you can install one of the names it displays by for example: ``` sudo apt-get install supertux ``` If you want to install a game from *dotdeb.com* for instance, you can open the terminal and type: ``` sudo dpkg -i ``` Make sure to leave a `Space` **after** the `-i` and then drag-and-drop the deb file you downloaded onto the terminal and press `Enter`.
I had the same problem with software. It's probably a permission thing. On my menu the command to open uses software-center with pkexec, which command without parameters defaults to superuser. It seems to have issues. By altermint the menu command to gksu software-center I found it worked and installed programs with no problems.
128,817
I am new to Ubuntu, and I have just installed Ubuntu 12.04 on a computer. I am using an automatic proxy server. When I select a software package to install and input my password, the progress icon displays for a few seconds, and then it stops. I tried to install different programs, and I always had the same problem. I can browse the web with Firefox, so I know I have a network connection. I do not see any errors or anything. What should I do?
2012/04/30
[ "https://askubuntu.com/questions/128817", "https://askubuntu.com", "https://askubuntu.com/users/58882/" ]
Just use synaptic package manager, even though it's not as fancy as the software center. To install it type: `sudo apt-get install synaptic` in the terminal.
I had the same problem with software. It's probably a permission thing. On my menu the command to open uses software-center with pkexec, which command without parameters defaults to superuser. It seems to have issues. By altermint the menu command to gksu software-center I found it worked and installed programs with no problems.
233,097
The Premise =========== * An earth-like world (gravity, 1 moon, distance from star) * Oceans do not touch the ground (ignoring the how for this premise, but for consistency we'll say it's floating atop **1 km** of air) * Oceans still in contact with shorelines (allowed to touch ground starting a maximum of 1km from shore) ### What the question is *NOT* * How ocean life would be affected * What destruction would be caused to the atmosphere * Feasibility of the premise The Question ------------ Given that an ocean didn't touch the ground outside of a 1km continental shelf allowance, how would natural ocean phenomena such as waves change? #### Clarifications I haven't been able to get on since posting the question, so I'll give some clarifications here: * The illustration below shows what I was trying to say: the water can only sit on top of land within 1 km of a continent, everywhere else has ~ 1 km of air between the water and ground [![MS Paint example](https://i.stack.imgur.com/nz9QZ.png)](https://i.stack.imgur.com/nz9QZ.png) * For the purposes of this premise, we can assume that the air being contained by the water bodies is air that is either more dense or less buoyant than the water atop it. * We can assume there is very little, if any, air flow getting below the water bodies from above them. * **I care less about the way the waves react upon reaching the shelf, and more about how they change (if they change at all) out on the open waters** **Disclaimer** If you notice anything wrong with my post, I'm still learning, and am always open to suggestions for improvement!
2022/07/22
[ "https://worldbuilding.stackexchange.com/questions/233097", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/97249/" ]
It wouldn't change much ======================= Your scenario is roughly equivalent to "There's a huge, 1 km deep, pocket of air at the bottom of the ocean, and all the ground below the continental shelf is dry" Waves on the ocean are mostly governed by surface effects, so what is happening deep below the surface will be largely unaffected. That isn't to say that if this change happened abruptly that there wouldn't be some big changes in the ocean, but after things settled down, the waves and the ocean would settle down and a new normal would be established.
Same amount of fluid ==================== If the ocean is sitting atop a layer of air, then we still have the same volume of fluid. The "ceiling" of the air layer, where it meets the ocean, might fluctuate by a very small amount (centimeters at most) in some places. "What about the density?" The deep ocean has very little effect on waves, nor is it very affected by waves. So, assuming that your scenario is possible in your world, it wouldn't matter. The waves on the surface of the ocean would be essentially identical. The real problem is with the air itself. In order for the ocean to sit on top of it, you will need some sort of magic holding it up, otherwise the air pressure of your underwater "atmosphere" is going to be just as high as it would be under the same depth of water--no one could live there. You will also need to explain how the air doesn't just bubble up through the ocean. Surface tension alone won't cut it.
233,097
The Premise =========== * An earth-like world (gravity, 1 moon, distance from star) * Oceans do not touch the ground (ignoring the how for this premise, but for consistency we'll say it's floating atop **1 km** of air) * Oceans still in contact with shorelines (allowed to touch ground starting a maximum of 1km from shore) ### What the question is *NOT* * How ocean life would be affected * What destruction would be caused to the atmosphere * Feasibility of the premise The Question ------------ Given that an ocean didn't touch the ground outside of a 1km continental shelf allowance, how would natural ocean phenomena such as waves change? #### Clarifications I haven't been able to get on since posting the question, so I'll give some clarifications here: * The illustration below shows what I was trying to say: the water can only sit on top of land within 1 km of a continent, everywhere else has ~ 1 km of air between the water and ground [![MS Paint example](https://i.stack.imgur.com/nz9QZ.png)](https://i.stack.imgur.com/nz9QZ.png) * For the purposes of this premise, we can assume that the air being contained by the water bodies is air that is either more dense or less buoyant than the water atop it. * We can assume there is very little, if any, air flow getting below the water bodies from above them. * **I care less about the way the waves react upon reaching the shelf, and more about how they change (if they change at all) out on the open waters** **Disclaimer** If you notice anything wrong with my post, I'm still learning, and am always open to suggestions for improvement!
2022/07/22
[ "https://worldbuilding.stackexchange.com/questions/233097", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/97249/" ]
It wouldn't change much ======================= Your scenario is roughly equivalent to "There's a huge, 1 km deep, pocket of air at the bottom of the ocean, and all the ground below the continental shelf is dry" Waves on the ocean are mostly governed by surface effects, so what is happening deep below the surface will be largely unaffected. That isn't to say that if this change happened abruptly that there wouldn't be some big changes in the ocean, but after things settled down, the waves and the ocean would settle down and a new normal would be established.
There would be (virtually) no tsunamis -------------------------------------- Tsunamis are caused by the land displacing large amounts of water when an earthquake occurs. With a 1km air buffer between land and sea, there would not be a direct land-water interface to move the water, and the air would likely absorb most (if not all) of that energy.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
Use an image relay script! To serve a imagefile that is outside the public\_html folder you would have to do it by a php script. E.g make a image-relay.php that reads the image that is outside the public html... ``` <?php header('Content-Type: image/jpeg'); $_file = 'myimage.jpg'; // or $_GET['img'] echo file_get_contents('/myimages/'.$_file); ?> ``` Now, $\_file could be a $\_GET parameter, but its absolutley important to validate the input parameter... now you can make an `<img src="image-relay.php?img=flower.jpg">` to access a flower.jpg image that is located in /myimage/flower.jpg ...
Well, a web browser will only be able to access files and folders inside public\_html.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
You want something that's basically impossible. The way a browser loads a page (in a very basic sense) is this: Step 1: Download the page. Step 2: Parse the page. Step 3: Download anything referenced in the content of the page (images, stylesheets, javascripts, etc) Each "Download" event is atomic. It seems like you want to only serve images to people who have just downloaded a page that references those images. As PHP Jedi illustrated, you can pass the files through PHP. You could expand on his code, and check the HTTP\_REFERER on the request to ensure that people aren't grabbing "just" the image. Now, serving every image through a PHP passthru script is not efficient, but it could work. The most common reason people want to do this is to avoid "hotlinking" -- when people create image tags on other sites that reference the image on your server. When they do that, you expend resources handling requests that get presented on someone else's page. If that's what you're really trying to avoid, you can use mod\_rewrite to check the referer. A decent-looking discussion of hotlinking/anti-hotlinking can be found [here](http://www.dagondesign.com/articles/hotlink-protection-with-htaccess/)
Well, a web browser will only be able to access files and folders inside public\_html.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
Use an image relay script! To serve a imagefile that is outside the public\_html folder you would have to do it by a php script. E.g make a image-relay.php that reads the image that is outside the public html... ``` <?php header('Content-Type: image/jpeg'); $_file = 'myimage.jpg'; // or $_GET['img'] echo file_get_contents('/myimages/'.$_file); ?> ``` Now, $\_file could be a $\_GET parameter, but its absolutley important to validate the input parameter... now you can make an `<img src="image-relay.php?img=flower.jpg">` to access a flower.jpg image that is located in /myimage/flower.jpg ...
If the `public_html` directory is the root of the server for your users, Apache cannot serve anything that is not inside/below that dorectory. If you want a file to be served by Apache directly, you'll have to put it in/below `public_html`.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
You want something that's basically impossible. The way a browser loads a page (in a very basic sense) is this: Step 1: Download the page. Step 2: Parse the page. Step 3: Download anything referenced in the content of the page (images, stylesheets, javascripts, etc) Each "Download" event is atomic. It seems like you want to only serve images to people who have just downloaded a page that references those images. As PHP Jedi illustrated, you can pass the files through PHP. You could expand on his code, and check the HTTP\_REFERER on the request to ensure that people aren't grabbing "just" the image. Now, serving every image through a PHP passthru script is not efficient, but it could work. The most common reason people want to do this is to avoid "hotlinking" -- when people create image tags on other sites that reference the image on your server. When they do that, you expend resources handling requests that get presented on someone else's page. If that's what you're really trying to avoid, you can use mod\_rewrite to check the referer. A decent-looking discussion of hotlinking/anti-hotlinking can be found [here](http://www.dagondesign.com/articles/hotlink-protection-with-htaccess/)
If the `public_html` directory is the root of the server for your users, Apache cannot serve anything that is not inside/below that dorectory. If you want a file to be served by Apache directly, you'll have to put it in/below `public_html`.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
Use an image relay script! To serve a imagefile that is outside the public\_html folder you would have to do it by a php script. E.g make a image-relay.php that reads the image that is outside the public html... ``` <?php header('Content-Type: image/jpeg'); $_file = 'myimage.jpg'; // or $_GET['img'] echo file_get_contents('/myimages/'.$_file); ?> ``` Now, $\_file could be a $\_GET parameter, but its absolutley important to validate the input parameter... now you can make an `<img src="image-relay.php?img=flower.jpg">` to access a flower.jpg image that is located in /myimage/flower.jpg ...
I think your misunderstanding is in the fact that if you include an image in an `<img>` tag, your browser will send the exact same request to the webserver to fetch it, that will be sent to the webserver if you try to open the `src` url of the image in your browser directly. Therefore, either both things work, or neither. There are hacks around, involving a (php or other) script to make sure that an IP that has requested the image has also requested the html page within the last few seconds (which will not work if the user is behind a proxy that rotates outgoing IPs) or by checking the referer (which does not work with HTTPs and also not if the user has referer disabled). If you want to make sure that only some users can see the image (both via `<img>` tag and directly), you can put the image outside public\_html and have a (php or other) script that verifies the user's credentials before serving the image.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
Use an image relay script! To serve a imagefile that is outside the public\_html folder you would have to do it by a php script. E.g make a image-relay.php that reads the image that is outside the public html... ``` <?php header('Content-Type: image/jpeg'); $_file = 'myimage.jpg'; // or $_GET['img'] echo file_get_contents('/myimages/'.$_file); ?> ``` Now, $\_file could be a $\_GET parameter, but its absolutley important to validate the input parameter... now you can make an `<img src="image-relay.php?img=flower.jpg">` to access a flower.jpg image that is located in /myimage/flower.jpg ...
If you are using Apache or lighttpd you can use the X-Sendfile header to send files that are not in the web root(provided you haven't changed the configuration of mod\_xsendfile). To learn more about X-sendfile see this [site](http://codeutopia.net/blog/2009/03/06/sending-files-better-apache-mod_xsendfile-and-php/). This solution is giving you the best possible performance as PHP doesn't send the file but the server does and therefore PHP can be exited while the files are being served. Hope that helps.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
You want something that's basically impossible. The way a browser loads a page (in a very basic sense) is this: Step 1: Download the page. Step 2: Parse the page. Step 3: Download anything referenced in the content of the page (images, stylesheets, javascripts, etc) Each "Download" event is atomic. It seems like you want to only serve images to people who have just downloaded a page that references those images. As PHP Jedi illustrated, you can pass the files through PHP. You could expand on his code, and check the HTTP\_REFERER on the request to ensure that people aren't grabbing "just" the image. Now, serving every image through a PHP passthru script is not efficient, but it could work. The most common reason people want to do this is to avoid "hotlinking" -- when people create image tags on other sites that reference the image on your server. When they do that, you expend resources handling requests that get presented on someone else's page. If that's what you're really trying to avoid, you can use mod\_rewrite to check the referer. A decent-looking discussion of hotlinking/anti-hotlinking can be found [here](http://www.dagondesign.com/articles/hotlink-protection-with-htaccess/)
Use an image relay script! To serve a imagefile that is outside the public\_html folder you would have to do it by a php script. E.g make a image-relay.php that reads the image that is outside the public html... ``` <?php header('Content-Type: image/jpeg'); $_file = 'myimage.jpg'; // or $_GET['img'] echo file_get_contents('/myimages/'.$_file); ?> ``` Now, $\_file could be a $\_GET parameter, but its absolutley important to validate the input parameter... now you can make an `<img src="image-relay.php?img=flower.jpg">` to access a flower.jpg image that is located in /myimage/flower.jpg ...
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
You want something that's basically impossible. The way a browser loads a page (in a very basic sense) is this: Step 1: Download the page. Step 2: Parse the page. Step 3: Download anything referenced in the content of the page (images, stylesheets, javascripts, etc) Each "Download" event is atomic. It seems like you want to only serve images to people who have just downloaded a page that references those images. As PHP Jedi illustrated, you can pass the files through PHP. You could expand on his code, and check the HTTP\_REFERER on the request to ensure that people aren't grabbing "just" the image. Now, serving every image through a PHP passthru script is not efficient, but it could work. The most common reason people want to do this is to avoid "hotlinking" -- when people create image tags on other sites that reference the image on your server. When they do that, you expend resources handling requests that get presented on someone else's page. If that's what you're really trying to avoid, you can use mod\_rewrite to check the referer. A decent-looking discussion of hotlinking/anti-hotlinking can be found [here](http://www.dagondesign.com/articles/hotlink-protection-with-htaccess/)
I think your misunderstanding is in the fact that if you include an image in an `<img>` tag, your browser will send the exact same request to the webserver to fetch it, that will be sent to the webserver if you try to open the `src` url of the image in your browser directly. Therefore, either both things work, or neither. There are hacks around, involving a (php or other) script to make sure that an IP that has requested the image has also requested the html page within the last few seconds (which will not work if the user is behind a proxy that rotates outgoing IPs) or by checking the referer (which does not work with HTTPs and also not if the user has referer disabled). If you want to make sure that only some users can see the image (both via `<img>` tag and directly), you can put the image outside public\_html and have a (php or other) script that verifies the user's credentials before serving the image.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
You want something that's basically impossible. The way a browser loads a page (in a very basic sense) is this: Step 1: Download the page. Step 2: Parse the page. Step 3: Download anything referenced in the content of the page (images, stylesheets, javascripts, etc) Each "Download" event is atomic. It seems like you want to only serve images to people who have just downloaded a page that references those images. As PHP Jedi illustrated, you can pass the files through PHP. You could expand on his code, and check the HTTP\_REFERER on the request to ensure that people aren't grabbing "just" the image. Now, serving every image through a PHP passthru script is not efficient, but it could work. The most common reason people want to do this is to avoid "hotlinking" -- when people create image tags on other sites that reference the image on your server. When they do that, you expend resources handling requests that get presented on someone else's page. If that's what you're really trying to avoid, you can use mod\_rewrite to check the referer. A decent-looking discussion of hotlinking/anti-hotlinking can be found [here](http://www.dagondesign.com/articles/hotlink-protection-with-htaccess/)
If you are using Apache or lighttpd you can use the X-Sendfile header to send files that are not in the web root(provided you haven't changed the configuration of mod\_xsendfile). To learn more about X-sendfile see this [site](http://codeutopia.net/blog/2009/03/06/sending-files-better-apache-mod_xsendfile-and-php/). This solution is giving you the best possible performance as PHP doesn't send the file but the server does and therefore PHP can be exited while the files are being served. Hope that helps.
15,105,461
In my application, I want to open device default calendar using code/programatically. I am using this code : ``` private void viewAllCalender() { // TODO Auto-generated method stub Intent i = new Intent(); if(Build.VERSION.SDK_INT >= 8 && Build.VERSION.SDK_INT <= 14){ i.setClassName("com.android.calendar","com.android.calendar.LaunchActivity"); }else if(Build.VERSION.SDK_INT >= 15){ i.setClassName("com.google.android.calendar", "com.android.calendar.LaunchActivity"); }else{ i.setClassName("com.android.calendar","com.android.calendar.LaunchActivity"); } startActivity(i); } ``` **IT IS WORKING FOR ALL THE DEVICES BUT IT IS NOT WORKING IN SAMSUNG S3 - (BUILD SDK VERSION - 17)** Please help me to figure out what the problem is?? Thanks
2013/02/27
[ "https://Stackoverflow.com/questions/15105461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114329/" ]
You gotta realise that you can't expect an Android device to have a certain application. Not even the play app can be expected to be installed. The correct way of doing this is simply not using .setClassName and then let the user decide what to do. There is a dozen different calendar apps and the phone manufactures each have their own... **Edit** If you want to add an event to calendar you could use my CalendarOrganizer which handles a lot of these issues: ``` public class CalendarOrganizer { private final static int ICE_CREAM_BUILD_ID = 14; /** * Creates a calendar intent going from startTime to endTime * @param startTime * @param endTime * @param context * @return true if the intent can be handled and was started, * false if the intent can't be handled */ public static boolean createEvent(long startTime, long endTime, String title, String description, String location, boolean isAllDay, Context context) { Intent intent = new Intent(Intent.ACTION_EDIT); int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < ICE_CREAM_BUILD_ID) { // all SDK below ice cream sandwich intent.setType("vnd.android.cursor.item/event"); intent.putExtra("beginTime", startTime); intent.putExtra("endTime", endTime); intent.putExtra("title", title); intent.putExtra("description", description); intent.putExtra("eventLocation", location); intent.putExtra("allDay", isAllDay); // intent.putExtra("rrule", "FREQ=YEARLY"); } else { // ice cream sandwich and above intent.setType("vnd.android.cursor.item/event"); intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime); intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime); intent.putExtra(Events.TITLE, title); intent.putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE); intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY , isAllDay); intent.putExtra(Events.DESCRIPTION, description); intent.putExtra(Events.EVENT_LOCATION, location); // intent.putExtra(Events.RRULE, "FREQ=DAILY;COUNT=10") } try { context.startActivity(intent); return true; } catch(Exception e) { return false; } } } ```
To open the calendar application refer to the intent-view guide <http://developer.android.com/guide/topics/providers/calendar-provider.html#intent-view>
6,090,160
Let's say I started Linux process, in the background. It is not a daemon, just a utility. If it gets SIGHUP, it would be killed. I did not take the "nohup" precaution. It is taking already much longer time than I thought. After 4 hours of running, ssh session might get disconnected. But I don't want to lose the process. I want to prevent it being killed by SIGHUP. Is it possible to make the equivalent of ``` signal(SIGHUP, SIG_IGN); ``` to this process without restarting it ? Thanks
2011/05/22
[ "https://Stackoverflow.com/questions/6090160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/564524/" ]
Use `disown(1)` > > disown: disown [-h] [-ar] [jobspec > ...] > Remove jobs from current shell. > > > > ``` > Removes each JOBSPEC argument from the table of active jobs. Without > any JOBSPECs, the shell uses its notion of the current job. > > Options: > -a remove all jobs if JOBSPEC is not supplied > -h mark each JOBSPEC so that SIGHUP is not sent to the job if > the shell receives a SIGHUP > -r remove only running jobs > > ``` > > [Detaching a process from terminal, entirely](https://superuser.com/questions/178587/detaching-a-process-from-terminal-entirely/178592#178592) > > "disown" is a bash builtin that > removes a shell job from the shell's > job list. What this basically means is > that you can't use "fg", "bg" on it > anymore, but more importantly, when > you close your shell it won't hang or > send a SIGHUP to that child anymore. > Unlike "nohup", "disown" is used after > the process has been launched and > backgrounded. > > >
Diswon is the good solution for this time. For the future, a nice workaround is to use "screen" tool : if ever your ssh session disconnects, you can reconnect and refetch your still running screen. However, I don't know a way to pull a current process into a screen session, so it won't solve your current case.
48,155,799
I am trying to calculate the average number participants scored correct on a memory task. I have a column called `RecallType` which tells me if participants were assessed through forward memory recall (called `forwards`) or through backwards memory recall (called `backwards`). I also have a column called `ProbeState` which identifies the type of memory task, of which there are two. In this column I have `positions` and `digits`. These are all my variables of interest. The memory task itself is split by two columns. `Recall.CRESP` is a column specifying the correct answers on a memory test selected through grid coordinates. `Recall.RESP` shows participants response. These columns look something like this: ``` |Recall.CRESP | Recall.RESP | |---------------------------------|---------------------------------| |grid35grid51grid12grid43grid54 | grid35grid51grid12grid43grid54 | |grid11gird42gird22grid51grid32 | grid11gird15gird55grid42grid32 | ``` So for example in row 1 of this table, the participant got 5/5 correct as the grid coordinates of `Recall.CRESP` matches with `Recall.RESP`. However in row 2, the participant only got 2/5 correct as only the first and the last grid coordinate are identical. The order of the coordinates must match to be correct. Ideally I would love to learn from any response. If you do reply please kindly put some comments. Thanks.
2018/01/08
[ "https://Stackoverflow.com/questions/48155799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8137074/" ]
THe problem is that you have a non virtual `foo()` so that `A::bar()` will call the only `foo()` it knows, being `A::foo()`, even if it's B that invokes it. Try: ``` class A { public: A() { foo(); } virtual ~A() { foo(); } // <<---------- recommendation virtual void foo() { cout << 3; } // <<<--------- solves it void bar() { foo(); } }; class B : public A { void foo() override { cout << 2; } // <<---------- recommendation }; ``` **Additional infos:** Making `foo()` [virtual](https://www.geeksforgeeks.org/virtual-function-cpp/) in the base class allows each class to override this function, and be sure that the `foo()` that is invoked is will be the `foo()` corresponding to the object's real class. It's a [good practice](https://stackoverflow.com/q/497630/3723423) then to use the keyword `override` in the derived classes: it's not mandatory, but in case you make a typo in the functions signature, you'll immediately notice with a compile-time error message. Another good practice is to make your base class destructor virtual if you have at least one virtual function in the class. A final remark: in B, `foo()`'s private. This is legal, but it's weird because the inheritance says that B is a kind of A, but you can't use B objects exactly as an A object.
You must include virtual in order to override the functionality stored in A. Add to A ``` virtual void foo() { cout << 3; } ``` and to B ``` void foo() override { cout << 2; } ``` Should do the trick. Virtual functions are member functions whose behavior can be overridden in derived classes. As opposed to non-virtual functions, the overridden behavior is preserved even if there is no compile-time information about the actual type of the class. If a derived class is handled using pointer or reference to the base class, a call to an overridden virtual function would invoke the behavior defined in the derived class.
48,155,799
I am trying to calculate the average number participants scored correct on a memory task. I have a column called `RecallType` which tells me if participants were assessed through forward memory recall (called `forwards`) or through backwards memory recall (called `backwards`). I also have a column called `ProbeState` which identifies the type of memory task, of which there are two. In this column I have `positions` and `digits`. These are all my variables of interest. The memory task itself is split by two columns. `Recall.CRESP` is a column specifying the correct answers on a memory test selected through grid coordinates. `Recall.RESP` shows participants response. These columns look something like this: ``` |Recall.CRESP | Recall.RESP | |---------------------------------|---------------------------------| |grid35grid51grid12grid43grid54 | grid35grid51grid12grid43grid54 | |grid11gird42gird22grid51grid32 | grid11gird15gird55grid42grid32 | ``` So for example in row 1 of this table, the participant got 5/5 correct as the grid coordinates of `Recall.CRESP` matches with `Recall.RESP`. However in row 2, the participant only got 2/5 correct as only the first and the last grid coordinate are identical. The order of the coordinates must match to be correct. Ideally I would love to learn from any response. If you do reply please kindly put some comments. Thanks.
2018/01/08
[ "https://Stackoverflow.com/questions/48155799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8137074/" ]
THe problem is that you have a non virtual `foo()` so that `A::bar()` will call the only `foo()` it knows, being `A::foo()`, even if it's B that invokes it. Try: ``` class A { public: A() { foo(); } virtual ~A() { foo(); } // <<---------- recommendation virtual void foo() { cout << 3; } // <<<--------- solves it void bar() { foo(); } }; class B : public A { void foo() override { cout << 2; } // <<---------- recommendation }; ``` **Additional infos:** Making `foo()` [virtual](https://www.geeksforgeeks.org/virtual-function-cpp/) in the base class allows each class to override this function, and be sure that the `foo()` that is invoked is will be the `foo()` corresponding to the object's real class. It's a [good practice](https://stackoverflow.com/q/497630/3723423) then to use the keyword `override` in the derived classes: it's not mandatory, but in case you make a typo in the functions signature, you'll immediately notice with a compile-time error message. Another good practice is to make your base class destructor virtual if you have at least one virtual function in the class. A final remark: in B, `foo()`'s private. This is legal, but it's weird because the inheritance says that B is a kind of A, but you can't use B objects exactly as an A object.
Member `A::foo` is non-virtual and will therefore be statically bound wherever used. So when compiling `A::bar`, the call to `foo()` will be (statically) bound to the implementation `A::foo()`. This statical binding in `A::foo` will not be changed by the fact that you create an instance of derived class `B` later on. If you call `b.foo()` in you main, however, `B::foo` will be bound. In order to have `B::foo` to be called through `A::bar`, you'll have to declare `A::foo` as `virtual: ``` class A { public: A() { foo(); } virtual ~A() { foo(); } virtual void foo() { cout << 3; } void bar() { foo(); } }; ``` Note that you'd also declare the destructor as virtual; non-virtual destructors do very rarely make sense.
48,155,799
I am trying to calculate the average number participants scored correct on a memory task. I have a column called `RecallType` which tells me if participants were assessed through forward memory recall (called `forwards`) or through backwards memory recall (called `backwards`). I also have a column called `ProbeState` which identifies the type of memory task, of which there are two. In this column I have `positions` and `digits`. These are all my variables of interest. The memory task itself is split by two columns. `Recall.CRESP` is a column specifying the correct answers on a memory test selected through grid coordinates. `Recall.RESP` shows participants response. These columns look something like this: ``` |Recall.CRESP | Recall.RESP | |---------------------------------|---------------------------------| |grid35grid51grid12grid43grid54 | grid35grid51grid12grid43grid54 | |grid11gird42gird22grid51grid32 | grid11gird15gird55grid42grid32 | ``` So for example in row 1 of this table, the participant got 5/5 correct as the grid coordinates of `Recall.CRESP` matches with `Recall.RESP`. However in row 2, the participant only got 2/5 correct as only the first and the last grid coordinate are identical. The order of the coordinates must match to be correct. Ideally I would love to learn from any response. If you do reply please kindly put some comments. Thanks.
2018/01/08
[ "https://Stackoverflow.com/questions/48155799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8137074/" ]
Member `A::foo` is non-virtual and will therefore be statically bound wherever used. So when compiling `A::bar`, the call to `foo()` will be (statically) bound to the implementation `A::foo()`. This statical binding in `A::foo` will not be changed by the fact that you create an instance of derived class `B` later on. If you call `b.foo()` in you main, however, `B::foo` will be bound. In order to have `B::foo` to be called through `A::bar`, you'll have to declare `A::foo` as `virtual: ``` class A { public: A() { foo(); } virtual ~A() { foo(); } virtual void foo() { cout << 3; } void bar() { foo(); } }; ``` Note that you'd also declare the destructor as virtual; non-virtual destructors do very rarely make sense.
You must include virtual in order to override the functionality stored in A. Add to A ``` virtual void foo() { cout << 3; } ``` and to B ``` void foo() override { cout << 2; } ``` Should do the trick. Virtual functions are member functions whose behavior can be overridden in derived classes. As opposed to non-virtual functions, the overridden behavior is preserved even if there is no compile-time information about the actual type of the class. If a derived class is handled using pointer or reference to the base class, a call to an overridden virtual function would invoke the behavior defined in the derived class.
32,739,725
I have a list of users and when I click on a list item I would like a sub section to slide down from beneath it. I'm fine with the animation and this isn't the area I need help on. My problem is that when I click on any list item, all drop-down sections appear underneath all list items. So my approach now is to use the `id` of each user to create a unique `ng-show`. Then when I click on a list item a function is called: ``` <ul id="users" ng-repeat="user in users"> <li ng-click="showUserDetail(user.id)"> {{user.name}} <div class="slide" ng-show="dropDownSection_{{user.id}}"> //Stuff will go here </div> </li> </ul> ``` The `showUserDetail` function is: ``` $scope.showUserDetail = function(id) { //not sure I can do this? var section = "dropDownSection" + "_" + id; $scope.section = true; //this would normally show the animation } ``` but this doesn't work - the dropdown doesn't appear. Is there a nice "Angular" way of achieving something like this?
2015/09/23
[ "https://Stackoverflow.com/questions/32739725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003632/" ]
what you can do is.. set the id to show on ng-click and check that id in ng-show `ng-click="idToDisplay = user.id"` and `ng-show="idToDisplay == user.id"`
You can keep track of the user for which details are currently shown via a variable on the scope. You set this variable when you click on a user. ``` $scope.userDetailId = 0; $scope.showUserDetail = function (id) { $scope.userDetailId = id; } ``` Then, inside your `ng-repeat` section, you can check if the current user's id matches the tracked ID: ``` <ul id="users" ng-repeat="user in users"> <li ng-click="showUserDetail(user.id)"> {{user.name}} <div class="slide" ng-show="userDetailId == user.id"> //Stuff will go here </div> </li> </ul> ``` Check this [Plunker](http://jsfiddle.net/jhjwzgth/1/) for a demo.
16,864,635
How can I animate an MKMapView to certain lat and lng? I have a map that is displayed when the user opens the app. When a user clicks a certain button I want the map to move to a specificc lat/lng. Is there not an animateTo(CLLocation) method?
2013/05/31
[ "https://Stackoverflow.com/questions/16864635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307428/" ]
This will animate to roughly the center of continental US: ``` MKCoordinateRegion region = mapView.region; region.center.latitude = 39.833333; region.center.longitude = -98.58333; region.span.latitudeDelta = 60; region.span.longitudeDelta = 60; [mapView setRegion:region animated:YES]; ``` set your "center" to your latitude/longitude coordinates, choose an appropriate span, and let setRegion to its thing.
This will scroll the map view to your new location: ``` CLLocationCoordinate2D yourCoordinate = CLLocationCoordinate2DMake(lat, lng); [self.mapView setCenterCoordinate:yourCoordinate animated:YES]; ```
15,259,830
I am attempting to write a method that will output the content (i.e. HTML) for any renderings that happen to exist within a specific placeholder. The goal is to pass in a `Sitecore.Data.Items.Item` and the placeholder key that i'm interested in, and the method should return the rendered content. The issue with this seems to be that there is no page context established, and therefore calling `RenderControl()` is throwing a null reference error in the `GetCacheKey()` method of the Sublayout. Is anyone aware of a way to render a Sublayout or XSLT rendering programmatically? Here's what I've got so far: ``` private string GetPlaceholderContent(Item item, string placeHolder) { StringWriter sw = new StringWriter(); using (HtmlTextWriter writer = new HtmlTextWriter(sw)) { foreach (RenderingReference renderingReference in item.Visualization.GetRenderings(Sitecore.Context.Device, false)) { if (renderingReference.Placeholder == placeHolder) { // This ensures we're only dealing with Sublayouts if (renderingReference.RenderingItem.InnerItem.IsOfType(Sitecore.TemplateIDs.Sublayout)) { var control = renderingReference.GetControl(); control.RenderControl(writer); // Throws null reference error in GetCacheKey() } } } } return sw.ToString(); } ```
2013/03/06
[ "https://Stackoverflow.com/questions/15259830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185749/" ]
It is almost 8 years since the question was originally asked, and it turn to be [Uniform](https://uniform.dev/uniform-for-sitecore) - rendering any item/placeholder fragment! Yes, it cuts the item you supply into placeholders/renderings: [![enter image description here](https://i.stack.imgur.com/E5lCO.jpg)](https://i.stack.imgur.com/E5lCO.jpg) The next step is to produce markup (for every possible data source out there): [![enter image description here](https://i.stack.imgur.com/6SJ4v.png)](https://i.stack.imgur.com/6SJ4v.png) That content is published into CDN and browser picks which version to load = personalization works! In other words, the question you've asked turned into a cutting-edge product that **can do so much more** on top of that! You could reverse-engineer the Uniform assemblies to see how they actually do that ;)
In my opinion, the best way to programmatically render a Sublayout is to use a repeater, and put a `<sc:Sublayout>` tag in the `<ItemTemplate>`. From there you only have to do one or both of the following: 1. Set the `DataSource` property of the `<sc:Sublayout>` to be the string representation of the desired item's GUID (i.e. the data source for the sublayout, if any) 2. Set the `Path` property of the `<sc:Sublayout>` to be the path to the Sublayout that you wish to render. The server/sitecore will handle the rest.
43,181,597
I'm working on a magento project with a plugin changes the `onclick` attribute on the `(document).ready()`. I tried to access this attribute using jquery to update it after a user action but it returns `undefined`. And I've noticed that the onclick attribute is NOT visible in the inspector but visible in the page source accessed by `view page source`or`Ctrl + u`. in inspector the targeted button looks like ``` <button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty"> <span>Add to cart<span> </button> ``` in the page source view it looks like: ``` <button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty" onclick="setLocation('http://mysite.local/eg_ar/checkout/cart/add/uenc/aHR0cDovL2hhaXJidXJzdGFyYWJpYS5sb2NhbC9lZ19hci8,/product/5/form_key/lqUtnptjQU7Cn7E1/qty/1/')"> <span>Add to cart</span> </button> ``` this button is correctly accessed via the variable `btn` and when i use `console.log(btn.attr("onclick"));` it returns `undefined` but with attribute like `id` it returns the id correctly. **NOTE**: the button is working very well. but I can't edit it. **Update**: as per @Saptal question I've to show more code. in the html part I've this block ``` <div class="add-to-cart"> <form id="product_addtocart_form_15"> <span class="custom-counter"> <input min="1" name="qty" id="qty" maxlength="2" value="1" title="qty" class="qty qty-updating" type="number"><div class="custom-counter-nav"><div class="custom-counter-button custom-counter-up">+</div><div class="custom-counter-button custom-counter-down">-</div></div> </span> <button type="button" id="addtocart_btn_15" title="Add to cart" class="button btn-cart btn-cart-with-qty"><span>Add to cart</span></button> </form> </div> ``` and in js I do that ``` <script> jQuery('.qty-updating').each(function(){ var qty = jQuery(this); qty.on('change', function(e){ alert('here'); var btn = qty.parent().siblings('.btn-cart'); console.log(btn.attr("onclick")); }); }); </script> ``` thanks in advance
2017/04/03
[ "https://Stackoverflow.com/questions/43181597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290292/" ]
click event is binded to the button and the onclick attribute isn't set explicitly as a html attribute on the button so, ``` btn.attr('onclick') ``` will return **undefined** and to solve this problem you need to off (unbind) the current click event and on (bind) the new click event as following: ``` btn.off('click'); btn.on('click', function() { yourFunction(); }); ``` hope this helps :)
In your issue description you said you use a plugin which changes the onclick attribute. It seems that there is a JS code which actually deletes that attribute. Can you disable that plugin just to make sure the onclick attribute is NOT deleted?
34,249,401
I was trying to store a json string in local storage and retrieving the value in another function but its not working as expected For storing ``` var data = '{"history":['+'{"keyword":"'+key+'","msg":"'+msg+'","ver":"'+ver+'"}]}'; localStorage.setItem("history",JSON.stringify(data)); ``` For retriving ``` var historydata = JSON.parse(localStorage.getItem("history")); ``` tried to use the historydata.length and its showing 57 (its considering json array as a single string and showing its length ) I want the array size
2015/12/13
[ "https://Stackoverflow.com/questions/34249401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066325/" ]
The variable you are trying to store is already a json encoded string. You can not `stringify` it again. You can drop those `'` and reformat the json, then it would be a normal json, then you can call `stringify` on it. ``` var data = {"history":[{"keyword":key,"msg":msg,"ver":ver}]}; localStorage.setItem("history", JSON.stringify(data)); ``` To get the length of the array after retrieve: ``` var historydata = JSON.parse(localStorage.getItem("history")); console.log(historydata.history.length); ```
You have already a JSON string. After JSON.stringify you get a string from a string. The array size is one, because the content in one object. ```js var key = 'KEY', msg = 'MSG', ver = 'VER', data = '{"history":[' + '{"keyword":"' + key + '","msg":"' + msg + '","ver":"' + ver + '"}]}', obj = JSON.parse(data); document.write(obj.history.length + '<br>'); document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>'); ``` Maybe you consider a better use of object, like an object literal: ```js var key = 'KEY', msg = 'MSG', ver = 'VER', obj = { history: [{ keyword: key, msg: msg, ver: ver }] }; document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>'); ```
29,067,083
I already have this line for Linux box. ``` find . -type f -name '*.txt' -exec ls -l {} \; ``` It's getting all the TXT files in directory. But what I can't do and what I want to do is, to read all the .txt files on subfolder in one directory. For example : ParentTxtFolder --> ChildTxtFolder --> Txtfolder1, Txtfolder2, Txtfolder3. Per one Txtfolder it contains .txt files. So what I want is, to scan Txtfolder1 and count .txtfiles. If this output is possible, Expected output : ``` Txtfolder1 - 14 Txtfolder2 - 10 Txtfolder3 - 18 ``` I'm really stuck on this one. Thanks in advance!
2015/03/15
[ "https://Stackoverflow.com/questions/29067083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4472008/" ]
In your shiro.ini set a web session manager and set that into your security manager. See that helps. ``` sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager securityManager.sessionManager = $sessionManager ```
I had the same problem and I solved it simple by cleaning the cache and cookies from local-host (or whatever is the server address) at the browser. None of the suggestions above worked for me.
71,453,541
I am trying to deploy my app on Heroku with node.js. App is running fine on my local but when I try to deploy it on Heroku it gives the following error: ``` 2022-03-13T00:12:16.474210+00:00 heroku[web.1]: Starting process with command `bin/boot` 2022-03-13T00:12:17.528943+00:00 app[web.1]: bash: bin/boot: No such file or directory 2022-03-13T00:12:17.679770+00:00 heroku[web.1]: Process exited with status 127 2022-03-13T00:12:17.738233+00:00 heroku[web.1]: State changed from starting to crashed 2022-03-13T00:13:07.280433+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=73dc7825-de2b-4a24-bf3f-4d7bfe67ec60 fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https 2022-03-13T00:13:07.460574+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=d29010bf-9c0b-4e27-b902-9540d393f667 fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https 2022-03-13T00:13:41.656858+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=91ecbc00-ee15-4eed-bbfd-c3d3af522548 fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https 2022-03-13T00:13:41.867824+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=cfd378e9-ab85-46a3-b636-3e4fac1140ad fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https ``` My Proficle is this: ``` web: bin/boot ``` and package.json ``` { "name": "sopra-fs22-client-template", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.24.0", "moment": "^2.29.1", "node-gyp": "^8.4.1", "node-sass": "^7.0.1", "react": "^17.0.2", "react-datetime-picker": "^3.5.0", "react-dom": "^17.0.2", "react-router-dom": "^5.3.0", "react-scripts": "^5.0.0", "styled-components": "^5.3.3" }, "scripts": { "dev": "react-scripts start", "start": "serve -s build", "build": "react-scripts build", "eject": "react-scripts eject", "test": "react-scripts test --env=jsdom", "heroku-postbuild": "npm run build" }, "eslintConfig": { "extends": "react-app" }, "browserslist": [ ">0.2%", "not dead", "not ie <= 11", "not op_mini all" ] } ``` I also checked the other posts and tried other things as well but I don't know where else to check thank you very much.
2022/03/13
[ "https://Stackoverflow.com/questions/71453541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17481832/" ]
I would recommend to switch from a web page that serves the sitemap when it's called, to a script that generates static XMLs and that you can optionally call via `crontab`. Step 1: Define directory where sitemaps are saved ------------------------------------------------- This will be used to write one static `xml` file for each sitemap, plus the sitemap index. The directory needs to be writable from the user running the script and accessible via web. ``` define('PATH_TO_SITEMAP', __DIR__.'/www/'); ``` Step 2: Define the public URL where the sitemaps will be reachable ------------------------------------------------------------------ This is the Web URL of the folder you defined above. ``` define('HTTP_TO_SITEMAP', 'https://yourwebsite.com/'); ``` Step 3: Write sitemaps to file ------------------------------ Instead of `echo` the Sitemap, write it to static xml files in the folder defined above. Furthermore keep a counter (`$count_urls` in my example below) for the number of URLs and when it reaches 50k reset the counter, close the sitemap and open a new one. Also, keep a counter of how many sitemaps you're creating (`$count_sitemaps` in my example below). Here's a working example that keeps your structure but writes the multiple files. It's not ideal, you should use a class/method or a function to write the sitemaps and avoid repeated code, but I thought this would be easier to understand as it keeps the same approach you had in your code. ``` $h = fopen(PATH_TO_SITEMAP.'sitemap_'.$count_sitemaps.'.xml', 'w+'); fwrite($h, '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="'.PROTOCOL.'://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>'.SITE_HOST.'</loc> <priority>1.0</priority> </url> '); $count_urls = 0; foreach ($dataAll1 as $val) { $count_urls++; $data = json_decode(file_get_contents('cache-data/'.$val), 1); if ($val == 'index.php') { continue; } // When you reach 50k, close the sitemap, increase the counter and open a new sitemap if ($count_urls >= 50000) { fwrite($h, '</urlset>'); fclose($h); $count_sitemaps++; $h = fopen(PATH_TO_SITEMAP.'sitemap_'.$count_sitemaps.'.xml', 'w+'); fwrite($h, '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="'.PROTOCOL.'://www.sitemaps.org/schemas/sitemap/0.9">'); $count_urls = 0; } fwrite($h, ' <url> <loc>'.SITE_HOST.'/job-detail/'.$data['jk'].'jktk'.$data['tk'].'-'.$service->slugify($data['title']).'</loc> <priority>0.9</priority> <changefreq>daily</changefreq> </url> '); } // Important! Close the final sitemap and save it. fwrite($h, '</urlset>'); fclose($h); ``` Step 4: Write SitemapIndex -------------------------- Finally you write a [sitemapindex](https://www.sitemaps.org/protocol.html#index) file that points to all the sitemaps you generated using the same `$count_sitemaps` counter. ``` // Build the SitemapIndex $h = fopen(PATH_TO_SITEMAP.'sitemap.xml', 'w+'); fwrite($h, '<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'); for ($i = 1; $i <= $count_sitemaps; $i++) { fwrite($h, ' <sitemap> <loc>'.HTTP_TO_SITEMAP.'sitemap_'.$i.'.xml</loc> <lastmod>'.date('c').'</lastmod> </sitemap> '); } fwrite($h, ' </sitemapindex>'); fclose($h); ``` Step 5 (optional): ping Google ------------------------------ ``` file_get_contents('https://www.google.com/webmasters/tools/ping?sitemap='.urlencode(HTTP_TO_SITEMAP.'sitemap.xml')); ``` Conclusions ----------- As mentioned this approach is a bit messy and doesn't follow best practices on code re-use, but it should be quite clear on how to loop, store multiple sitemaps and finally build the sitemapindex file. For a better approach, I suggest you to look at this [open source Sitemap class](https://github.com/andreaolivato/Sitemap).
You should start the array generated from the scandir with the 50001, but it would be better to split it into several scripts with a crontab, so you don't exhaust the server with excessive runtime; otherwise, increase the runtime of PHP scripts.
51,889,794
Here's my custom module stored in `util.py` that wrapps up 3-steps what I always gone-through to read images when using `tensorflow` ``` #tf_load_image from path def load_image(image_path, image_shape, clr_normalize = True ): '''returns tensor-array on given image path and image_shape [height, width]''' import tensorflow as tf image = tf.read_file(image_path) image = tf.image.decode_jpeg(image, channels=3) if clr_normalize == True: image = tf.image.resize_images(image, image_shape) / 127.5 - 1 else: image = tf.image.resize_images(image, image_shape) return image ``` But this is quite inefficient to deal with lots of image load since it generally calls `import tensorflow as tf` everytime I read "single image". I'd like to let this function to inherit `tf` command from the `main.py`'s tf where the load\_image actually imported into. Like.. ``` import tensor flow as tf from util import load_image image = load_image("path_string") #where load_image no longer wraps the import tensorflow as tf in itself. ```
2018/08/17
[ "https://Stackoverflow.com/questions/51889794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8889050/" ]
> > But this is quite inefficient (...) since it generally calls `import tensorflow as tf` everytime I read "single image". > > > imported modules are cached in `sys.modules` on first import (I mean "the very first time a module is imported in a given process"), subsequent calls will retrieve already imported modules from this cache, so the overhead is way less than you might think. But anyway: > > I'd like to let this function to inherit tf command from the main.py's tf where the load\_image actually imported into. > > > The only way would be to explicitely pass the module to your function, ie: ``` # utils.py def load_image(tf, ....): # code here using `tf` ``` and then ``` # main.py import tensorflow as tf from utils import load_image im = load_image(tf, ...) ``` BUT this is actually totally useless: all you have to do is, in utils.py, to move the import statement out of the function: ``` # utils.py import tensorflow as tf def load_image(image_path, image_shape, clr_normalize = True ): '''returns tensor-array on given image path and image_shape [height, width]''' import tensorflow as tf image = tf.read_file(image_path) image = tf.image.decode_jpeg(image, channels=3) if clr_normalize: image = tf.image.resize_images(image, image_shape) / 127.5 - 1 else: image = tf.image.resize_images(image, image_shape) return image ``` FWIW, [it IS officially recommanded to put all your imports at the top of the module](https://www.python.org/dev/peps/pep-0008/#imports), before any other definitions (functions, classes, whatever). Importing within a function should only be used as a Q&D last resort fix for circular imports (which are usually a sure sign you have a design issue and should actually be fixed by fixing the design itself).
As @MatrixTai has suggested in the comments, you could make `utils.py` like this: ``` import tensorflow as tf def load_image(.........): ............ ``` and in `main.py`, you could `import util` as you want to.
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can't do it the way you want to because borders add pixels to the dimensions. The closest thing you could do is remove one of the sides of each rectangle that otherwise would have double, [like this](http://jsfiddle.net/cyd4M/), but the container still has to be `153px` by `153px` because you have the border each side and one in between two elements Using negative margins do the same thing as the above fix, but it is still impossible to get it 150x150 pixels using that method Using `outline` instead you can get close, but you can't remove part of an outline [so it's not perfect](http://jsfiddle.net/cyd4M/1/) This leaves you with the following options (in addition to the ones linked above) to have a perfectly 150x150 total box: * [Don't have a border at all](http://jsfiddle.net/cyd4M/2/) * [Make the inner rectangles smaller](http://jsfiddle.net/cyd4M/3/) If you only need a border around the outside then do as RDrazard said and apply the border to `#container`
the div falling out of the container is expected behavior because you are making a floating div. when the size of the screen grows the div is bound to be squeeze out of the container.
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your borders push it out. Set the border to the container and leave the height and width at 150px, as it should be with rectangles of 100x50 in the layout you posted. Cleaned up the code. [**JSFiddle demonstration.**](http://jsfiddle.net/v8uR7/) ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { display: block; border: 1px solid #000; background-color:#ff0000; height:150px; width:150px; } .horizontal { width:100px; height:50px; } .vertical { width:50px; height:100px; } #box1 { background-color:#ffffff } #box2 { background-color:#cccccc; } #box3 { background-color:#999999; } #box4 { background-color:#666666 } #box1, #box3 { float: left; } #box2, #box4 { float: right; } ```
You can't do it the way you want to because borders add pixels to the dimensions. The closest thing you could do is remove one of the sides of each rectangle that otherwise would have double, [like this](http://jsfiddle.net/cyd4M/), but the container still has to be `153px` by `153px` because you have the border each side and one in between two elements Using negative margins do the same thing as the above fix, but it is still impossible to get it 150x150 pixels using that method Using `outline` instead you can get close, but you can't remove part of an outline [so it's not perfect](http://jsfiddle.net/cyd4M/1/) This leaves you with the following options (in addition to the ones linked above) to have a perfectly 150x150 total box: * [Don't have a border at all](http://jsfiddle.net/cyd4M/2/) * [Make the inner rectangles smaller](http://jsfiddle.net/cyd4M/3/) If you only need a border around the outside then do as RDrazard said and apply the border to `#container`
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I did this and it worked: html ``` <div id="container"> <div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="div4">4</div> </div> ``` css: ``` * { padding: 0; margin: 0; } #container { border: 1px dotted green; width: 250px; height: 250px; margin: 30px auto; background: red; } #div1 { background: #fff; float: left; width: 60%; height: 30%; } #div2 { background: #333; float: right; width: 40%; height: 70%; } #div3 { background: #555; float: left; width: 40%; height: 70%; } #div4 { background: #999; float: right; width: 60%; height: 30%; } ``` Follow fiddle: <http://jsfiddle.net/637R9/>
the div falling out of the container is expected behavior because you are making a floating div. when the size of the screen grows the div is bound to be squeeze out of the container.
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your borders push it out. Set the border to the container and leave the height and width at 150px, as it should be with rectangles of 100x50 in the layout you posted. Cleaned up the code. [**JSFiddle demonstration.**](http://jsfiddle.net/v8uR7/) ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { display: block; border: 1px solid #000; background-color:#ff0000; height:150px; width:150px; } .horizontal { width:100px; height:50px; } .vertical { width:50px; height:100px; } #box1 { background-color:#ffffff } #box2 { background-color:#cccccc; } #box3 { background-color:#999999; } #box4 { background-color:#666666 } #box1, #box3 { float: left; } #box2, #box4 { float: right; } ```
I did this and it worked: html ``` <div id="container"> <div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="div4">4</div> </div> ``` css: ``` * { padding: 0; margin: 0; } #container { border: 1px dotted green; width: 250px; height: 250px; margin: 30px auto; background: red; } #div1 { background: #fff; float: left; width: 60%; height: 30%; } #div2 { background: #333; float: right; width: 40%; height: 70%; } #div3 { background: #555; float: left; width: 40%; height: 70%; } #div4 { background: #999; float: right; width: 60%; height: 30%; } ``` Follow fiddle: <http://jsfiddle.net/637R9/>
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
<http://jsfiddle.net/ku9bf/1/> Use negative margins, ex: ``` #box3 { margin-top: -1px; } ``` and reduce the max-width of the container by 1px.
the div falling out of the container is expected behavior because you are making a floating div. when the size of the screen grows the div is bound to be squeeze out of the container.
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your borders push it out. Set the border to the container and leave the height and width at 150px, as it should be with rectangles of 100x50 in the layout you posted. Cleaned up the code. [**JSFiddle demonstration.**](http://jsfiddle.net/v8uR7/) ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { display: block; border: 1px solid #000; background-color:#ff0000; height:150px; width:150px; } .horizontal { width:100px; height:50px; } .vertical { width:50px; height:100px; } #box1 { background-color:#ffffff } #box2 { background-color:#cccccc; } #box3 { background-color:#999999; } #box4 { background-color:#666666 } #box1, #box3 { float: left; } #box2, #box4 { float: right; } ```
<http://jsfiddle.net/ku9bf/1/> Use negative margins, ex: ``` #box3 { margin-top: -1px; } ``` and reduce the max-width of the container by 1px.
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your borders push it out. Set the border to the container and leave the height and width at 150px, as it should be with rectangles of 100x50 in the layout you posted. Cleaned up the code. [**JSFiddle demonstration.**](http://jsfiddle.net/v8uR7/) ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { display: block; border: 1px solid #000; background-color:#ff0000; height:150px; width:150px; } .horizontal { width:100px; height:50px; } .vertical { width:50px; height:100px; } #box1 { background-color:#ffffff } #box2 { background-color:#cccccc; } #box3 { background-color:#999999; } #box4 { background-color:#666666 } #box1, #box3 { float: left; } #box2, #box4 { float: right; } ```
the div falling out of the container is expected behavior because you are making a floating div. when the size of the screen grows the div is bound to be squeeze out of the container.
1,326,572
Let $X$ be a (possibly T1, that is, singleton subsets are closed) topological space. Suppose that there is a *proper* subset $D \subset X$ such that: * $D$ is dense in $X$; * $D$ is homeomorphic to $X$. What can be said about $X$?
2015/06/15
[ "https://math.stackexchange.com/questions/1326572", "https://math.stackexchange.com", "https://math.stackexchange.com/users/248346/" ]
$$32(x + 1) = y^2 \implies 32 \mid y^2 \implies 4 \mid y$$ so let $y = 4z$. $$2(x+1) = z^2 \implies 2 \mid z$$ so let $z = 2w$ $$x + 1 = 2w^2 $$ so given any $w$ we can solve for $x$. So the set of solutions is $$\{(2w^2 - 1, 8w) \mid w \in \Bbb Z\}$$
The answer by user3491648 gives a complete characterization of the full set of values $x$ for which $32x+32$ is a square numbers. This is really just an observation on the set of values $$\{64,1600,53824,1827904,62094400,2109381184\}$$ reported by the OP. These are not actually values that $x$ takes on. (As user3491648 finds, it requires on *odd* value of $x$ to make $32x+32$ a square.) Rather, these seem to be the square values that correspond to values of $x$ that are themselves squares, namely of the following values: $$\{1,7,41,239,1393,8119\}$$ For example, $32\cdot239^2+32=1827904$. It's unclear why these values are being singled out, but they do seem to obey a two-term recursion, namely $$a\_{n+1}=6a\_n-a\_{n-1}$$ For example, $1393=6\cdot239-41$.
1,326,572
Let $X$ be a (possibly T1, that is, singleton subsets are closed) topological space. Suppose that there is a *proper* subset $D \subset X$ such that: * $D$ is dense in $X$; * $D$ is homeomorphic to $X$. What can be said about $X$?
2015/06/15
[ "https://math.stackexchange.com/questions/1326572", "https://math.stackexchange.com", "https://math.stackexchange.com/users/248346/" ]
$$32(x + 1) = y^2 \implies 32 \mid y^2 \implies 4 \mid y$$ so let $y = 4z$. $$2(x+1) = z^2 \implies 2 \mid z$$ so let $z = 2w$ $$x + 1 = 2w^2 $$ so given any $w$ we can solve for $x$. So the set of solutions is $$\{(2w^2 - 1, 8w) \mid w \in \Bbb Z\}$$
Solution for x such that 32x+32 is a square as follows: For integral solution, x= (n2 -2)/2 such that x is in Natural number.(n is in natural number)
1,326,572
Let $X$ be a (possibly T1, that is, singleton subsets are closed) topological space. Suppose that there is a *proper* subset $D \subset X$ such that: * $D$ is dense in $X$; * $D$ is homeomorphic to $X$. What can be said about $X$?
2015/06/15
[ "https://math.stackexchange.com/questions/1326572", "https://math.stackexchange.com", "https://math.stackexchange.com/users/248346/" ]
The answer by user3491648 gives a complete characterization of the full set of values $x$ for which $32x+32$ is a square numbers. This is really just an observation on the set of values $$\{64,1600,53824,1827904,62094400,2109381184\}$$ reported by the OP. These are not actually values that $x$ takes on. (As user3491648 finds, it requires on *odd* value of $x$ to make $32x+32$ a square.) Rather, these seem to be the square values that correspond to values of $x$ that are themselves squares, namely of the following values: $$\{1,7,41,239,1393,8119\}$$ For example, $32\cdot239^2+32=1827904$. It's unclear why these values are being singled out, but they do seem to obey a two-term recursion, namely $$a\_{n+1}=6a\_n-a\_{n-1}$$ For example, $1393=6\cdot239-41$.
Solution for x such that 32x+32 is a square as follows: For integral solution, x= (n2 -2)/2 such that x is in Natural number.(n is in natural number)
18,024,759
I want to prevent a ComboBox to resize acording to the size of the selected item. Consider this simplified example: ``` <Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="150" Width="300"> <GroupBox Header="Group Header" Margin="5"> <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ComboBox MinWidth="100" Grid.Column="0" Margin="5" MaxWidth="150"/> <ComboBox Grid.Column="1" Margin="5" MinWidth="110"> <ComboBoxItem Content="Very loooooooooooooooooooooooooooooooooooooooong text"/> <ComboBoxItem Content="Normal text"/> </ComboBox> </Grid> </ScrollViewer> </GroupBox> </Window> ``` When you select the first item in the second ComboBox, that ComboBox is expanded so the whole content of the selected item fits, hiding the ComboBox from the left I would like to achieve three things: * Have the scrollviewer so the controls fit in their minimum size * If the Window is very large, I want the second ComboBox to fit the remaining size * If I select a very long item in the second ComboBox, I want it to preserve the size it had and **not** adjust to the contents of the selected item Is it possible?
2013/08/02
[ "https://Stackoverflow.com/questions/18024759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1094526/" ]
Edit: ----- I looked again at the problem and found out much simpler solution than previously proposed. The idea is to override MeasureOverride function of the ComboBox class and provide limited space that is available, where width is equal to the MinWidth property of the ComboBox. In order to do that we create ComboBox derived class: ``` public class MyComboBox : ComboBox { protected override Size MeasureOverride(Size constraint) { return base.MeasureOverride(new Size(MinWidth, constraint.Height)); } } ``` and then we use it in our control in place of ComboBox with HorizontalContentAlignment set to Stretch: ``` <local:MyComboBox Grid.Column="1" Margin="5" MinWidth="110" HorizontalContentAlignment="Stretch"> <ComboBoxItem Content="Very loooooooooooooooooooooooooooooooooooooooong text"/> <ComboBoxItem Content="Normal text"/> </local:MyComboBox> ``` Previously proposed, too complex solution: ------------------------------------------ You can bind the MaxWidth property of the second ComboBox to the space which is left (you can calculate it): ``` <Window x:Class="Example.MainWindow" xmlns:local="clr-namespace:Example" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="150" Width="300"> <Window.Resources> <local:SubstractConverter x:Key="SubstractConverter"/> </Window.Resources> <GroupBox Header="Group Header" Margin="5"> <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" x:Name="ScrollViewer1"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ComboBox MinWidth="100" Grid.Column="0" Margin="5" MaxWidth="150" x:Name="ComboBox1"/> <ComboBox Grid.Column="1" Margin="5" MinWidth="110"> <ComboBox.MaxWidth> <MultiBinding Converter="{StaticResource SubstractConverter}"> <Binding ElementName="ScrollViewer1" Path="ActualWidth"/> <Binding ElementName="ComboBox1" Path="ActualWidth"/> <Binding ElementName="ComboBox1" Path="Margin.Left"/> <Binding ElementName="ComboBox1" Path="Margin.Right"/> <Binding Path="Margin.Left" RelativeSource="{RelativeSource Self}"/> <Binding Path="Margin.Right" RelativeSource="{RelativeSource Self}"/> </MultiBinding> </ComboBox.MaxWidth> <ComboBoxItem Content="Very loooooooooooooooooooooooooooooooooooooooong text"/> <ComboBoxItem Content="Normal text"/> </ComboBox> </Grid> </ScrollViewer> </GroupBox> </Window> ``` I'm substracting ActualWidth of the first combobox, its margins and margins of the second combobox from the ActualWidth of the scrollviewer. In order to have less elements to substract, you can put a border around ComboBox1. You will then substract border's ActualWidth instead of ComboBox1 properties. Converter which is used here: ``` public class SubstractConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values != null && values.Any()) { var result = System.Convert.ToDouble(values.First()); var toSubstract = values.Skip(1); foreach (var number in toSubstract) { result -= System.Convert.ToDouble(number); } return result; } return 0d; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } ```
I had the same problem with a ComboBox inside a ScrollViewer. I did not want a horizontal scrolling but only vertical. But the ComboBox kept resizing itself to the selected item. I used aligators answer but replaced MinWidth with ActualWidth which keeps the CombobBox from resizing itself, but the selected item will always use the space available. ``` public class FixedWidthComboBox : ComboBox { protected override Size MeasureOverride(Size constraint) { return base.MeasureOverride(new Size(ActualWidth, constraint.Height)); } } ```
462,153
I have thermoelectric modules and set it in series, then I connected to a DC to DC step up (CN6009) to enhance the voltage. Then I connected to my phone with usb charger to try charge with it, but the voltage suddenly drops. Should I change the step up or increase the amount of the module?
2019/10/09
[ "https://electronics.stackexchange.com/questions/462153", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/233718/" ]
You've got a couple of things going on that are causing your problems: 1. The output resistance of [TEG modules](https://en.wikipedia.org/wiki/Thermoelectric_generator#Practical_limitations) is fairly high. They act like a battery with a big resistor in series. 2. By boosting the voltage, you increase the needed current. Say you need 5V at 1A to charge your phone, and your TEG can deliver 2.5V. Your TEG will have to provide 2.5V at 2A in order to deliver the 5 watts of power your charger needs. Those two combine to cause your voltage drop. 1. Voltage **always** drops when current flows through a resistor. The TEG doesn't have a seperate resistor in it. Its construction involves materials and connections that raise the electrical resistance. They **must** be made that way to work, it isn't an artificial limit. 2. You have the TEGs in series, so the internal resistance adds up. If you have, say, three TEGs in series then you have three times the resistance. 3. Boosting the voltage increases the current draw from the TEG, and makes the voltage drop worse. The problem boils down to your charger needing more power than the TEGs can provide. * You can try putting more TEGs in parallel. * You can try using a more efficient boost converter. * You could use larger TEGs. * You could put the TEGs in parallel and charge a low voltage battery, then charge your phone from the low voltage battery using a boost converter. That last solution means you charge a low voltage battery slowly with your TEGs. When that battery is fully charged, you use it with a boost converter to quickly charge your phone.
I think that peltier devices act as current sources up to some maximum voltage. If you demand more current than the devices supply, the voltage will drop. Measure the current produced by one device and then calculate the number of peltier devices you need to deliver the target current into your boost converter.
1,295,381
I'm trying to convert a **mkv** file and add a watermark logo to it, but I tried a bunch of different instructions but it is always missing the logo after 24 seconds of the video. Here's my code: ``` ffmpeg \ -i RTed83e104ac4d98c46383630d733a3282.mkv \ -i RT894ce44c6ba84eb98300566adae4e7bf.mka \ -i logo_white.png \ -filter_complex "[2] scale=120:18 [ovr1], [0:v][ovr1]overlay=10:452" \ output.mp4 ``` For example: <https://cl.ly/0F3K1K121E2W> you can see the image is gone after 24 seconds. What I'm doing wrong? **OUTPUT/LOGS**: ``` ffmpeg \ -i RTed83e104ac4d98c46383630d733a3282.mkv \ -i RT894ce44c6ba84eb98300566adae4e7bf.mka \ -i logo_white.png \ -filter_complex "[2] scale=120:18 [ovr1], [0:v][ovr1]overlay=10:452" \ output.mp4 ffmpeg version 3.4.1 Copyright (c) 2000-2017 the FFmpeg developers built with Apple LLVM version 9.0.0 (clang-900.0.39.2) configuration: --prefix=/usr/local/Cellar/ffmpeg/3.4.1 --enable-shared --enable-pthreads --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-gpl --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --enable-videotoolbox --disable-lzma libavutil 55. 78.100 / 55. 78.100 libavcodec 57.107.100 / 57.107.100 libavformat 57. 83.100 / 57. 83.100 libavdevice 57. 10.100 / 57. 10.100 libavfilter 6.107.100 / 6.107.100 libavresample 3. 7. 0 / 3. 7. 0 libswscale 4. 8.100 / 4. 8.100 libswresample 2. 9.100 / 2. 9.100 libpostproc 54. 7.100 / 54. 7.100 Input #0, matroska,webm, from 'RTed83e104ac4d98c46383630d733a3282.mkv': Metadata: encoder : GStreamer matroskamux version 1.8.1.1 creation_time : 2018-02-13T18:16:31.000000Z Duration: 00:05:48.26, start: 1.456000, bitrate: 528 kb/s Stream #0:0(eng): Video: h264 (Constrained Baseline), yuv420p(progressive), 640x480, SAR 1:1 DAR 4:3, 30 fps, 30 tbr, 1k tbn, 2k tbc (default) Metadata: title : Video Input #1, matroska,webm, from 'RT894ce44c6ba84eb98300566adae4e7bf.mka': Metadata: encoder : GStreamer matroskamux version 1.8.1.1 creation_time : 2018-02-13T18:16:31.000000Z Duration: 00:05:47.78, start: 1.421000, bitrate: 45 kb/s Stream #1:0(eng): Audio: opus, 48000 Hz, stereo, fltp (default) Metadata: title : Audio Input #2, png_pipe, from 'logo_white.png': Duration: N/A, bitrate: N/A Stream #2:0: Video: png, rgba(pc), 600x90, 25 tbr, 25 tbn, 25 tbc Stream mapping: Stream #0:0 (h264) -> overlay:main (graph 0) Stream #2:0 (png) -> scale (graph 0) overlay (graph 0) -> Stream #0:0 (libx264) Stream #1:0 -> #0:1 (opus (native) -> aac (native)) Press [q] to stop, [?] for help [libx264 @ 0x7fc62308c400] using SAR=1/1 [libx264 @ 0x7fc62308c400] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 AVX2 LZCNT BMI2 [libx264 @ 0x7fc62308c400] profile High, level 3.0 [libx264 @ 0x7fc62308c400] 264 - core 148 r2795 aaa9aa8 - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00 Output #0, mp4, to 'output.mp4': Metadata: encoder : Lavf57.83.100 Stream #0:0: Video: h264 (libx264) (avc1 / 0x31637661), yuv420p(progressive), 640x480 [SAR 1:1 DAR 4:3], q=-1--1, 30 fps, 15360 tbn, 30 tbc (default) Metadata: encoder : Lavc57.107.100 libx264 Side data: cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: -1 Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default) Metadata: title : Audio encoder : Lavc57.107.100 aac Past duration 0.609993 too large 0kB time=00:00:01.73 bitrate= 0.2kbits/s dup=7 drop=0 speed=3.43x Last message repeated 2 times frame=10449 fps=152 q=-1.0 Lsize= 11658kB time=00:05:48.20 bitrate= 274.3kbits/s dup=151 drop=0 speed=5.06x video:5860kB audio:5422kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 3.338063% [libx264 @ 0x7fc62308c400] frame I:42 Avg QP:13.16 size: 32061 [libx264 @ 0x7fc62308c400] frame P:2657 Avg QP:18.79 size: 1347 [libx264 @ 0x7fc62308c400] frame B:7750 Avg QP:22.91 size: 138 [libx264 @ 0x7fc62308c400] consecutive B-frames: 0.9% 0.5% 0.5% 98.1% [libx264 @ 0x7fc62308c400] mb I I16..4: 13.1% 64.6% 22.3% [libx264 @ 0x7fc62308c400] mb P I16..4: 0.3% 0.7% 0.1% P16..4: 10.4% 3.3% 1.7% 0.0% 0.0% skip:83.5% [libx264 @ 0x7fc62308c400] mb B I16..4: 0.0% 0.0% 0.0% B16..8: 8.0% 0.1% 0.0% direct: 0.0% skip:91.7% L0:41.7% L1:56.6% BI: 1.7% [libx264 @ 0x7fc62308c400] 8x8 transform intra:63.1% inter:64.4% [libx264 @ 0x7fc62308c400] coded y,uvDC,uvAC intra: 75.8% 77.6% 61.0% inter: 1.3% 2.0% 0.2% [libx264 @ 0x7fc62308c400] i16 v,h,dc,p: 17% 13% 37% 33% [libx264 @ 0x7fc62308c400] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 25% 17% 25% 5% 4% 4% 5% 6% 9% [libx264 @ 0x7fc62308c400] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 30% 18% 17% 8% 5% 5% 5% 5% 7% [libx264 @ 0x7fc62308c400] i8c dc,h,v,p: 57% 20% 18% 5% [libx264 @ 0x7fc62308c400] Weighted P-Frames: Y:0.0% UV:0.0% [libx264 @ 0x7fc62308c400] ref P L0: 65.0% 9.6% 16.7% 8.8% [libx264 @ 0x7fc62308c400] ref B L0: 85.7% 12.4% 1.9% [libx264 @ 0x7fc62308c400] ref B L1: 93.5% 6.5% [libx264 @ 0x7fc62308c400] kb/s:137.80 [aac @ 0x7fc623086600] Qavg: 5304.135 ```
2018/02/15
[ "https://superuser.com/questions/1295381", "https://superuser.com", "https://superuser.com/users/873164/" ]
WebRTC sourced inputs are often sloppy and may change parameters midstream resulting in surprises. In your case a lazy solution could be to loop the overlay image: ``` ffmpeg \ -i RTed83e104ac4d98c46383630d733a3282.mkv \ -i RT894ce44c6ba84eb98300566adae4e7bf.mka \ -loop 1 -i logo_white.png \ -filter_complex "[2] scale=120:18 [ovr1], [0:v][ovr1]overlay=10:452:shortest=1" \ output.mp4 ```
I was able to do what I was looking for, but I had to do it in steps. I think my problem was because my videos are from WebRTC as @LordNeckbeard explained bellow. Here's my **solution** if someone in the future needs it: ``` # convert student video + audio ffmpeg \ -i RT0dcbc54f85d17eb6f7922f58f7b12079.mkv \ -i RTb0ccec59e2119a15642b7cd772db843e.mka \ student.mp4 # convert instructor video + audio ffmpeg \ -i RTed83e104ac4d98c46383630d733a3282.mkv \ -i RT894ce44c6ba84eb98300566adae4e7bf.mka \ instructor.mp4 # add watermark to instructor_video ffmpeg \ -i instructor.mp4 \ -i logo_white.png \ -filter_complex "[1] scale=120:18 [ovr1], [0:v][ovr1]overlay=10:452" \ instructor_with_logo.mp4 # Final - Include student video ffmpeg \ -i instructor_with_logo.mp4 \ -i student.mp4 \ -filter_complex "[1:v]setpts=PTS-STARTPTS+24/TB[v1]; \ [v1] scale=120:90 [student], [0:v][student]overlay=510:380:enable='between(t,24,36)'" \ final.mp4 ```
73,937,079
I have a table that contains this (HIght value, LOw value data according to a DatetTime): ``` mysql> select dt, hi, lo from mytable where dt >='2022-10-03 09:20:00' limit 20; +---------------------+--------+--------+ | dt | hi | lo | +---------------------+--------+--------+ | 2022-10-03 09:21:00 | 4.1200 | 4.1180 | | 2022-10-03 09:24:00 | 4.1080 | 4.1040 | | 2022-10-03 09:25:00 | 4.1040 | 4.1000 | | 2022-10-03 09:26:00 | 4.0960 | 4.0940 | | 2022-10-03 09:28:00 | 4.0940 | 4.0920 | | 2022-10-03 09:29:00 | 4.0980 | 4.0940 | | 2022-10-03 09:31:00 | 4.1020 | 4.0980 | | 2022-10-03 09:32:00 | 4.1000 | 4.1000 | | 2022-10-03 09:33:00 | 4.0940 | 4.0940 | | 2022-10-03 09:36:00 | 4.0720 | 4.0720 | | 2022-10-03 09:37:00 | 4.0600 | 4.0500 | | 2022-10-03 09:39:00 | 4.0620 | 4.0560 | | 2022-10-03 09:42:00 | 4.0660 | 4.0580 | | 2022-10-03 09:47:00 | 4.0620 | 4.0620 | | 2022-10-03 09:48:00 | 4.0620 | 4.0620 | | 2022-10-03 09:50:00 | 4.0580 | 4.0580 | | 2022-10-03 09:51:00 | 4.0580 | 4.0580 | | 2022-10-03 09:52:00 | 4.0560 | 4.0540 | | 2022-10-03 09:53:00 | 4.0460 | 4.0460 | | 2022-10-03 09:55:00 | 4.0420 | 4.0360 | +---------------------+--------+--------+ 20 rows in set (0,00 sec) ``` I want to obtain, in MySQL (because I'm learning a little), for each line the differance (rdif) between the 'hi' of the line and the 'lo' of 10 minutes ago. I get it like this: (I know, the 'as' are optional, but it helps to understand better) ``` mysql> select dt as rdt, hi as rhi, (select lo from mytable where dt = rdt-interval 10 minute) as rlo, (hi-(select rlo)) as rdif from mytable where dt >= '2022-10-03 09:20:00' limit 20; +---------------------+--------+--------+---------+ | rdt | rhi | rlo | rdif | +---------------------+--------+--------+---------+ | 2022-10-03 09:21:00 | 4.1200 | 3.9900 | 0.1300 | | 2022-10-03 09:24:00 | 4.1080 | 4.0180 | 0.0900 | | 2022-10-03 09:25:00 | 4.1040 | 4.0500 | 0.0540 | | 2022-10-03 09:26:00 | 4.0960 | 4.0800 | 0.0160 | | 2022-10-03 09:28:00 | 4.0940 | NULL | NULL | | 2022-10-03 09:29:00 | 4.0980 | NULL | NULL | | 2022-10-03 09:31:00 | 4.1020 | 4.1180 | -0.0160 | | 2022-10-03 09:32:00 | 4.1000 | NULL | NULL | | 2022-10-03 09:33:00 | 4.0940 | NULL | NULL | | 2022-10-03 09:36:00 | 4.0720 | 4.0940 | -0.0220 | | 2022-10-03 09:37:00 | 4.0600 | NULL | NULL | | 2022-10-03 09:39:00 | 4.0620 | 4.0940 | -0.0320 | | 2022-10-03 09:42:00 | 4.0660 | 4.1000 | -0.0340 | | 2022-10-03 09:47:00 | 4.0620 | 4.0500 | 0.0120 | | 2022-10-03 09:48:00 | 4.0620 | NULL | NULL | | 2022-10-03 09:50:00 | 4.0580 | NULL | NULL | | 2022-10-03 09:51:00 | 4.0580 | NULL | NULL | | 2022-10-03 09:52:00 | 4.0560 | 4.0580 | -0.0020 | | 2022-10-03 09:53:00 | 4.0460 | NULL | NULL | | 2022-10-03 09:55:00 | 4.0420 | NULL | NULL | +---------------------+--------+--------+---------+ 20 rows in set (0,00 sec) ``` The 'NULL' is normal because there is not always the previous minute that corresponds (in addition it suits me in this case) But I have questions: 1) In "(hi-(select rlo)) as rdif" why can't I just use 'rlo' (have to add the select)? (Even if you answer the question below, please answer this one anyway) 2) How to avoid double select-from in table? (is that a subquery?) There must be better… What do you suggest? 3) I then consider other operations, in this style, more or less simple but complicated for me in MySQL. (calculations plus column updates..., not necessarily selections to display...) Do I have a better way to simply read/write the table and code these calculations in my app in nodejs (which I master: I'm learning a little MySQL, ok, but I still want to finsh my app…) (How much would run time be?) Thanks !
2022/10/03
[ "https://Stackoverflow.com/questions/73937079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15157921/" ]
You have to use `(select rlo)` because you can't refer to a column alias in the same query The more proper way to do this is with a self-join, then you don't need multiple selects for each calculation. You need to use `LEFT JOIN` to get null values when there's no matching row. ``` SELECT t1.dt as rdt, t1.hi as rhi, t2.lo AS rlo, t1.hi - t2.lo AS rdif FROM mytable AS t1 LEFT JOIN mytable AS t2 ON t2.dt = t1.dt - INTERVAL 10 MINUTE where t1.dt >= '2022-10-03 09:20:00' limit 20 ``` [DEMO](https://www.db-fiddle.com/f/bAUjRtNB3wQH9JMZpwUcf8/1)
ad 1) you've got to think of the logical execution order of SQL queries which is roughly: FROM (data source), WHERE (filter), SELECT (projection). That is, the expressions in the SELECT clause are applied to the filtered data specified in the FROM and WHERE clauses. Therefore it makes perfect sense that an expression can't refer directly to another expression in the SELECT clause. But there's an exception: subqueries. They are evaluated on their own, have their own expression list and can contain backward references to column aliases, that is ``` SELECT col AS x, (SELECT x) FORM tbl ``` is allowed, since `x` was declared before it was selected, while ``` SELECT (SELECT x), col AS x FORM tbl ``` will result in an error, because forward references are not supported. Although this is poorly documented, you can find more information on subqueries in [section 13.2.11](https://dev.mysql.com/doc/refman/8.0/en/subqueries.html) of the MySQL 8.0 Reference Manual. ad 2) see the [answer](https://stackoverflow.com/a/73937351/19657183) of user [Barmar](https://stackoverflow.com/users/1491895/barmar). The LEFT JOIN means: give me all record of the left table and join them with the records of the right table based on the ON condition. If there's no matching record in the right table, use NULL values. An INNER JOIN would only return matching records, that is records from the left table which have a matching record in the right table (based on the ON condition). ad 3) Of course, you can calculate in MySQL, too. That's what you already do, e.g. by `t1.dt - INTERVAL 10 MINUTE`. Some people try to do anything in SQL (if possible all kind of things in a single query...) which is something I wouldn't do. Keep it simple.
73,937,079
I have a table that contains this (HIght value, LOw value data according to a DatetTime): ``` mysql> select dt, hi, lo from mytable where dt >='2022-10-03 09:20:00' limit 20; +---------------------+--------+--------+ | dt | hi | lo | +---------------------+--------+--------+ | 2022-10-03 09:21:00 | 4.1200 | 4.1180 | | 2022-10-03 09:24:00 | 4.1080 | 4.1040 | | 2022-10-03 09:25:00 | 4.1040 | 4.1000 | | 2022-10-03 09:26:00 | 4.0960 | 4.0940 | | 2022-10-03 09:28:00 | 4.0940 | 4.0920 | | 2022-10-03 09:29:00 | 4.0980 | 4.0940 | | 2022-10-03 09:31:00 | 4.1020 | 4.0980 | | 2022-10-03 09:32:00 | 4.1000 | 4.1000 | | 2022-10-03 09:33:00 | 4.0940 | 4.0940 | | 2022-10-03 09:36:00 | 4.0720 | 4.0720 | | 2022-10-03 09:37:00 | 4.0600 | 4.0500 | | 2022-10-03 09:39:00 | 4.0620 | 4.0560 | | 2022-10-03 09:42:00 | 4.0660 | 4.0580 | | 2022-10-03 09:47:00 | 4.0620 | 4.0620 | | 2022-10-03 09:48:00 | 4.0620 | 4.0620 | | 2022-10-03 09:50:00 | 4.0580 | 4.0580 | | 2022-10-03 09:51:00 | 4.0580 | 4.0580 | | 2022-10-03 09:52:00 | 4.0560 | 4.0540 | | 2022-10-03 09:53:00 | 4.0460 | 4.0460 | | 2022-10-03 09:55:00 | 4.0420 | 4.0360 | +---------------------+--------+--------+ 20 rows in set (0,00 sec) ``` I want to obtain, in MySQL (because I'm learning a little), for each line the differance (rdif) between the 'hi' of the line and the 'lo' of 10 minutes ago. I get it like this: (I know, the 'as' are optional, but it helps to understand better) ``` mysql> select dt as rdt, hi as rhi, (select lo from mytable where dt = rdt-interval 10 minute) as rlo, (hi-(select rlo)) as rdif from mytable where dt >= '2022-10-03 09:20:00' limit 20; +---------------------+--------+--------+---------+ | rdt | rhi | rlo | rdif | +---------------------+--------+--------+---------+ | 2022-10-03 09:21:00 | 4.1200 | 3.9900 | 0.1300 | | 2022-10-03 09:24:00 | 4.1080 | 4.0180 | 0.0900 | | 2022-10-03 09:25:00 | 4.1040 | 4.0500 | 0.0540 | | 2022-10-03 09:26:00 | 4.0960 | 4.0800 | 0.0160 | | 2022-10-03 09:28:00 | 4.0940 | NULL | NULL | | 2022-10-03 09:29:00 | 4.0980 | NULL | NULL | | 2022-10-03 09:31:00 | 4.1020 | 4.1180 | -0.0160 | | 2022-10-03 09:32:00 | 4.1000 | NULL | NULL | | 2022-10-03 09:33:00 | 4.0940 | NULL | NULL | | 2022-10-03 09:36:00 | 4.0720 | 4.0940 | -0.0220 | | 2022-10-03 09:37:00 | 4.0600 | NULL | NULL | | 2022-10-03 09:39:00 | 4.0620 | 4.0940 | -0.0320 | | 2022-10-03 09:42:00 | 4.0660 | 4.1000 | -0.0340 | | 2022-10-03 09:47:00 | 4.0620 | 4.0500 | 0.0120 | | 2022-10-03 09:48:00 | 4.0620 | NULL | NULL | | 2022-10-03 09:50:00 | 4.0580 | NULL | NULL | | 2022-10-03 09:51:00 | 4.0580 | NULL | NULL | | 2022-10-03 09:52:00 | 4.0560 | 4.0580 | -0.0020 | | 2022-10-03 09:53:00 | 4.0460 | NULL | NULL | | 2022-10-03 09:55:00 | 4.0420 | NULL | NULL | +---------------------+--------+--------+---------+ 20 rows in set (0,00 sec) ``` The 'NULL' is normal because there is not always the previous minute that corresponds (in addition it suits me in this case) But I have questions: 1) In "(hi-(select rlo)) as rdif" why can't I just use 'rlo' (have to add the select)? (Even if you answer the question below, please answer this one anyway) 2) How to avoid double select-from in table? (is that a subquery?) There must be better… What do you suggest? 3) I then consider other operations, in this style, more or less simple but complicated for me in MySQL. (calculations plus column updates..., not necessarily selections to display...) Do I have a better way to simply read/write the table and code these calculations in my app in nodejs (which I master: I'm learning a little MySQL, ok, but I still want to finsh my app…) (How much would run time be?) Thanks !
2022/10/03
[ "https://Stackoverflow.com/questions/73937079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15157921/" ]
Thanks to Barmar and Mihe, I understood LEFT JOIN and INNER JOIN. And I think that INNER JOIN is what I often used without knowing it (without specifying INNER JOIN in the query): -> Me, before: ``` mysql> SELECT t1.dt as rdt, t1.hi as rhi, t2.lo AS rlo, t1.hi - t2.lo AS rdif -> FROM valtest_xpar_dbg_i AS t1, valtest_xpar_dbg_i AS t2 -> where t1.dt >= '2022-10-03 09:20:00' and t2.dt = t1.dt - INTERVAL 10 MINUTE -> limit 10; +---------------------+--------+--------+---------+ | rdt | rhi | rlo | rdif | +---------------------+--------+--------+---------+ | 2022-10-03 09:21:00 | 4.1200 | 3.9900 | 0.1300 | | 2022-10-03 09:24:00 | 4.1080 | 4.0180 | 0.0900 | | 2022-10-03 09:25:00 | 4.1040 | 4.0500 | 0.0540 | | 2022-10-03 09:26:00 | 4.0960 | 4.0800 | 0.0160 | | 2022-10-03 09:31:00 | 4.1020 | 4.1180 | -0.0160 | | 2022-10-03 09:36:00 | 4.0720 | 4.0940 | -0.0220 | | 2022-10-03 09:39:00 | 4.0620 | 4.0940 | -0.0320 | | 2022-10-03 09:42:00 | 4.0660 | 4.1000 | -0.0340 | | 2022-10-03 09:47:00 | 4.0620 | 4.0500 | 0.0120 | | 2022-10-03 09:52:00 | 4.0560 | 4.0580 | -0.0020 | +---------------------+--------+--------+---------+ 10 rows in set (0,00 sec) ``` -> Me, now: ``` mysql> SELECT t1.dt as rdt, t1.hi as rhi, t2.lo AS rlo, t1.hi - t2.lo AS rdif -> FROM valtest_xpar_dbg_i AS t1 -> INNER JOIN valtest_xpar_dbg_i AS t2 ON t2.dt = t1.dt - INTERVAL 10 MINUTE -> where t1.dt >= '2022-10-03 09:20:00' -> limit 10; +---------------------+--------+--------+---------+ | rdt | rhi | rlo | rdif | +---------------------+--------+--------+---------+ | 2022-10-03 09:21:00 | 4.1200 | 3.9900 | 0.1300 | | 2022-10-03 09:24:00 | 4.1080 | 4.0180 | 0.0900 | | 2022-10-03 09:25:00 | 4.1040 | 4.0500 | 0.0540 | | 2022-10-03 09:26:00 | 4.0960 | 4.0800 | 0.0160 | | 2022-10-03 09:31:00 | 4.1020 | 4.1180 | -0.0160 | | 2022-10-03 09:36:00 | 4.0720 | 4.0940 | -0.0220 | | 2022-10-03 09:39:00 | 4.0620 | 4.0940 | -0.0320 | | 2022-10-03 09:42:00 | 4.0660 | 4.1000 | -0.0340 | | 2022-10-03 09:47:00 | 4.0620 | 4.0500 | 0.0120 | | 2022-10-03 09:52:00 | 4.0560 | 4.0580 | -0.0020 | +---------------------+--------+--------+---------+ 10 rows in set (0,00 sec) ``` Same result ! But I suppose 'INNER JOIN' version is better. **-->> Is it realy the same execution in MySQL ? Speed ?** Thanks again !
ad 1) you've got to think of the logical execution order of SQL queries which is roughly: FROM (data source), WHERE (filter), SELECT (projection). That is, the expressions in the SELECT clause are applied to the filtered data specified in the FROM and WHERE clauses. Therefore it makes perfect sense that an expression can't refer directly to another expression in the SELECT clause. But there's an exception: subqueries. They are evaluated on their own, have their own expression list and can contain backward references to column aliases, that is ``` SELECT col AS x, (SELECT x) FORM tbl ``` is allowed, since `x` was declared before it was selected, while ``` SELECT (SELECT x), col AS x FORM tbl ``` will result in an error, because forward references are not supported. Although this is poorly documented, you can find more information on subqueries in [section 13.2.11](https://dev.mysql.com/doc/refman/8.0/en/subqueries.html) of the MySQL 8.0 Reference Manual. ad 2) see the [answer](https://stackoverflow.com/a/73937351/19657183) of user [Barmar](https://stackoverflow.com/users/1491895/barmar). The LEFT JOIN means: give me all record of the left table and join them with the records of the right table based on the ON condition. If there's no matching record in the right table, use NULL values. An INNER JOIN would only return matching records, that is records from the left table which have a matching record in the right table (based on the ON condition). ad 3) Of course, you can calculate in MySQL, too. That's what you already do, e.g. by `t1.dt - INTERVAL 10 MINUTE`. Some people try to do anything in SQL (if possible all kind of things in a single query...) which is something I wouldn't do. Keep it simple.
59,394,539
When estimating the time complexity of a certain algorithm, let's say the following in pseudo code: ``` for (int i=0; i<n; i++) ---> O(n) //comparison? ---> ? //substitution ---> ? for (int i=0; i<n; i++) ---> O(n) //some function which is not recursive ``` In this case the time complexity of these instructions is `O(n)` because we iterate over the input `n`, but how about the comparison and substitution operations are they constant time since they don't depend on `n`? Thanks
2019/12/18
[ "https://Stackoverflow.com/questions/59394539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627565/" ]
First, read [this](http://kddlab.zjgsu.edu.cn:7200/students/lipengcheng/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA%EF%BC%88%E8%8B%B1%E6%96%87%E7%AC%AC%E4%B8%89%E7%89%88%EF%BC%89.pdf) book. Here is good explanation of this topic. 1. Comparsion. For instance, we have two variables **a** and **b**. And when we doing this `a==b`we just take **a** and **b** from the memory and compare them. Let's define "*c*" as cost of memory, and "*t*" as cost of time. In this case we're using *2c* (because we're using two cells of the memory) and *1t* (because there is only one operation with the constant cost), therefore the *1t* - is the constan. Thus the time complexity is constant. 2. Substitution. It's pretty same as the previous operation. We're using two variables and one operation. This operation is same for the any type, therefore the cost of the time of the substitutin is constant. Then complexity is constant too.
> > but how about the comparison and substitution operations are they > constant time since they don't depend on n? > > > **Yes**. Comparison and substitution operations are a constant factor because their execution time doesn't depend on a size of the input. Their execution time takes time but, again, it's independent from the input size. However, the execution time of your `for` loop grows proportionally to the number of items `n` and so its time complexity is `O(n)`. **UPDATE** As @kaya3 correctly pointed out, we assume that we deal with fixed-size data types. If they're not then check an answer from @kaya3.
59,394,539
When estimating the time complexity of a certain algorithm, let's say the following in pseudo code: ``` for (int i=0; i<n; i++) ---> O(n) //comparison? ---> ? //substitution ---> ? for (int i=0; i<n; i++) ---> O(n) //some function which is not recursive ``` In this case the time complexity of these instructions is `O(n)` because we iterate over the input `n`, but how about the comparison and substitution operations are they constant time since they don't depend on `n`? Thanks
2019/12/18
[ "https://Stackoverflow.com/questions/59394539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627565/" ]
Both of the other answers assume you are comparing some sort of fixed-size data type, such as 32-bit integers, doubles, or characters. If you are using operators like `<` in a language such as Java where they can only be used on fixed-size data types, and cannot be overloaded, then that is correct. But your question is not language-specific, and you also did not say you are comparing using such operators. In general, the time complexity of a comparison operation depends on the data type you are comparing. It takes O(1) time to compare 64-bit integers, doubles, or characters, for example. But as a counter-example comparing strings in lexicographic order takes O(min(*k*, *k'*)) time in the worst case, where *k*, *k'* are the lengths of the strings. For example, here is the Java source code for the [`String.compareTo`](http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java) method in OpenJDK 7, which clearly does not take constant time: ```java public int compareTo(String anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; } ``` Therefore when analysing the time complexity of comparison-based sorting algorithms, we often analyse their complexity *in terms of* the number of comparisons and substitutions, rather than the number of basic operations; for example, [selection sort](https://en.wikipedia.org/wiki/Selection_sort) does O(*n*) substitutions and O(*n*²) comparisons, whereas [merge sort](https://en.wikipedia.org/wiki/Merge_sort) does O(*n* log *n*) substitutions and O(*n* log *n*) comparisons.
> > but how about the comparison and substitution operations are they > constant time since they don't depend on n? > > > **Yes**. Comparison and substitution operations are a constant factor because their execution time doesn't depend on a size of the input. Their execution time takes time but, again, it's independent from the input size. However, the execution time of your `for` loop grows proportionally to the number of items `n` and so its time complexity is `O(n)`. **UPDATE** As @kaya3 correctly pointed out, we assume that we deal with fixed-size data types. If they're not then check an answer from @kaya3.
17,365,606
I am using FormView control, and I want to programmatically insert null value in OnItemInserting and OnItemUpdating event, by NewValues dictioanry in FormViewUpdateEventArgs parameter. But if I use ``` protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { e.NewValues["EntityFrameworkEntityPropertyName"] = null; } ``` such modification is ignored, database column is not updated and keeps its old value. EntityFramework entity property is: Type Int32, Nullable True, StoreGeneratedPattern None. If I bind TextBox control directly to property by Bind(), nulls are inserted well. Also if values are different from null, everything works fine. How can I insert null value?
2013/06/28
[ "https://Stackoverflow.com/questions/17365606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831219/" ]
To remove you can simply use: ``` [myTextField removeFromSuperview]; ```
You can use `[myTextField removeFromSuperview];` to get rid of a view.
17,365,606
I am using FormView control, and I want to programmatically insert null value in OnItemInserting and OnItemUpdating event, by NewValues dictioanry in FormViewUpdateEventArgs parameter. But if I use ``` protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { e.NewValues["EntityFrameworkEntityPropertyName"] = null; } ``` such modification is ignored, database column is not updated and keeps its old value. EntityFramework entity property is: Type Int32, Nullable True, StoreGeneratedPattern None. If I bind TextBox control directly to property by Bind(), nulls are inserted well. Also if values are different from null, everything works fine. How can I insert null value?
2013/06/28
[ "https://Stackoverflow.com/questions/17365606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831219/" ]
try this one... > > Blockquote > > > UILabel \*t1; ``` NSArray *arr1=[YourView subviews]; for (UIView *v in arr1) { if([v isKindOfClass:[UILabel class]]) { t1 = (UILabel *)v; if (t1.tag==your_tag) [t1 removeFromSuperview]; } } ``` > > Blockquote > > >
You can use `[myTextField removeFromSuperview];` to get rid of a view.
17,365,606
I am using FormView control, and I want to programmatically insert null value in OnItemInserting and OnItemUpdating event, by NewValues dictioanry in FormViewUpdateEventArgs parameter. But if I use ``` protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { e.NewValues["EntityFrameworkEntityPropertyName"] = null; } ``` such modification is ignored, database column is not updated and keeps its old value. EntityFramework entity property is: Type Int32, Nullable True, StoreGeneratedPattern None. If I bind TextBox control directly to property by Bind(), nulls are inserted well. Also if values are different from null, everything works fine. How can I insert null value?
2013/06/28
[ "https://Stackoverflow.com/questions/17365606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831219/" ]
To remove you can simply use: ``` [myTextField removeFromSuperview]; ```
``` [myTextField removeFromSuperview] ``` See [UIView documentation](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html).
17,365,606
I am using FormView control, and I want to programmatically insert null value in OnItemInserting and OnItemUpdating event, by NewValues dictioanry in FormViewUpdateEventArgs parameter. But if I use ``` protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { e.NewValues["EntityFrameworkEntityPropertyName"] = null; } ``` such modification is ignored, database column is not updated and keeps its old value. EntityFramework entity property is: Type Int32, Nullable True, StoreGeneratedPattern None. If I bind TextBox control directly to property by Bind(), nulls are inserted well. Also if values are different from null, everything works fine. How can I insert null value?
2013/06/28
[ "https://Stackoverflow.com/questions/17365606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831219/" ]
try this one... > > Blockquote > > > UILabel \*t1; ``` NSArray *arr1=[YourView subviews]; for (UIView *v in arr1) { if([v isKindOfClass:[UILabel class]]) { t1 = (UILabel *)v; if (t1.tag==your_tag) [t1 removeFromSuperview]; } } ``` > > Blockquote > > >
``` [myTextField removeFromSuperview] ``` See [UIView documentation](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html).
17,365,606
I am using FormView control, and I want to programmatically insert null value in OnItemInserting and OnItemUpdating event, by NewValues dictioanry in FormViewUpdateEventArgs parameter. But if I use ``` protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { e.NewValues["EntityFrameworkEntityPropertyName"] = null; } ``` such modification is ignored, database column is not updated and keeps its old value. EntityFramework entity property is: Type Int32, Nullable True, StoreGeneratedPattern None. If I bind TextBox control directly to property by Bind(), nulls are inserted well. Also if values are different from null, everything works fine. How can I insert null value?
2013/06/28
[ "https://Stackoverflow.com/questions/17365606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831219/" ]
To remove you can simply use: ``` [myTextField removeFromSuperview]; ```
All controls inherited from UIView. So you can remove all the controls which added on UIView using like this. By clicking the button action write like this ``` for(UIView *control in [self.view subviews]) { [control removeFromSuperview]; } ```
17,365,606
I am using FormView control, and I want to programmatically insert null value in OnItemInserting and OnItemUpdating event, by NewValues dictioanry in FormViewUpdateEventArgs parameter. But if I use ``` protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { e.NewValues["EntityFrameworkEntityPropertyName"] = null; } ``` such modification is ignored, database column is not updated and keeps its old value. EntityFramework entity property is: Type Int32, Nullable True, StoreGeneratedPattern None. If I bind TextBox control directly to property by Bind(), nulls are inserted well. Also if values are different from null, everything works fine. How can I insert null value?
2013/06/28
[ "https://Stackoverflow.com/questions/17365606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831219/" ]
try this one... > > Blockquote > > > UILabel \*t1; ``` NSArray *arr1=[YourView subviews]; for (UIView *v in arr1) { if([v isKindOfClass:[UILabel class]]) { t1 = (UILabel *)v; if (t1.tag==your_tag) [t1 removeFromSuperview]; } } ``` > > Blockquote > > >
All controls inherited from UIView. So you can remove all the controls which added on UIView using like this. By clicking the button action write like this ``` for(UIView *control in [self.view subviews]) { [control removeFromSuperview]; } ```
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Windows RDP uses the executable mstsc.exe located in c:\windows\system32 Simply right click on this file, and go to properties, then click the version tab. hope this helps.
or you could also click Start > Run > mstsc and when you see the Remote Desktop Connection window appear, click the top left hand corner "computer" icon and select "About".
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Or you could Right click on the window and select About ![enter image description here](https://i.stack.imgur.com/CvjyF.png)
Windows RDP uses the executable mstsc.exe located in c:\windows\system32 Simply right click on this file, and go to properties, then click the version tab. hope this helps.
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Windows RDP uses the executable mstsc.exe located in c:\windows\system32 Simply right click on this file, and go to properties, then click the version tab. hope this helps.
Here's a PowerShell query you can use: ``` wmic datafile where name="C:\\windows\\system32\\mstsc.exe" get manufacturer, name, version ```
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Windows RDP uses the executable mstsc.exe located in c:\windows\system32 Simply right click on this file, and go to properties, then click the version tab. hope this helps.
There can be maybe better way with PowerShell. First one need complete table of MSTSC build numbers and just compare to output of: ``` (Get-Item C:\Windows\System32\mstsc.exe).VersionInfo.FileVersion ``` And the second one is to read CLSID of registered components which contain also RDP binaries, like that: ``` $Current = 0 $GUID = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name $GUIDNum = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name | Measure While($Current -ne $GUIDNum.Count) { $Path = $GUID[$Current] | Select -ExpandProperty Name $GUIDName = ((get-itemproperty -literalpath "Registry::$Path").'(default)') If ($GUIDName -like 'Microsoft RDP Client Control (redistributable) - version*') { Write-Host $GUIDName } $Current++ } ```
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Or you could Right click on the window and select About ![enter image description here](https://i.stack.imgur.com/CvjyF.png)
or you could also click Start > Run > mstsc and when you see the Remote Desktop Connection window appear, click the top left hand corner "computer" icon and select "About".
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
or you could also click Start > Run > mstsc and when you see the Remote Desktop Connection window appear, click the top left hand corner "computer" icon and select "About".
There can be maybe better way with PowerShell. First one need complete table of MSTSC build numbers and just compare to output of: ``` (Get-Item C:\Windows\System32\mstsc.exe).VersionInfo.FileVersion ``` And the second one is to read CLSID of registered components which contain also RDP binaries, like that: ``` $Current = 0 $GUID = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name $GUIDNum = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name | Measure While($Current -ne $GUIDNum.Count) { $Path = $GUID[$Current] | Select -ExpandProperty Name $GUIDName = ((get-itemproperty -literalpath "Registry::$Path").'(default)') If ($GUIDName -like 'Microsoft RDP Client Control (redistributable) - version*') { Write-Host $GUIDName } $Current++ } ```
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Or you could Right click on the window and select About ![enter image description here](https://i.stack.imgur.com/CvjyF.png)
Here's a PowerShell query you can use: ``` wmic datafile where name="C:\\windows\\system32\\mstsc.exe" get manufacturer, name, version ```
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Or you could Right click on the window and select About ![enter image description here](https://i.stack.imgur.com/CvjyF.png)
There can be maybe better way with PowerShell. First one need complete table of MSTSC build numbers and just compare to output of: ``` (Get-Item C:\Windows\System32\mstsc.exe).VersionInfo.FileVersion ``` And the second one is to read CLSID of registered components which contain also RDP binaries, like that: ``` $Current = 0 $GUID = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name $GUIDNum = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name | Measure While($Current -ne $GUIDNum.Count) { $Path = $GUID[$Current] | Select -ExpandProperty Name $GUIDName = ((get-itemproperty -literalpath "Registry::$Path").'(default)') If ($GUIDName -like 'Microsoft RDP Client Control (redistributable) - version*') { Write-Host $GUIDName } $Current++ } ```
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Here's a PowerShell query you can use: ``` wmic datafile where name="C:\\windows\\system32\\mstsc.exe" get manufacturer, name, version ```
There can be maybe better way with PowerShell. First one need complete table of MSTSC build numbers and just compare to output of: ``` (Get-Item C:\Windows\System32\mstsc.exe).VersionInfo.FileVersion ``` And the second one is to read CLSID of registered components which contain also RDP binaries, like that: ``` $Current = 0 $GUID = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name $GUIDNum = Get-ChildItem -LiteralPath "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID" | Select Name | Measure While($Current -ne $GUIDNum.Count) { $Path = $GUID[$Current] | Select -ExpandProperty Name $GUIDName = ((get-itemproperty -literalpath "Registry::$Path").'(default)') If ($GUIDName -like 'Microsoft RDP Client Control (redistributable) - version*') { Write-Host $GUIDName } $Current++ } ```
21,971,036
I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database : ``` { "env": { "MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx" } } ``` with the command : ``` mrt deploy myapp.meteor.com --settings settings.json ``` It doesn't even work, My app continue to connect the local database provided with the Meteor.app ! My MONGO\_URL env variable didnt changed. Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ? I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ?
2014/02/23
[ "https://Stackoverflow.com/questions/21971036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2917448/" ]
You are not able to use your own `MONGO_URL` with Meteor deploy hosting. Meteor deploy hosting takes care of the Email with Mailgun (if you use it), and provides mongodb for all apps deployed there. It is possible to change the `MAIL_URL`, but it is not possible to use a different mongodb. You can try, though im not sure it will work: Place this in your server side code somewhere ``` process.env.MONGO_URL = '..'; ```
Regarded to the Unoficial Meteor.js FAQ, thats not possible to do it easily, that might be tricky. So i signed up for a modulus Account, with MongoHQ Database. It works right now.
21,971,036
I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database : ``` { "env": { "MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx" } } ``` with the command : ``` mrt deploy myapp.meteor.com --settings settings.json ``` It doesn't even work, My app continue to connect the local database provided with the Meteor.app ! My MONGO\_URL env variable didnt changed. Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ? I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ?
2014/02/23
[ "https://Stackoverflow.com/questions/21971036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2917448/" ]
You are not able to use your own `MONGO_URL` with Meteor deploy hosting. Meteor deploy hosting takes care of the Email with Mailgun (if you use it), and provides mongodb for all apps deployed there. It is possible to change the `MAIL_URL`, but it is not possible to use a different mongodb. You can try, though im not sure it will work: Place this in your server side code somewhere ``` process.env.MONGO_URL = '..'; ```
having a settings.json file is not enough you need to run with ``` meteor --settings settings.json ``` which is you cant do with meteor.com deploy.
21,971,036
I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database : ``` { "env": { "MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx" } } ``` with the command : ``` mrt deploy myapp.meteor.com --settings settings.json ``` It doesn't even work, My app continue to connect the local database provided with the Meteor.app ! My MONGO\_URL env variable didnt changed. Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ? I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ?
2014/02/23
[ "https://Stackoverflow.com/questions/21971036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2917448/" ]
You are not able to use your own `MONGO_URL` with Meteor deploy hosting. Meteor deploy hosting takes care of the Email with Mailgun (if you use it), and provides mongodb for all apps deployed there. It is possible to change the `MAIL_URL`, but it is not possible to use a different mongodb. You can try, though im not sure it will work: Place this in your server side code somewhere ``` process.env.MONGO_URL = '..'; ```
The application-configuration package (built in meteor package) contains the code to set mongo\_url. See my answer here <https://stackoverflow.com/a/23485319/2391620>
21,971,036
I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database : ``` { "env": { "MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx" } } ``` with the command : ``` mrt deploy myapp.meteor.com --settings settings.json ``` It doesn't even work, My app continue to connect the local database provided with the Meteor.app ! My MONGO\_URL env variable didnt changed. Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ? I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ?
2014/02/23
[ "https://Stackoverflow.com/questions/21971036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2917448/" ]
The application-configuration package (built in meteor package) contains the code to set mongo\_url. See my answer here <https://stackoverflow.com/a/23485319/2391620>
Regarded to the Unoficial Meteor.js FAQ, thats not possible to do it easily, that might be tricky. So i signed up for a modulus Account, with MongoHQ Database. It works right now.