text
stringlengths
15
59.8k
meta
dict
Q: Java: Array with loop(matches) I need to find the first match in this task. Probably i am just missing something. As you can see, i found the last match.I am not copied the first half of the code. Thank you. for (int i = 0; i <= n - 1; i++) { if (iv[i] == a) { hely = i; } } if (hely == -1) { System.out.println("text"); } else { System.out.println("text " + a + " text " + (hely + 1) + "text"); } A: break the loop when you find first match. for (int i = 0; i <= n - 1; i++) { if (iv[i] == a) { hely = i; break; } } A: You need to exit the for loop after finding the first match: for (int i = 0; i <= n - 1; i++) { if (iv[i] == a) { hely = i; break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/35957900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to stop/invalidate NStimer I am using [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(update) userInfo:nil repeats:YES]; I want to stop calling this timer one. viewDidDisappear How can i do that? invalidate? A: Try this viewController .h NSTimer *timer; viewcontroller.m timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(pollTime) userInfo:nil repeats:YES]; - (void) viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [timer invalidate]; } A: Declare NSTimer *myTimer in .h file. Assign instance as tom said like this myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(update) userInfo:nil repeats:YES]; Stop and Invalidate using this - (void) viewDidDisappear:(BOOL)animated { [myTimer invalidate]; myTimer = nil; } A: Yes, you would use the - (void)invalidate instance method of NSTimer. Of course, to do that, you would have to save the NSTimer instance returned from [NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:] into an ivar or property of your view controller, so you can access it in viewDidDisappear. A: invalidate Method of NSTimer is use for stop timer - (void) viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.timer invalidate]; self.timer = nil; } If you are not ARC then don't forget [self.timer release]; A: For stopping or invalidating NSTimer first you have to create instance for NSTimer in Globally. Timer=[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(update) userInfo:nil repeats:YES]; after that try like this, if (Timer != nil) { [Timer invalidate]; Timer = nil; }
{ "language": "en", "url": "https://stackoverflow.com/questions/15170518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Spring Security Login Redirects to /j_spring_security_check Without Authenticating I am currently trying to get a simple Spring security login to work. I am using mongodb and can get users to be saved to the database (can query them from mongo shell). However, when I enter the credentials into the login form, I get redirected to /j_spring_security_check and I'm not sure if the authentication is even being attempted. Here's the console output after I attempt to login: 11:19:10.625 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 11:19:10.625 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT 11:19:10.625 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@54c21095. A new one will be created. 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter' 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 3 of 9 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 4 of 9 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.DefaultSavedRequest - pathInfo: both null (property equals) 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.DefaultSavedRequest - queryString: both null (property equals) 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.DefaultSavedRequest - requestURI: arg1=/api/accounts/admin; arg2=/api/accounts/j_spring_security_check (property not equals) 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.HttpSessionRequestCache - saved request doesn't match 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 5 of 9 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 6 of 9 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@90572420: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@255f8: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: 897C850D53E8B5AEC983E6060077E3F0; Granted Authorities: ROLE_ANONYMOUS' 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 7 of 9 in additional filter chain; firing Filter: 'SessionManagementFilter' 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 8 of 9 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 9 of 9 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/login' 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/logout' 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/accessdenied' 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/admin' 11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Public object - authentication not attempted 11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check reached end of additional filter chain; proceeding with original chain 11:19:10.626 [tomcat-http--7] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing POST request for [/hdft-rest-api/api/accounts/j_spring_security_check] 11:19:10.627 [tomcat-http--7] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /api/accounts/j_spring_security_check 11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/api/accounts/j_spring_security_check] 11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Matching patterns for request [/api/accounts/j_spring_security_check] are [/**] 11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - URI Template variables for request [/api/accounts/j_spring_security_check] are {} 11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Mapping [/api/accounts/j_spring_security_check] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler@29ab0eef] and 1 interceptor 11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 11:19:10.641 [tomcat-http--7] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'appServlet': assuming HandlerAdapter completed request handling 11:19:10.641 [tomcat-http--7] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request 11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally 11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed I've attached the relevant configuration files: Here's my spring-security.xml: <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <global-method-security pre-post-annotations="enabled" secured-annotations="enabled" /> <http auto-config="false" use-expressions="true" access-denied-page="/api/accounts/accessdenied"> <intercept-url pattern="/api/accounts/login" access="permitAll" /> <intercept-url pattern="/api/accounts/logout" access="permitAll" /> <intercept-url pattern="/api/accounts/accessdenied" access="permitAll" /> <intercept-url pattern="/api/accounts/admin" access="hasRole('ROLE_ADMIN')" /> <form-login login-page="/api/accounts/login" default-target-url="/api/accounts/welcome" authentication-failure-url="/api/accounts/accessdenied" /> <logout logout-success-url="/api/accounts/logout" /> </http> <beans:bean id="mongoUserDetailsService" class="com.services.impl.MongoUserDetailsService" /> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="mongoUserDetailsService"> <password-encoder hash="plaintext" /> </authentication-provider> </authentication-manager> MongoUserDetailsService.java: @Component public class MongoUserDetailsService implements UserDetailsService { @Resource private UserRepository urepo; private org.springframework.security.core.userdetails.User userdetails; public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; com.DTOs.users.User user = urepo.findByUsername(username); userdetails = new User(user.getUsername(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole())); return userdetails; } public List<GrantedAuthority> getAuthorities(Integer role) { List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); if (role.intValue() == 1) { authList.add(new SimpleGrantedAuthority("ROLE_ADMIN")); } else if (role.intValue() == 2) { authList.add(new SimpleGrantedAuthority("ROLE_USER")); } System.out.println(authList); return authList; } User.java POJO: @Document public class User { @Id private String id; private String firstName; private String lastName; private String username; private int role; private String password; public User(String id, String firstName, String lastName, String username, int role, String password) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.username = username; this.role = role; this.password = password } // setter and getter methods... And finally my login.jsp: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" % <html> <body> <h1 id="banner">Spring 3 security MongoDB Demo</h1> <form name="f" action="j_spring_security_check" method="post"> <label for="username">Username:</label> <input id="username" name="j_username"></br> <label for="password">Password:</label> <input id="password" name="j_password" type='password'></br> <input name="submit" type="submit" value="Login"/> </form> </body> Please let me know if you see where I'm going wrong or need additional information. It would be much appreciated. Edit: I tried the suggestion in the comment below. It is attempting authentication, but the authentication is failing. I checked my mongodb and I'm definitely entering the credentials correctly so I'm not sure what I'm doing wrong. Here is the new error log: 11:07:28.794 [tomcat-http--12] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@7f10f850. A new one will be created. 11:07:28.794 [tomcat-http--12] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter' 11:07:28.794 [tomcat-http--12] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 3 of 9 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Request is to process authentication 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder to contain null Authentication 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@52e16021 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.SimpleUrlAuthenticationFailureHandler - Redirecting to /api/accounts/accessdenied 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.web.DefaultRedirectStrategy - Redirecting to '/hdft-rest-api/api/accounts/accessdenied' 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed 11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT 11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@7f10f850. A new one will be created. 11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter' 11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 3 of 9 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 4 of 9 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.DefaultSavedRequest - pathInfo: both null (property equals) 11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.DefaultSavedRequest - queryString: both null (property equals) 11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.DefaultSavedRequest - requestURI: arg1=/hdft-rest-api/api/accounts/admin; arg2=/hdft-rest-api/api/accounts/accessdenied (property not equals) 11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.HttpSessionRequestCache - saved request doesn't match 11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 5 of 9 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 6 of 9 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@6faa6108: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff10d0: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: 7A0F91CF4FD4ADA0A192E2EDE53AADB0; Granted Authorities: ROLE_ANONYMOUS' 11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 7 of 9 in additional filter chain; firing Filter: 'SessionManagementFilter' 11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 8 of 9 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 9 of 9 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/accessdenied'; against '/api/accounts/login' 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/accessdenied'; against '/api/accounts/logout' 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/accessdenied'; against '/api/accounts/accessdenied' 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /api/accounts/accessdenied; Attributes: [permitAll] 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@6faa6108: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff10d0: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: 7A0F91CF4FD4ADA0A192E2EDE53AADB0; Granted Authorities: ROLE_ANONYMOUS 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7de6385e, returned: 1 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful 11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object 11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied reached end of additional filter chain; proceeding with original chain 11:07:28.797 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing GET request for [/hdft-rest-api/api/accounts/accessdenied] 11:07:28.797 [tomcat-http--13] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /api/accounts/accessdenied 11:07:28.797 [tomcat-http--13] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public java.lang.String com.schneiderlab.hdft_mobile.rest_api.UserController.loginerror(org.springframework.ui.ModelMap)] 11:07:28.797 [tomcat-http--13] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userController' 11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - Last-Modified value for [/hdft-rest-api/api/accounts/accessdenied] is: -1 11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'denied'; URL [/WEB-INF/views/denied.jsp]] in DispatcherServlet with name 'appServlet' 11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.view.JstlView - Added model object 'error' of type [java.lang.String] to request in view with name 'denied' 11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/denied.jsp] in InternalResourceView 'denied' 11:07:28.799 [tomcat-http--13] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 11:07:28.799 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request 11:07:28.799 [tomcat-http--13] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally 11:07:28.799 [tomcat-http--13] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed A: You're POSTing your credentials to "/api/accounts/j_spring_security_check", while the monitored URL is just "/j_spring_security_check". You should construct the action URL in the form using: <c:url value="/j_spring_security_check"/> So the result would be: <form name="f" action="<c:url value="/j_spring_security_check"/>" method="post"> Update after changed question... Your authentication fails throwing Exception or returning null. The result of call to your UserDetailsProvider are checked like this (inside DaoAuthenticationProvider) with the result of throwing AuthenticationServiceException: try { loadedUser = this.getUserDetailsService().loadUserByUsername(username); } catch (UsernameNotFoundException notFound) { throw notFound; } catch (Exception repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (loadedUser == null) { throw new AuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } You should: * *improve your code to include some logging *start debugger and go through your code to see what fails or returns null *or implement a custom AuthenticationFailureHandler which will print complete content of the exception it receives as a parameter and plug it instead of the default one
{ "language": "en", "url": "https://stackoverflow.com/questions/24535164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server 2008 The transaction ended in the trigger. The batch has been aborted I got this stored procedure: CREATE PROCEDURE getManagerSalary ( @Emp_id INT, @ManagerSalary MONEY OUTPUT ) AS SELECT @ManagerSalary = es.Salary FROM [outdoorparadise].[dbo].[Employee] AS e INNER JOIN [outdoorparadise].[dbo].[Employee] AS m ON e.Manager_id = m.Emp_id INNER JOIN [outdoorparadise].[dbo].[Employee_staff] AS es ON e.Manager_id = es.Emp_staff_code WHERE e.Emp_id = @Emp_id; I got this trigger: CREATE TRIGGER checkSalary ON Employee_staff AFTER UPDATE AS DECLARE @Emp_id INT, @NewSalary MONEY, @ManagerSalary MONEY; SELECT @NewSalary = Salary FROM inserted; SELECT @Emp_id = Emp_staff_code FROM inserted; EXEC getManagerSalary @Emp_id = @Emp_id, @ManagerSalary = @ManagerSalary OUTPUT; IF @NewSalary > @ManagerSalary BEGIN RAISERROR 60000 'Salary cannot be higher than the salary of the manager!' ROLLBACK TRANSACTION; END ELSE COMMIT TRANSACTION; When I update salary to a value higher than the manager's salary I get the raise error + this error: The transaction ended in the trigger. The batch has been aborted. When I try to update the salary to a value lower than the manager's salary I still get this: The transaction ended in the trigger. The batch has been aborted. Could someone please tell me how can I fix this problem? I searched, but couldn't find anything. Thanks, Ryuken PS: This is my first post maybe I didn't paste code the correct way so I'm sorry. A: Ditch the trigger. Replace it with a check constraint and a scalar function. CREATE FUNCTION dbo.GetManagerSalary(@Emp_id int) RETURNS money AS BEGIN RETURN SELECT es.Salary FROM [dbo].[Employee] e JOIN [dbo].[Employee] m ON m.Emp_id = e.Manager_id JOIN [dbo].[Employee_staff] es ON es.Emp_staff_code = e.Manager_id WHERE e.Emp_id = @Emp_id; END GO ALTER TABLE Employee_staff ADD CONSTRAINT CK_Salary CHECK (ISNULL([Salary], 0) <= ISNULL(dbo.GetManagerSalary([Salary]), 1e9)))
{ "language": "en", "url": "https://stackoverflow.com/questions/6360618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java AES decryption error, encryption is working fine I have a question about using Decrypt in AES. I wrote the same program that encrypts the text. Here is my Decrypt class. (I use a 16 byte key). public static byte[] decryptAES(String message) throws Exception { String secretKey = "JohnIsAwesome!1!"; SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(message.getBytes()); } Here is my main. The encrypt is working perfectly. public static void main (String[] args) throws Exception { String text = "MySuperSecretPassword!"; //Ecrypt the Text, then print it out in an array String encryptText = Arrays.toString(encryptAES(text)); System.out.println("Encrypted Message"+ encryptText); //Decrypt the Text, then print it out in an array String decryptText = Arrays.toString(decryptAES(text1)); System.out.println("Decrypted Message"+ decryptText); } Encrypt output: Encrypted Message[16, 69, 84, 118, 68, -36, -67, 125, -86, -106, -4, 24, -59, -77, -41, -32, -37, 104, -44, -42, 112, 87, 87, 101, 28, 99, 60, -27, 34, -88, -17, -114] If anyone has any ideas why the decryption would not work, It would be greatly appreciated. I've been banging my head against the wall on this one. Thank you Sorry, forgot to add my Encrypt class here as well. public static byte[] encryptAES(String message) throws Exception { String secretKey = "JohnIsAwesome!1!"; SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(message.getBytes()); } A: Arrays.toString(byte[] a) "Returns a string representation of the contents of the specified array." It does not convert a byte array to a String. Instead try using: new String(decryptAES(text1), "UTF-8");
{ "language": "en", "url": "https://stackoverflow.com/questions/19286076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mocha: how do I use the assert.reject in typescript with promise in params? how do I use the assert.reject in typescript with promise in params? here is my code: import { assert } from "chai"; import { suite, test, timeout, slow } from "mocha-typescript"; import "mocha"; import { car } from "./Car"; // module that run your function let carVIN: string = "1234567890"; // this car has four wheel; @suit export class CarTest() { @test public async oneWheelsCar() { const wheels = await car.findWheelsByCarId(carVIN); assert.isRejected(wheels, "Expected to have four wheels"); } } My question is how do I make my carId function to run like promise because my problem is assert.isRejected run early before the carId error return back. I tried this below: assert.throws(carId, Error, "Expected to be error "); and I also try to use try-catch to wrap my function: import { assert } from "chai"; import { suite, test, timeout, slow } from "mocha-typescript"; import "mocha"; import { car } from "./Car"; // module that run your function let carVIN: string = "1234567890"; // this car has four wheel; @suit export class CarTest() { @test public async oneWheelsCar() { try { const wheels = await car.findWheelsByCarId(carVIN); assert.isNotString(wheels, "Expected to be error but return four wheels"); } catch (error) { assert.throws(error, Error, "Expected to be error "); } } } I had tried to use chai-as-promise, but the example is not that clear in the their github repo. Visit https://github.com/domenic/chai-as-promised#readme Source: https://www.npmjs.com/package/chai-as-promised A: Problem is await. await resolves promise to actual value or throws exception (simplified view). So, after this line: const wheels = await car.findWheelsByCarId(carVIN); wheels is not a promise, but actual wheel (or whatever). Change it to: const wheelsPromise = car.findWheelsByCarId(carVIN); // no await And then this: assert.isRejected(wheelsPromise, "Expected to have four wheels"); Should work as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/56084545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sorting an ObservableCollection after editing a property of an item I'm trying to bind an ObservableCollection<T> to a DataGrid in WPF. Below the DataGrid, there are fields to edit the currently selected item from the DataGridlike so: So the generic T of the ObservableCollection<T> has the following properties: - Title (Überschrift) - Description (Beschreibung) - Path (Pfad) and it also has a property Reihenfolge which means Order. With the yellow arrows, I want to be able to modify the order of the entries. Unfortunately, the ObservableCollection doesn't have an OrderBy-method... I've tried the following: In XAML I have defined a CollectionViewSource like this: <CollectionViewSource Source="{Binding Bilder}" x:Key="Pictures"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="Reihenfolge" /> </CollectionViewSource.SortDescriptions> </CollectionViewSource> And I have binded the DataGrid to this CollectionViewSource <DataGrid Grid.Column="0" Grid.Row="1" Name="PictureDataGrid" ItemsSource="{Binding Source={StaticResource Pictures}}" AutoGenerateColumns="False" IsReadOnly="True" CanUserAddRows="false" SelectedItem="{Binding SelectedBild}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> ... In the ViewModel, I have these properties: public ObservableCollection<BildNotifiableModel> Bilder { get; set; } public BildNotifiableModel SelectedBild { get; set; } and two methods which are called with DelegateCommands that update the order private void MoveSeiteUp() { const int smallestReihenfolge = 1; if (this.SelectedBild.Reihenfolge > smallestReihenfolge) { var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge - 1); this.SelectedBild.Reihenfolge--; bildToSwapReihenfolgeWith.Reihenfolge++; RaisePropertyChanged(nameof(this.Bilder)); } } private void MoveSeiteDown() { if (this.SelectedBild.Reihenfolge < MaxAllowedImages) { var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge + 1); this.SelectedBild.Reihenfolge++; bildToSwapReihenfolgeWith.Reihenfolge--; RaisePropertyChanged(nameof(this.Bilder)); } } The order gets updated correctly, but unfortunately, the view doesn't reflect the changes... only after closing and reopening the view, the entries in the DataGrid are in the correct order. * *What am I doing wrong here? *How can I make the DataGrid update, when changing the order? Thanks in advance A: I think the problem is that the CollectionView doesn't listen for the PropertyChanged-Events from its elements and also RaisePropertyChanged(nameof(this.Bilder)); dosen't work because the CollectionView is not really changed. I would recomend to create the CollectionView in code via CollectionViewSource.GetDefaultView(list). So you can control the CollectionView from your model and call ICollectionView.Refresh if needed. A: In your Methods, create a new Collection and add it to "Bilder". Just raising the PropertyChanged will execute an evaluation for referential equality. If it is the same - which it will be, if you just move items inside around - it will not update the DataGrid. If you are not using the ObservableCollections attributes, like automatically updates, when items are added or removed, you might also change it to a "normal" List. private void MoveSeiteUp() { const int smallestReihenfolge = 1; if (this.SelectedBild.Reihenfolge > smallestReihenfolge) { var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge - 1); this.SelectedBild.Reihenfolge--; bildToSwapReihenfolgeWith.Reihenfolge++; this.Bilder = new ObservableCollection<BildNotifiableModel> (this.Bilder); RaisePropertyChanged(nameof(this.Bilder)); } } private void MoveSeiteDown() { if (this.SelectedBild.Reihenfolge < MaxAllowedImages) { var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge + 1); this.SelectedBild.Reihenfolge++; bildToSwapReihenfolgeWith.Reihenfolge--; this.Bilder = new ObservableCollection<BildNotifiableModel> (this.Bilder); RaisePropertyChanged(nameof(this.Bilder)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/52423445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When does a double become NaN? I am trying to understand which circumstances can cause a double to become NaN. For instance, 0/0 is nan. This is also stated in the official Documentation. https://learn.microsoft.com/en-us/dotnet/api/system.double.nan?view=net-6.0 However, my debug code indicates that the division is not by 0: public class StandardDeviation { public StandardDeviation() { Clear(); } private double M { get; set; } private double S { get; set; } private uint Iteration { get; set; } public double Value { get { return Math.Sqrt(S / (Iteration - 2)); } } public void AddValue(double value) { if (double.IsNaN(value)) { throw new ArgumentException("value IS nan!"); } double tmpM = M; M += (value - tmpM) / Iteration; S += (value - tmpM) * (value - M); Iteration++; if (double.IsNaN(M)) { Console.WriteLine($"\nNAN EXCEPTION!!! divide by: {Iteration}"); Console.WriteLine($"\nNAN EXCEPTION!!! tmpM: {tmpM}"); throw new ArgumentException("m IS nan!"); } } public void Clear() { M = 0.0; S = 0.0; Iteration = 1; } } console message: NAN EXCEPTION!!! divide by: 3 NAN EXCEPTION!!! tmpM: ∞ The issue primairly seems to be prevalent in release configuration, which makes it hard to debug. Whenever the exception is thrown, Iteration = 3.
{ "language": "en", "url": "https://stackoverflow.com/questions/73662582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reduce, reduceByKey, reduceGroups in Spark or Flink reduce: function takes accumulated value and next value to find some aggregation. reduceByKey: is also the same operation with specified key. reduceGroups: is apply specified operation to the grouped data. I don't know how memory managed for these operations. For example, how data is taken while using reduce function(e.g all data loaded to the memory?)? I want to know how data is managed for reduce operations. I also want to know what is the difference between these operations according to the data management. A: Reduce is one of the cheapest operations in Spark,since that the only thing it does is actually grouping similar data to the same node.The only cost of a reduce operation is the reading of the tuple and a decision of where it should be grouped. This means that the simple reduce,in contrast to the reduceByKey or reduceGroups is more expensive because Spark does not know how to make the grouping and searches for correlations among tuples. Reduce can also ignore a tuple if it does not meet any requirement.
{ "language": "en", "url": "https://stackoverflow.com/questions/58154979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error making/compiling objective C file Today I had my first lesson in Objective_C, it was about how to create "HELLO WORLD". After I downloaded the compiler and wrote the program I had to run it through the "shell" ,as stated in the tutorial, using the command "make" but i receive "No target specified and no makefile found. stop" error To note, I program objectivec under windows OS main.m Code: // #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@"***Sweet tutos***\n"); NSLog(@"***Hello World!***\n");//This will output Hello World! [pool release]; return 0; } GNU makfile: # This script was developed for SweetTutos Tutorials # www.sweettutos.wordpress.com # include $(GNUSTEP_MAKEFILES)/common.make # make a simple program in Objective-C, call it SweetTutos TOOL_NAME = SweetTutos # The implementation Objective-C file which is going to be compiled SweetTutos_OBJC_FILES = main.m # Header files of your project #SweetTutos_HEADER_FILES = xxx.h //here goes all header files (.h). For the moment, on n'en a pas. # Define compilation flags ADDITIONAL_CPPFLAGS = -Wall -Wno-import # Include rules for creating a command line tool for Objective-C include $(GNUSTEP_MAKEFILES)/tool.make A: "no makefile found" usually means you have no file named literally GNUmakefile, makefile or Makefile in the current directory (or the directory pointed at if you use -C). In the Makefile you need to specify at least one rule so that make can do something. The first rule in the file (sequentially, not chronologically) becomes the default rule, so you don't actually have to specify a target like the error message indicates.
{ "language": "en", "url": "https://stackoverflow.com/questions/23462065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Putting Submit button at the bottom of the form I want the submit button to be at the bottom of the form. I have tried using <div>, <div float="left">, <div float="right">, <br> and <span>. So far the only solution I have come up with is to repeat <br> multiple times which is a messy solution and one that is only compatible on laptops the same size as mine. <form method="post" action=""> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div float="left"> {# Include the visible fields #} {% for field in form.visible_fields %} <br class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} </br> {{ field }} {% endfor %} </div> <div float="right"><input type="submit" value="Submit"></div> </form> Update I tried Gumbos suggestion (CSS How to place a submit button on a new line?). But there is something about the map which is making the submit button act strangely. For testing purposes I created a submit button after every field. Gumbos suggestion worked fine for text boxes and list boxes. But not maps. {% extends "blog/base.html" %} {% block content %} {% load crispy_forms_tags %} <html> <head> <style> input[type=submit] {display: block} </style> {{ form.media }} </head> <body> <form method="post" action=""> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {# Include the visible fields #} {% for field in form.visible_fields %} <br class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} </br> {{ field }} <input type="submit" value="Submit"> {% endfor %} </form> </body> </html> {% endblock content %} A: I think you need to remove the float and change br into div <form method="post" action=""> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div> {# Include the visible fields #} {% for field in form.visible_fields %} <div className="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} </div> {{ field }} {% endfor %} </div> <div><input type="submit" value="Submit"></div> </form> A: Check out this post Overwrite float:left property in span for the answer. With Bens help I was able to overwrite some of the default CSS.
{ "language": "en", "url": "https://stackoverflow.com/questions/62354598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: timestamp in milliseconds and date range - elasticsearch query string I have a timstamp in milliseconds, like 1645825932144 I'd like to make a date range query with elastic search query string for being able to get all records whom timestamp is in the last 24h: timestamp:[now-24h TO now] This does not work as timestamp is in milliseconds and now produces strings like 2001-01-01 13:00:00 Is it possible to achieve this with a cast or something? I read about range queries and date math, but did not find anything. A: It's easy to compute the timestamp in milliseconds for now and now-24h so why not do it in your application logic and build the query out of those values? For instance (in JS), const now = new Date().getTime(); const now24h = now - 86400000; const query = `timestamp:[${now24h} TO ${now}]`; query would contain the following value: timestamp:[1647785319578 TO 1647871719578] UPDATE: PS: I might have misunderstood the initial need, but I'm leaving the above answer as it might help others. What you need to do in your case is to change your mapping so that your date field accepts both formats (normal date and timestamp), like this: PUT your-index/_mapping { "properties": { "timestamp": { "type": "date", "format": "date_optional_time||epoch_millis" } } } Then you'll be able to query like this by mix and matching timestamps and date math: GET test/_search?q=timestamp:[now-24h TO 1645825932144] and also like this: GET test/_search?q=timestamp:[1645825932144 TO now]
{ "language": "en", "url": "https://stackoverflow.com/questions/71500880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to integrate firebase/angularfire with Nx I am try to use firebase (angularfire) with Angular/Nx. I found the plugin @nxtend/firebase. https://nxtend.dev/docs/firebase/getting-started/ When trying to add it via ng add @nxtend/firebase I get the following error: An unhandled exception occurred: Schematic "ng-add" not found in collection "@nxtend/firebase". The next command gives another error: nx generate @nxtend/firebase:init Error: Unable to resolve @nxtend/firebase:init. Cannot find generator 'init' in ....\node_modules@nxtend\firebase\collection.json. I am using @nrwl/workspace": "12.9.0" - and Angular 12.x Now my Questions: * *How to fix that? *Can it be that @nxtend/firebase": "^11.1.2" ist not compatible with Angular 12.x? And most important: 3. Ay suggestions how to integrate firebase/angularfire with Nx? Because unfortunatelly this seems to be a complicated task... A: I already successfully setup nx + angular + firebase. (ps. with only one app in nx monorepo) details and pictures can be found here: https://blog-host-d6b29.web.app/2022/11/27/nx-angular-fire.html I suggest you also try to setup a new nx + angular workspace, walk through my steps and see how it works. -- to work with angular & firebase, I suggest using The official Angular library for Firebase "@angular/fire". https://github.com/angular/angularfire
{ "language": "en", "url": "https://stackoverflow.com/questions/69172110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: pyspark -- an error appears only in IPython, but not in vanila python If I start pyspark by typing /usr/bin/pyspark in the console, the following sample code runs without any error. However, if I use it with IPython, either by invoking $IPYTHON_OPTS="notebook" /usr/bin/pyspark # notebook or by $IPYTHON=1 /usr/bin/pyspark then an exception is raised. This is the code: from pyspark import SparkContext,SparkConf from pyspark import SQLContext from pyspark.sql.types import * # sc is a SparkContex object created when pyspark is invoked sqc = SQLContext(sc) And this is the error message: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-1-f0bbbc9cdb50> in <module>() 3 from pyspark.sql.types import * 4 # sc is a SparkContex object created when pyspark is invoked ----> 5 sqc = SQLContext(sc) /opt/cloudera/parcels/CDH-5.4.2-1.cdh5.4.2.p0.2/lib/spark/python/pyspark/sql/context.py in __init__(self, sparkContext, sqlContext) 91 """ 92 self._sc = sparkContext ---> 93 self._jsc = self._sc._jsc 94 self._jvm = self._sc._jvm 95 self._scala_SQLContext = sqlContext AttributeError: 'module' object has no attribute '_jsc' What causes this error and how can I fix it? UPDATE It turns out that the problem exists if I use Anaconda python distribution for Linux: ~$ ipython --version 4.0.0 ~$ python --version Python 2.7.10 :: Anaconda 2.3.0 (64-bit) But, if I disable the anaconda distribution and use Python that comes with the system, everything works well $ ipython --version 4.0.0 $ python --version Python 2.7.3 $ cat /etc/issue Debian GNU/Linux 7 \n \l So, the problem is with Anaconda, but still don't know what the problem is A: not sure about the specific error, as it should have the same issue for vanilla and anaconda spark, however, a couple of things you can check: Make sure the same python version is installed on both your drivers and workers. Different versions can cause issues with serialization. IPYTHON_OPTS is generally deprecated. Instead I define the following environment variables: # tells pyspark to use notebook export PYSPARK_DRIVER_PYTHON_OPS="notebook" # tells pyspark to use the jupyter executable instead of python. In your case you might want this to be ipython instead export PYSPARK_DRIVER_PYTHON=/opt/anaconda2/bin/jupyter # tells pyspark where the python executable is on the executors. It MUST be the same version of python (preferably with the same packages if you are using them in a UDF or similar export PYSPARK_PYTHON=/opt/anaconda2/bin/python Of course I see you are not adding a master to the command line so this would run spark locally if you haven't changed you spark defaults (i.e. no workers).
{ "language": "en", "url": "https://stackoverflow.com/questions/32889120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Unable to click on a link inside textview message on android mobile app-Appium Anyone help on this.... code I want to access the hyperlink within my text as depicted in the pic : Notes: I tried directly clicking in text by using id but didnt worked. I tried using scrollTo() but still it didnt worked. I tried with linkText even that didnt worked. A: clickable is set to false. You have to set it true in xml file and later on handle onClick event in your activity class A: image only you need to handle onclick listener in Android java file where you make reference the text of your xml like TextView mytext=(TextView)findviewbyid(R.id.ref of your TextView); mytext.setOnClickList();
{ "language": "en", "url": "https://stackoverflow.com/questions/35482941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using ViewFlipper with onclick to switch views I'm using ViewFLipper with Random.nextInt(). to change layouts onClick (Button). Now I have 3 xml layouts. 1_view.xml 2_view.xml 3_view.xml. Starting from 1_view.xml I have a button there. When button clicked I should get a random layout. it works. But the problem is now, sometimes I get the same layout (1_view.xml). When a user clicks a button on (1_view.xml), I want them to go to the layouts I have left (2_view.xml and 3_view.xml). Codes Main.xml <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dip" > <TextView android:id="@+id/TVLeft" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_gravity="left|top" android:text="0" android:textColor="#4CB848" android:textSize="40sp" android:textStyle="bold" /> <TextView android:id="@+id/TVRight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_toRightOf="@+id/TVLeft" android:gravity="right" android:text="0" android:textColor="#FF0000" android:textSize="40sp" android:textStyle="bold" /> </RelativeLayout> <ViewFlipper android:id="@+id/viewFlipper1" android:layout_width="match_parent" android:layout_height="wrap_content" > <include android:id="@+id/1_View" layout="@layout/1_view" /> <include android:id="@+id/2_View" layout="@layout/2_view" /> <include android:id="@+id/3_View" layout="@layout/3_view" /> </ViewFlipper> </LinearLayout> Main.java // FlipperView MyViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper1); TVRight = (TextView) findViewById(R.id.TVRight); TVLeft = (TextView) findViewById(R.id.TVLeft); // 1_view.xml Q1_btn1 = (Button) findViewById(R.id.btn_1); Q1_btn2 = (Button) findViewById(R.id.btn_2); Q1_btn3 = (Button) findViewById(R.id.btn_3); Q1_btn4 = (Button) findViewById(R.id.btn_4); Q1_btn1.setOnClickListener(new OnClickListener() { public void onClick(View v) { Wrongnum++; WrongResult.setText(Integer.toString(Wrongnum)); } }); Q1_btn2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Rightnum++; RightResult.setText(Integer.toString(Rightnum)); Random RandomView = new Random(); MyViewFlipper.setDisplayedChild(RandomView.nextInt(3)); } }); Q1_btn3.setOnClickListener(new OnClickListener() { public void onClick(View v) { Wrongnum++; WrongResult.setText(Integer.toString(Wrongnum)); } }); Q1_btn4.setOnClickListener(new OnClickListener() { public void onClick(View v) { Wrongnum++; WrongResult.setText(Integer.toString(Wrongnum)); } }); A: You can do this in your code: Random RandomView = new Random(); int nextViewIndex = RandomView.nextInt(3); while (nextViewIndex == MyViewFlipper.getDisplayedChild()) { nextViewIndex = RandomView.nextInt(3); } MyViewFlipper.setDisplayedChild(nextViewIndex); Basically just call Random.nextInt() until it doesn't match current viewFlipper's index. To only show a viewFlipper once randomly: // Intialize this once List<Integer> vfIndices = new ArrayList<Integer>(); for (int i = 0; i < MyViewFlipper.getChildCount(); i++) { vfIndices.add(i); } // when button is clicked if (vfIndices.size() == 0) { return; // no more view flipper to show! } int viewIndex = RandomView.nextInt(vfIndices.size()); MyViewFlipper.setDisplayedChild(vfIndices.get(viewIndex)); vfIndicies.remove(viewIndex); The idea is use an ArrayList to keep track of the viewFlipper index that has not been shown. When button is clicked, pick an index randomly from this array and set the viewFlipper to. Then remove that index from the ArrayList. Next time the button is clicked, it will show one of the remaining flippers.
{ "language": "en", "url": "https://stackoverflow.com/questions/11442287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Searching in couchdb or do river thru an elastic search I understand we create views on couchdb and then we can search. Another interesting approach is to connect couchdb with elasticsearch thru river and search in elasticsearch. I have two questions: * *in terms of disk space usage, will elasticsearch be more efficient? *what would be the pros and cons of using couchdb search vs using elasticsearch on top of couchdb? Thanks! A: Only thing CouchDB queries can give you is the key -> value mapping. You can search the ordered dictionary, but you cannot search in the multi-dimensional data, with regular expression or even the key that contain a keyword as a substring (e.g. you have data "Mr. John Smith", and you want it to be found by the query with the keyword "John"). ElasticSearch fills the gap and provides additional indexing of the data. It is mainly useful for full-text indexing, but also supports geospatial data. A: In terms of disk usage: * *https://github.com/logstash/logstash/wiki/Elasticsearch-Storage-Optimization *http://till.klampaeckel.de/blog/archives/95-Operating-CouchDB.html As Marcin pointed out, Elasticsearch excels in full-text-search and its flexibility of analyzer and search functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/13025065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Banner overlay a html5 video and something happen when click on play i'm searching for a long time a solution for my necessities but i can't find anything help me. Well, i have a html5 player with a video (with exception, if not support, use flash) i wanna insert a banner into this video at a certain time and for a certain duration, full screen and normal size. what javascript code should i use? the html should be easy: div banner (hidden) video /div what javascript code should i use? 2° Question: i always have this player, i want that when the user click for the first time on play, happen something, like open an full size image, or open a video, ecc. I not found so much on internet about advertising and coding, and i'm not very good with javascript. So, i hope some one there can help me, thank you. A: * *Display your ad image on page load and ask user to click to play video. *Load your video with a proper player plugin *Start playing video *Continuously check video duration using player API *At a specific duration like (15th second) display and overlay div on top of your video *Done. Also if you're not that good with javascript probably it's better to start with something less complicated.
{ "language": "en", "url": "https://stackoverflow.com/questions/40343391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Thin Controllers in Laravel 4 I am trying to work out the 'best' way of structuring my controllers/models in a new Laravel 4 app. Obviously I want to keep the controllers thin and lightweight. So I want to work with Repos/Services to separate things, however I don't really know how to implement this in Laravel 4. Laravel 3 gave us some idea of how this should work, but no samples. Has any one figured out the neatest way to do this, or have any sample code I could take a peek at? A: I agree on the fact that it isn't very clear where to store these classes in Laravel 4. A simple solution would be creating repositories/services folders in your main app/ folder and updating your main composer.json file to have them autoloaded: { "require": { "laravel/framework": "4.0.*" }, "autoload": { "classmap": [ "app/commands", "app/controllers", "app/models", "app/database/migrations", "app/tests/TestCase.php", "app/repositories", "app/services" ] }, "minimum-stability": "dev" } Note: everytime you create a new class you have to run composer dump-autoload. In case of repositories, you can have Laravel inject them into your controllers automatically. I find this a good screencast on this subject. A: I found this collection of tutorials to be a great introduction on the proper place to store your custom service providers and other files that you want to inject into your project: * *http://fideloper.com/laravel-4-application-setup-app-library-autoloading *http://fideloper.com/laravel-4-where-to-put-bindings *http://fideloper.com/error-handling-with-content-negotiation These tutorials come from this collection: http://fideloper.com/tag/laravel-4 A: The first thing that I do when I get a fresh install of Laravel is: * *Remove the "models" folder *Create a src folder *Under the src, create a Application folder (or the name of the app) *On Application folder, create Entities, Repositories, Services and Tests So, in this case your namespace will be Application\Entities, Application\Repositories and Application\Services In composer.json: { "require": { "laravel/framework": "4.0.*" }, "autoload": { "psr-0": { "Application": "app/src/" }, "classmap": [ "app/commands", "app/controllers", "app/database/migrations", ] }, "minimum-stability": "dev" } To each one of those you'll need to create the classes and a service provider to bind a repository to an entity. Here is a tutorial explaining how to create the repositories: http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/ Anyway, I'm still looking for the best architecture. If anyone has a better idea, I'll be glad to hear it!
{ "language": "en", "url": "https://stackoverflow.com/questions/14645929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Table export jquery - display issue I have a table with a Header Row and a Sub-header row. The Header row has colspan of 3 for most cells. When exporting to Excel, I cannot get this Header Row to: * *Show as merged cell. *Leave blank spaces if it cannot merge. As a result the Header row is shorter than the sub-header row. I have tried the following, but it doesn't export the hidden cells. <th colspan=3>Contacted</th> <th style="display:none;" data-tableexport-display="always">Number</th> <th style="display:none;" data-tableexport-display="always">Number</th> Is anything extra needed to make data-tableexport-display="always" work? TL;DR, How to deal with colspan not displaying as merged cell?
{ "language": "en", "url": "https://stackoverflow.com/questions/47173846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing color of HTML element using radio button I have 10 groups of radio button with two options, each group separated by a <div>. <div id = "radio1"> <p>Do you like to walk?</p> <input type="radio" value="a" name="radgrp1"/> Yes <br /> <input type="radio" value="b" name="radgrp1"/> No <br /> </div> <div id = "radio2"> <p>Would you prefer to walk without effort?</p> <input type="radio" value="a" name="radgrp2"/> Yes <br /> <input type="radio" value="b" name="radgrp2"/> No <br /> </div> Then I have 10 tags that point to each group. <a id ="a1" href="#radio1">Goto 1</a> <a id ="a1" href="#radio2">Goto 2</a> What I am looking to achieve is the moment a user clicks on "Yes" option, color of respective tag ie Goto 1, Goto 2 etc turns green. A: A common technique is to create a relationship between elements by using data attributes. In your case, you could put an attribute on each input/radio button that references the id of the element you want to affect. <input type="radio" value="a" name="radgrp1" data-target="a1" /> Yes <br /> Then using some jQuery you could do this: $('input[type="radio"]').change(function(){ var id = $(this).attr('data-target'); $('#' + id).css('background-color', 'rgb(255, 255, 255)'); }); A: You may try this (assumed there is no document.body.onclick event handler other than this) var radios = document.querySelectorAll('input[name^=radgrp]'); document.body.onclick = function(e){ var evt = e || window.event, target = evt.target || evt.srcElement; if(target.name) { var prefix = target.name.substr(0, 6), suffix = target.name.substr(6); if(prefix && prefix == 'radgrp') { if(target.value == 'a' ) { document.getElementById('a' + suffix).style.color = 'green'; } else { document.getElementById('a' + suffix).style.color = ''; } } } }; Put this code just before the closing </body> tag between <script> tags like <script type='text/javascript'> // code goes here </script> Also, you may check this for registering events using different approaches. Update : querySelectorAll won't work in IE-6 so you may try this alternative solution for IE-6 to work. Also, if you use jQuery (put the code in <head> between <script>), you may use this example and in case of jQuery, you have to add jQuery script in your <head> section section first.
{ "language": "en", "url": "https://stackoverflow.com/questions/20040731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tabs in the Pyqt4 Which command to use to "break" a row of tabs? I would like to have, for example, 3 tabs in one row and 3 tabs just below it. The skeleton I have referenced as tabs is: # layout tab tabs = qg.QTabWidget() # Create tabs tab1 = qg.QWidget() tab2 = qg.QWidget() tab3 = qg.QWidget() tab4 = qg.QWidget() tab5 = qg.QWidget() tab6 = qg.QWidget() tabs.addTab(tab1,"Properties") tabs.addTab(tab2,"Nodes") tabs.addTab(tab3,"Bars") tabs.addTab(tab4,"Restrains") tabs.addTab(tab5,"Nodal Loads") tabs.addTab(tab6,"Dist.Loads") Here is an example of what I want
{ "language": "en", "url": "https://stackoverflow.com/questions/52171529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two Layouts for row in ListView I have two layouts that are used according to product availability (available and missing) in stock. I tried to use them but without success, so I created a standard layout and change the Shape that contains the settings for each case. This is the best way to do? How can I use both in my Layouts APPLICATION? Ps .: Remember that the ListView will not be with alternating colors (zebra style), but according to product availability. using System; using Android.App; using Android.Views; using Android.Widget; using ServiceClass.Auvo_WebService; using Android.Content; using AppClass_Mobile; public class AdapterProduct : BaseAdapter { private Activity _Activity = null; private static Product[] _ListOfProduct; public static User _InstaceOfUser; public static LayoutInflater _Inflater = null; private View _View; public AdapterProduct(Activity activity, Product[] listOfProduct) { _Activity = activity; _ListOfProduct = listOfProduct; try { _Inflater = (LayoutInflater)_Activity.GetSystemService(Context.LayoutInflaterService); } catch (Exception ex) { Console.WriteLine(ex); } } public override View GetView(int position, View convertView, ViewGroup parent) { _View = convertView; ViewHolderProduct holderProduct; try { if (_View != null) holderProduct = _View.Tag as ViewHolderProduct; else { _View = _Activity.LayoutInflater.Inflate(Resource.Layout.LayoutGenericProd, null); holderProduct = CriaHolder(position); } PopulaHolder(holderProduct, position); _View.Tag = holderProduct; } catch (Exception ex) { Console.WriteLine(ex); } return _View; } private void PopulaHolder(ViewHolderProduct holderProduct, int position) { if (_ListOfProduct[position].ThisProductIsOk) { holderProduct.descrProd.SetBackgroundResource(Resource.Layout.ShapeRoundedCornerOut); holderProduct.descrProd.SetTextColor(Android.Graphics.Color.Black); } else holderProduct.descrProd.SetBackgroundResource(Resource.Layout.ShapeRoundedCornerIn); holderProduct.descrProd.Text = _ListOfProduct[position].Name; holderProduct.lastUpDate.Text = _ListOfProduct[position].DataProduct.ToString("HH:mm"); } private ViewHolderProduct CriaHolder(int position) { ViewHolderProduct holderProduct = new ViewHolderProduct(); holderProduct.descrProd = _View.FindViewById<TextView>(Resource.Id.descrProd); holderProduct.lastUpDate = _View.FindViewById<TextView>(Resource.Id.lastUpDate); return holderProduct; } public override Java.Lang.Object GetItem(int position) { return null; } public override long GetItemId(int position) { return position; } public override int Count { get { return _ListOfProduct.Length; } } public int GetCount() { return _ListOfProduct.Length; } public void AddItem(Product product, User User) { try { if (User.SerialNum == _InstaceOfUser.SerialNum) AddPordInList(product); } catch (Exception ex) { Console.WriteLine(ex); } } private void AddPordInList(Product product) { Array.Resize(ref _ListOfProduct, _ListOfProduct.Length + 1); _ListOfProduct[GetCount() - 1] = product; this.NotifyDataSetChanged(); } private class ViewHolderProduct : Java.Lang.Object { public TextView descrProd { get; set; } public TextView lastUpDate { get; set; } public ImageView statusProd { get; set; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/26935758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SignalR in windows forms SignalR is very interesting and impressive in real time web applications. Now I am doing a simple chat applciation using windows forms. Whenever, I use ".wait()", it threw an error 'one or more errors' and while invoke the message from text box, there is an error 'start must be call before send'. I don't know where i made mistake. I tried many of the solutions. But it doesn't work. Everything is perfect in web and console applications. Can anyone help me? Can you give some examples with how it works...? I couldn't see any samples of signalR in windows forms. A: Assuming you are trying to do a SignalR Client in Windows Forms Appliation then check this post(http://mscodingblog.blogspot.com/2012/12/testing-signalr-in-wpf-console-and.html) on how to do client side SignalR in WPF application in VB. With similar approach I guess you could make Signalr client working in Windows Forms Application.
{ "language": "en", "url": "https://stackoverflow.com/questions/13641928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to translate shutter speed values into usable data? I'm gathering light statistics of EXIF data for a large collection of photos and I'm trying to find the simplest way (i.e. performance doesn't matter) of translating Exposure Time values to/from usable data. There is (as far as I can find) no standard for what values camera manufacturers might use i.e. I can't just scan the web for random images and hard-code a map. Here are is a sample set of values I've encountered (" indicates seconds): 279", 30", 5", 3.2", 1.6", 1.3", 1", 1/1.3, 1/1.6, 1/2, 1/2.5, 1/3, 1/4, 1/5, 1/8, 1/13, 1/8000, 1/16000 Also take into consideration that I'd also like to find the average (mean) ... but it should be one of the actual shutter speeds collected and not just some arbitrary number. EDIT: By usable data I mean some sort of creative? numbering system that I can convert to/from for performing calculations. I thought about just multiplying everything by 1,000,000 except some fractions when divided are quite exotic. EDIT #2: To clarify, I'm using ExposureTime instead of ShutterSpeed because it contains photographer friendly values e.g. 1/50. ShutterSpeed is more of an approximation (which varies between camera manufacturers) and leads to values such as 1/49. A: You want to parse them into some kind of time-duration object. A simple way, looking at that data, would be to check wheter " or / occurs, if " parse as seconds, / parse as fraction of seconds. I don't really understand what else you could mean. For an example you'd need to specify a language--also, there might be a parser out there already. A: Shutter speed is encoded in the EXIF metadata as an SRATIONAL, 32-bits for the numerator and 32-bits for the denominator. Sample code that retrieves it, using System.Drawing: var bmp = new Bitmap(@"c:\temp\canon-ixus.jpg"); if (bmp.PropertyIdList.Contains(37377)) { byte[] spencoded = bmp.GetPropertyItem(37377).Value; int numerator = BitConverter.ToInt32(spencoded, 0); int denominator = BitConverter.ToInt32(spencoded, 4); Console.WriteLine("Shutter speed = {0}/{1}", numerator, denominator); } Output: Shutter speed = 553859/65536, sample image retrieved here. A: It seems there are three types of string you will encounter: * *String with double quotes " for seconds *String with leading 1/ *String with no special characters I propose you simply test for these conditions and parse the value accordingly using floats: string[] InputSpeeds = new[] { "279\"", "30\"", "5\"", "3.2\"", "1.6\"", "1.3\"", "1\"", "1/1.3", "1/1.6", "1/2", "1/2.5", "1/3", "1/4", "1/5", "1/8", "1/13", "1/8000", "1/16000" }; List<float> OutputSpeeds = new List<float>(); foreach (string s in InputSpeeds) { float ConvertedSpeed; if (s.Contains("\"")) { float.TryParse(s.Replace("\"", String.Empty), out ConvertedSpeed); OutputSpeeds.Add(ConvertedSpeed); } else if (s.Contains("1/")) { float.TryParse(s.Remove(0, 2), out ConvertedSpeed); if (ConvertedSpeed == 0) { OutputSpeeds.Add(0F); } else { OutputSpeeds.Add(1 / ConvertedSpeed); } } else { float.TryParse(s, out ConvertedSpeed); OutputSpeeds.Add(ConvertedSpeed); } } If you want TimeSpans simply change the List<float> to List<TimeSpan> and instead of adding the float to the list, use TimeSpan.FromSeconds(ConvertedSpeed);
{ "language": "en", "url": "https://stackoverflow.com/questions/4197206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Filter list of old bookmark URLs to exclude websites no longer in service using Vim I'm trying to learn some more about Vim and the Linux command line; the project I'm working on is: Trying to convert a browser's export of bookmarks.html into a plain text list of URLs that still work. * *First, I used lynx -dump -listonly bookmarks.html > bookmarks to format the HTML to plain text: 1. https://example.com/vim-is-cool.html 2. https://example.com/index.html *Used Vim to strip the numbers and leading spaces away (:% s/.\+ /) *Used Vim to remove everything but the top level domain (:%! cut -d'/' -f1,2,3) *Used Vim to remove duplicates with :sort u *To test one of the links, I'd use: curl -I https://www.example.com | grep HTTP | sed 's/HTTP\/1\.1 //g' 200 OK Now, I'd like to: *Check the shortlist of short URLs via the same command (I'm not sure how to iterate the same command for every line in Vim's buffer) *Filter the file containing all full URLs based on whether cURL gets a 200 OK for the short URL (this part is also way beyond me) *Write the remaining list of working full URLs to bookmarks4 (most likely I could handle this) If reasonably possible, I'd like to complete all of that without scripting in shell/bash or leaving Vim. A: This might work for you (all GNU utilities using bash): lynx -dump -listonly bookmarks.html | grep -o 'https\?://[^/]*' | sort -u | parallel -k 'curl -I -m2 {} |& grep -q "HTTP/[0-9.]\+ 200" && echo {}' >bookmarks4 Use lynx to format links. Use grep to format urls. Use sort to sort and remove duplicates. Use parallel to check the urls using curl and checking its output for a 200 reply using grep. Output those urls that meet the requirements to bookmarks4. To output the original urls, perhaps: lynx -dump -listonly bookmarks.html | grep http | parallel --rpl '{url} s:.*(https?.*):$1:' \ --rpl '{dom} s:.*(https?\://[^/]*).*:$1:' \ 'curl -m2 -I {dom} |& grep -q "HTTP/[0-9.]\+ 200" && echo {url}' | sort -u >bookmarks4
{ "language": "en", "url": "https://stackoverflow.com/questions/75067844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rebase from commit I have a framework that I coded, it's into a Github repository, as the master branch. Into that branch are only the core files of the framework, so I named it the core branch. Now into other branches, I list projects that use said core framework — I did this because I though working with branches would be easier but as I just discovered, it's not. Seriously. So to sum up : I have a core branch, and a project branch that uses that core. Now on the project branch, I do mostly commits related to the project (added image X, modified stylesheet Y) but sometimes I modify the core, to make it better. Now what I'd like to do, and again I thought this would be simple, is when I start working on the core more than the project, merge the changes to the core into the core branch. There's several solution and it's all starting to confuse me, and since I would like not to mess up my core branch, how should I proceed ? I know I can cherry pick commits and push it but I'd really like to keep the history of changes to the core files, so I've been directed to rebasing. Problem is : if I rebase my core branch to a specific commit on the project branch, it will push all the files and stuff that have nothing to do with the core. So how do I rebase from a certain commit (and not to, which seems to be the default ?). Here is some sort of idea of what commits on the project branch might look like : project branch 00:12 - Added image X 00:14 - Modified stylesheet Y to have a pink background (pink is pretty) 00:16 - Modified class core.background to handle pink background 00:18 - Modified class core.string to always capitalize Pink (because it's so pretty) How do I merge the last two commits into core branch without merging the two first one that were project-related, and by keeping history — ie. keeping those two changes to the core as two commits and not one ? Edit : more precisions. My core framework defines a project's folder organization and thus needs to be at the root of the project folder. That's why it's not a submodule, which would have been the dream. Also, I tried a fork of the core, but apparently you can't fork your own projects. If there is another way besides branches to do what I want, I'm all ears. A: git branches don't really work like that - the branches all relate to the repository. Separating projects, or parts of projects, into separate branches isn't really the right way to go. Eventually, most branches should be merged into a release branch of some type, or discarded. I have a core branch, and a project branch that uses that core. Now on the project branch, I do mostly commits related to the project... I'd really like to keep the history of changes to the core files [separate] From that, I think it sounds a lot like you have a good use case for two separate repositories, one for core-files and one for project - you want to keep the history of core and project separate. Rather than keeping them in the same repository in different branches, I'd advocate pulling the core-files into a git submodule of projects. That'd give you several advantages right off the bat: * *project and core history are separate. *Using core with another project is very simple; import core as a git submodule of the otherproject. *The history of both project and core is much, much easier to maintain, because you're not having to cherry-pick between branches anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/10693644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: API for google apis console? Is there any way how to access https://code.google.com/apis/console with any kind of api? I need to access it with python and add subdomains to oauth2 callbacks dynamically, thanks. A: No, there's no API to programmatically configure projects in the APIs Console.
{ "language": "en", "url": "https://stackoverflow.com/questions/12121555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OpenAL Memory not release in iOS I used OpenAL to play sounds ,I used alGetError(); check every OpenAL functions , no errors ,after finished used OpenAL I release the buffer、source 、 context 、 OpenAL device I used Instrument to check the memory used , there still some memory cannot be release // relese source buffer alSourcei(sourceId, AL_BUFFER, 0); alDeleteSources(1, &sourceId); alDeleteBuffers(1, &bufferId); //release context device bool res = alcMakeContextCurrent( NULL ); alcDestroyContext( context ); BOOL res = alcCloseDevice( device ); the leaked memory probally when I first and second used alGenBuffers( 1, &bufferId ); judge by the size of leakd memory,and I am not quite sure I have setup the OpenAL Context and device before used any OpenAL functions,I used alGetError(); check every steps ,no errors is this normal, OpenAL just cache the memory? Anybody have any ideas? Thanks How openAL reclaim memory?
{ "language": "en", "url": "https://stackoverflow.com/questions/73033225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't customize bootstraps tab's border-top - have blank space with 100% width in absolute position Can't customize bootstrap's tabs border-top - have blank space with 100% width in absolute position after the line. http://jsfiddle.net/Vimpil/0mmv73oh/ li.active:after { position: absolute; width: 97%; padding: 1px; top: -1px; content: ''; background: #000; height: 4px; } A: This extra space is because of margin-right applied to links in Bootstrap's default styles. You can fix this by overriding that styles or remove width and use left: 0 and right: 2px to stretch line. jQuery(function () { jQuery('#myTab a:last').tab('show') }) @import url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css'); li.active:after { position: absolute; padding: 1px; top: -1px; content: ''; background: #000; height: 4px; right: 2px; left: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <ul class="nav nav-tabs" id="myTab"> <li class="active"><a data-target="#home" data-toggle="tab">Home</a></li> <li><a data-target="#profile" data-toggle="tab">Profile</a></li> <li><a data-target="#messages" data-toggle="tab">Messages</a></li> <li><a data-target="#settings" data-toggle="tab">Settings</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="home">Home</div> <div class="tab-pane" id="profile">Profile</div> <div class="tab-pane" id="messages">Message</div> <div class="tab-pane" id="settings">Settings</div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/39364561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Error at backbone model fetch to slim framework I'm trying to get a simple app working. It uses backbone, the slim framework and cordova. For now, all i'm trying to do is fetch user models from a MySQL database. Client side code looks like: // Cordova is ready function onDeviceReady() { // This little code snippet prepends our root to any Ajax call. $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { options.url = 'http://localhost/~nmeibergen/IBMI/www/' + options.url; }); var profileView = new ProfileView(); var Router = Backbone.Router.extend({ routes: { "": "home" } }); var router = new Router(); router.on('route:home', function() { profileView.render(); }); Backbone.history.start(); } var Users = Backbone.Collection.extend({ url: 'index.php/users', model: User }); var User = Backbone.Model.extend({ urlRoot: 'index.php/users', defaults: { user_id: 1, name: 'Nathan', } }); var ProfileView = Backbone.View.extend({ el: '#home', render: function () { var users = new Users(); alert('all fine'); users.fetch(); } }); Whenever I simply go to http://localhost/~nmeibergen/IBMI/www/index.php/users, I get the expected JSON object: [{"user_id":"1","name":"Jhonathan "},{"user_id":"0","name":"Nathan"}] However when running the above code it hits the alert 'all fine', but then gives me the following error and stack trace: TypeError: 'undefined' is not an object (evaluating 'targetModel.prototype') in backbone.js:1:689 set backbone.js:1:689 success backbone.js:1:686 fire jquery-1.11.1.js:3119 fireWith jquery-1.11.1.js:3231 done jquery-1.11.1.js:9275 callback jquery-1.11.1.js:9685 I can't seem to find out what is wrong with the code, it should be pretty basic. Thank you for looking! A: When you say this: var x = 6; The var x declaration will be hoisted to the top of the current scope. However, the assignment part will not be hoisted. The result is that you're saying this: var x; // Everything from the top of the scope to your `var x = 6` goes here. x = 6; In your case, you're doing this: var Users = Backbone.Collection.extend({ url: 'index.php/users', model: User }); var User = Backbone.Model.extend({ urlRoot: 'index.php/users', defaults: { user_id: 1, name: 'Nathan', } }); so var User is hoisted to the top of the scope but User = Backbone.Model.extend(...) happens after Users = Backbone.Collection.extend(...). Rearranging the code to match what really happens, we have: var Users, User; Users = Backbone.Collection.extend({ //... model: User }); User = Backbone.Model.extend({ //... }); What do you think the value of User will be when it is used in the definition of Users? User will be undefined just like any other uninitialized variable. Demo: http://jsfiddle.net/ambiguous/xYkmc/ You need to define your User before Users: var User = Backbone.Model.extend({ urlRoot: 'index.php/users', defaults: { user_id: 1, name: 'Nathan', } }); var Users = Backbone.Collection.extend({ url: 'index.php/users', model: User }); Demo: http://jsfiddle.net/ambiguous/E7V84/
{ "language": "en", "url": "https://stackoverflow.com/questions/24128323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Turing a monolithic application into a Microservice based architecture and keeping the GIT history I'm planning to split a monolithic application into a micro service based architecture, but I want to keep the GIT history. The monolit should be split into three micro services. My first approach would be, copying the GIT Repository three times and removing all non domain specific parts from the new micro service which should keep the most parts of the git history alive. But I am not shure if this is the best way keeping the version control history. A: You can use git filter-branch with the --subdirectory-filter option to filter a subdirectory of your repository and thus make the repository contain the subfolder as root directory. This is described in step 5 here, documentation here might also help. You would have to clone your repository three times and run filter-branch in each of those for a different part of your project. Since (with said --subdirectory-filter) only subdirectories can be treated this way, you may have to rearrange your repository before. The advantage over the naive deletion of other parts is, however, that by using filter-branch you will only preseve history that concerns the actual content of your repository, and do not have any history of the parts filtered out.
{ "language": "en", "url": "https://stackoverflow.com/questions/43515765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SignalR Hub hosted in azure misses to send message to few connections - AspNetCore.SignalR I am using Microsoft.AspNetCore.SignalR to broadcast a message to all connected clients. The Hub is hosted in Azure as App Service. I am able to see the connected client's Connection IDs by inserting them to a table in DB. When I hit broadcast the messages are send only to 8 out of 10 clients(Always misses few clients). The status of the missed out clients are logged as connected in DB. My Hub Code: public class NotificationHub : Hub { public override async Task OnConnectedAsync() { ****Here I insert the connection IDs to DB with connected status*** await Groups.AddToGroupAsync(Context.ConnectionId, "SignalRUsers_" + Context.ConnectionId); await base.OnConnectedAsync(); } } I am calling the HubContext from outside the Hub as I need to broadcast the message on external process completion. My Broadcaster Code: public class SignalBroadcaster : ISignalBroadcaster { private readonly IHubContext<NotificationHub> _hubContext; public class SignalRConnections { public string ConnectionId { get; set; } public DateTime ConnectedOn { get; set; } public string Status { get; set; } } public SignalBroadcaster(IHubContext<NotificationHub1> hubContext) { _hubContext = hubContext; } public async void BroadcastToAll(ISignal signal, TelemetryClient log) { List<SignalRConnections> lstsignalRConnections = new List<SignalRConnections>(); try { using (SqlConnection conn = new SqlConnection(Environment.GetEnvironmentVariable("XXXXXXX"))) { using (SqlCommand command = new SqlCommand("", conn)) { try { conn.Open(); command.CommandText = "SELECT * FROM SignalRXXXXXXX WHERE SignalRStatus = 'CONNECTED'"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { SignalRConnections signalRConnections = new SignalRConnections() { ConnectionId = reader.GetString(0), ConnectedOn = reader.GetDateTime(1), Status = reader.GetString(2), }; lstsignalRConnections.Add(signalRConnections); } } } catch (Exception ex) { //command.CommandText = "INSERT INTO SignalRConnections (ConnectionId,ConnectedOn,SignalRStatus) VALUES ('" + Context.ConnectionId + "',GETDATE(),'DISCONNECTED')"; //command.ExecuteNonQuery(); } finally { conn.Close(); } } } foreach (var item in lstsignalRConnections) { try { await _hubContext.Clients.Client(item.ConnectionId).SendAsync("ReceiveMessage", signal.JobId, signal.QuantificationResult, signal.JobType); log.TrackTrace("SignalR sent: " + item.ConnectionId); } catch(Exception ex) { log.TrackTrace("SignalR send failed: " + item.ConnectionId + " Exception :" + ex.ToString()); } } } catch (Exception ex) { Exception exp= new Exception(String.Format(Constants.GETDATAEXCEPTIONMESSAGE, "BroadcastToAll ", ex.InnerException)); } } } Please ignore the DB connection mess here as I am doing it for testing purpose. Will refactor later. My client Code: connection.on("ReceiveMessage", (user, message,msg1) => { var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); var encodedMsg = user + " says " + msg + msg1; var li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); connection.start().catch(err => console.log(err)); Please help me why it is missing few clients randomly. I tried searching lot of articles and help but could not find something specific to this issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/52369272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Graph for URLs - Getting the number of shares for a group of pages How can we know the sum of all Facebook shares for all URLs that start with: http://www.guardian.co.uk/artanddesign/ There's an API method for a specific URL that is: https://graph.facebook.com/?ids=http://www.guardian.co.uk/artanddesign/2012/feb/19/frank-gehry-new-york-interview But I can't make it sum all the URLs that start with http://www.guardian.co.uk/artanddesign/. Notes: * *I can't iterate trough all the URL's in the directory "artsanddesign". *Please note that the URL's above are just examples. *I can't access insights because I don't have permissions to add a meta-tag on the root directory of the site *Maybe the solution is using the Facebook Query Language (FQL)? How could it work? A: I don't believe there's any way to get information for all URLs that match a certain pattern, I think you have to specify the individual URLs manually - this shouldn't be a bug problem if it's your own site, as you'll already have a database of all possible article URLs, but if you're checking someone else's site it could be difficult.
{ "language": "en", "url": "https://stackoverflow.com/questions/9354003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: cannot run the cardboard demo on iOS device I have done everything google developer website told,but the problem is Xcode still has some problems when compiling the demo project. The problem is:ld: /Users/Day1/Desktop/temp files/New Unity Project 3/cardboarddeomsave2/Libraries/Plugins/iOS/libvrunity.a(unity-6C9520564923BB79.o) does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Another thing I have realize is that, before I compile the project, the right side of the Xcode scene has one area which is red. (libiconv.2.dylib is red) Is there any correlations here? (By the way I have upgraded my OS X to OS X EI Captian beta and my Xcode is Xcode 7.0 beta) A: I was reaching this problem as well and this seemed to solve my problem. (It builds for me and deploys the application, but then fails to run while still connected. If I stop the connection and restart the app so that it is only running from the phone, it runs perfectly fine.) * *In Xcode, select the folder view in the left pane top menu and select your project in the left pane. *Then in the menu above the main panel, select Build Settings. *In Build Settings, make sure that "All" is selected (not "Basic") *Scroll down to Build Options and set "Bitcode Enabled" to NO.
{ "language": "en", "url": "https://stackoverflow.com/questions/32393691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WHat is the use of @Valid when @NonNull does the job for us? Code in controller - @PostMapping("/employees") public Employee saveEmployee(@Valid @RequestBody Employee employee) { return employeeService.saveEmployee(employee); } Entity Object - @NotNull(message = "Department must not be null") @Column(name = "department") private String department; Suppose I pass an item with a null department field. @NonNull will throw an exception in that case. But I have seen @Valid being used for the same purpose. Can somebody elaborate why @Valid needs to be used in addition to @NonNull? A: If you omit the @Valid Spring will omit the validation on the web layer. Which basically means your controller, will not trigger validation. Validation is done by the RequestMappingHandlerAdapter when an @Valid(adted) annotation is found on an @ModelAttribute or @RequestBody annotated method argument. JPA will also use a configured validator and trigger validation as well. So a validation exception will be thrown upon writing into the database. You can disable this with spring.jpa.properties.javax.persistence.validation.mode=none in your application.properties (or the YAML equivalent). When disabling both no validation will be done. In that case you only hope is a database constraint that the column isn't allowed to be null. So validation is still done but the location where the validation is done is different. Due to the difference you will also get a different exception. You have to wonder do you really want to do this somewhere upon persisting the entity with the risk of having executed some complex/time consuming business logic, or quickly upon submission of the form. A: So that the object can be validated in the Controller layer you need @Valid (or @Validated) to trigger its validation. You can read more about this on the following online resources: * *https://www.baeldung.com/spring-boot-bean-validation *https://www.baeldung.com/spring-valid-vs-validated On which you can read: Of course, the most relevant part is the use of the @Valid annotation. When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/70369960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LSTM Text Generation Applied on a Time Series with Keras I am currently working on time series prediction. LSTM for Regression with Time Steps subsection in the link gets me going pretty well. However, I want to predict into the further future, not only one-step ahead (i.e. predict every step into the future up to 30th step -- so a sequence generation), and text generation on LSTM networks sounds like the thing I am looking for. To give an example for my ultimate goal, think of the famous Shakespeare text generators. I am trying to either feed all of Shakespeare's works and get a new Shakespeare "play," or complete an unfinished Shakespeare play (because he died without completing this particular work). Is there a way to translate this feature of sequence generation to time series, if so, can you point me towards any resources or examples. Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/42818068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using ostream overloading on pointers to objects So, I have a struct Bike, which looks like this struct Bike { std::string brand; std::string model; bool is_reserved; friend std::ostream& operator<<(std::ostream out, const Bike& b); }; std::ostream& operator<<(std::ostream out, const Bike& b) { return out << "| Brand: " << b.brand << '\n' << "| Model: " << b.model << '\n'; } And another class BikeRentalService, which has a std::vector<Bike*> called bikes_m. This class also has a method print_available_bikes(), which is supposed to iterate over said std::vector<Bike*> and print each Bike by using the overloaded operator<< shown above. This method looks like that: void BikeRentalService::print_available_bikes(std::ostream& out) { if (bikes_m.empty()) { out << "| None" << '\n'; } else { for (auto bike : bikes_m) { if (!bike->is_reserved) { out << bike; } } } } The problem is that using this function just prints out the addresses of those Bike objects. Dereferencing the objects before using out << does not work either, Visual Studio says it can't reference std::basic_ostream because it is a "deleted function". Writing the for loop as (auto *bike : bikes_m) does not change anything. A: The rigth way to overload the ostream operator is as follows: struct Bike { std::string brand; std::string model; bool is_reserved; friend std::ostream& operator<<(std::ostream& out, const Bike& b); // <- note passing out by reference }; std::ostream& operator<<(std::ostream& out, const Bike& b) { return out << "| Brand: " << b.brand << '\n' << "| Model: " << b.model << '\n'; } Also, as noted by @KyleKnoepfel you should change out << bike; to out << *bike; too.
{ "language": "en", "url": "https://stackoverflow.com/questions/37586337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why can I retrieve environment variable in one part of my code, but not another? I've stored an API token as an environment variable in my wsgi file. I'm able to retrieve it in one instance in my Django app, but not another. I'm able to use the token successfully during a save_model operation in my admin. When I use nearly identical code in a management command I get an auth error. My wsgi.py file: import os import sys from django.core.wsgi import get_wsgi_application os.environ['SLACK_TOKEN'] = '12344567890qazxswedcvfrtgbnhyujmkiolp' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() Working admin.py usage: import os from slacker import Slacker def save_model(self, request, obj, form, change): if obj.condition == True: super().save_model(request, obj, form, change) token = os.getenv('SLACK_TOKEN') slack = Slacker(token) slack.chat.post_message('#test-channel', 'mymessage') Not working management command usage: import os from slacker import Slacker def handle(self, *args, **options): try: #test condition except: token = os.getenv('SLACK_TOKEN') slack = Slacker(token) slack.chat.post_message('#newsflow-test', 'mymessage') Troubleshooting indicates the env variable isn't loading -- print(token) produces None response when I run the management command or try to retrieve the token in the Django shell. A: wsgi.py is imported by your Python application server, e.g. gunicorn. Management commands are executed directly and bypass importing wsgi.py. You should use some mechanism, e.g. django-dotenv to load environment variables from a .env file both in your manage.py script and wsgi.py application initializer.
{ "language": "en", "url": "https://stackoverflow.com/questions/58672512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: junk after document element Firefox Error Loading Content With JQuery Get I have a page (which is unfortunately behind a login system), which basically has a nav bar down the left of a list of articles, and when you click on an article, it loads the content from a .inc file stored on the server, using a provided file path. This works fine on Google Chrome. However, on Firefox, when the page loads, I get this weird javascript error: "junk after document element" - When I click the error, it takes me to line 2 of the content from the first article being loaded. Let me show you some code. This is the last JS function which is run when the page has finished loading, and it's purpose is to load the initial article. function initialise_family_center_page() { if (current_element_id == "" || current_element_id == "family_center_general_info") //If this is the first article to be loaded { //Get the file path of the inc file to load var content_directory = file path....; jQuery.get(content_directory, function(data) { $('#family_center_main_content').html(data); //Load the content }); } } The content in the .inc file being loaded is as follows: <p>Some text</p> <p>Some text</p> It's worth mentioning at this point, that in Chrome and Firefox, the content loads. However in firefox, because of the JS error, you can no longer use the rest of the page because the JS has stopped working. Interesting point, which I discovered from googling the problem, is if I change the content of the file to: <html> <p>Some Text</p> <p>Some Text</p> </html> Then the error does not appear and the page works (until you load the next content file without the tags. However, this is not a suitable fix because there are thousands and thousands of files. Can anyone help? A: I had this same problem. I had created a base page where clicking on a nav element triggered an $.ajax() fetch of an inc file that would populate the main div on the page - as follows: $(document).ready(function(){ // Set trigger and container variables var trigger = $('nav.primary ul li a'), container = $('#se-main'); trigger.on('click', function(){ // Set click target from data attribute target = this.target; $.ajax({ url:'../inc/'+target + '.inc', success: function(data){ // Load target page into container container.html(data); }, dataType: "text" // this seems to be ignored in Firefox }); // snip other stuff }); The Firefox console always logged the 'junk after document element' error unless I edited the INC files and wrapped the text in <html></html>. (The page content still updated, though - so the user wasn't held up by it). To fix this: add inc to the text/html line in the apache mime.types config file. Find the line with text/html html htm change to text/html html htm inc Then restart apache. That worked for me. Default file locations: Linux: /etc/mime.types; WAMP: [wampdir]\bin\apache\[apacheversion]\conf\mime.types XAMPP: [xamppdir]\apache\conf\mime.types Where [wampdir] is wherever you installed WAMP/XAMPP, and [apacheversion] is the version of apache that WAMP is using. This solution is no use if you don't have access to the mime.types file, or if you're running on shared hosting. In that case - assuming that you have access to .htaccess - adding the following to .htaccess might work - AddType text/html .html .htm .inc
{ "language": "en", "url": "https://stackoverflow.com/questions/34201654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can't get image from camera with intent chooser on 4.2.2 AVD I'm working on a part of my application that allows a user to select an image either from camera or from gallery, using an Intent chooser. It's working fine on my 2.2.1 android phone, but when i compile it on a 4.2.2 AVD it returns a null pointer error when i use the camera, public void onClick(View View) { Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,null); galleryIntent.setType("image/*"); galleryIntent.setAction(Intent.ACTION_GET_CONTENT); galleryIntent.addCategory(Intent.CATEGORY_OPENABLE); Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); Intent chooser = new Intent(Intent.ACTION_CHOOSER); chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent); chooser.putExtra(Intent.EXTRA_TITLE, "Chooser"); Intent[] intentArray = {cameraIntent}; chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooser,REQUEST_CODE); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { try { if (bitmap != null) { bitmap.recycle(); } InputStream stream = getContentResolver().openInputStream(data.getData()); bitmap = BitmapFactory.decodeStream(stream); stream.close(); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.onActivityResult(requestCode, resultCode, data); } } this is the error i get: 05-05 05:03:31.730: E/AndroidRuntime(820): Caused by: java.lang.NullPointerException And it said that the problem is in this line : InputStream stream = getContentResolver().openInputStream(data.getData()); What am i doing wrong? Updated: Now it's working and here is the solution: protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { if(data.getData()!=null) { try { if (bitmap != null) { bitmap.recycle(); } InputStream stream = getContentResolver().openInputStream(data.getData()); bitmap = BitmapFactory.decodeStream(stream); stream.close(); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { bitmap=(Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(bitmap); } super.onActivityResult(requestCode, resultCode, data); } } Thank you for you help! A: Hi have a try with this code. following code is for camera button click works : imgviewCamera.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //define the file-name to save photo taken by Camera activity String fileName = "new-photo-name.jpg"; //create parameters for Intent with filename ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, fileName); values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera"); //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState) imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); //create new Intent Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, PICK_Camera_IMAGE); } }); OnActivityresult code will be like below protected void onActivityResult(int requestCode, int resultCode, Intent data) { Uri selectedImageUri = null; String filePath = null; switch (requestCode) { case PICK_Camera_IMAGE: if (resultCode == RESULT_OK) { //use imageUri here to access the image selectedImageUri = imageUri; } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show(); } break; } if(selectedImageUri != null){ try { // OI FILE Manager String filemanagerstring = selectedImageUri.getPath(); // MEDIA GALLERY String selectedImagePath = getPath(selectedImageUri); if (selectedImagePath != null) { filePath = selectedImagePath; } else if (filemanagerstring != null) { filePath = filemanagerstring; } else { Toast.makeText(getApplicationContext(), "Unknown path", Toast.LENGTH_LONG).show(); Log.e("Bitmap", "Unknown path"); } if (filePath != null) { Toast.makeText(getApplicationContext(), " path" + filePath, Toast.LENGTH_LONG).show(); Intent i = new Intent(getApplicationContext(), EditorActivity.class); // passing array index i.putExtra("id", filePath); startActivity(i); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Internal error", Toast.LENGTH_LONG).show(); Log.e(e.getClass().getName(), e.getMessage(), e); } } } public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor != null) { // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else return null; } dont forget to add camera permission in manifest file. hope this will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/16381616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In AVD emulator how to see sdcard folder and install an APK to the AVD? I have created an Android emulator (Android Virtual Device), but I am unable to find out the SD card I have built during creation of this. How can I find the SD card and its content and also how to install APK files to the AVD? A: These days the location of the emulated SD card is at /storage/emulated/0 A: On linux sdcard image is located in: ~/.android/avd/<avd name>.avd/sdcard.img You can mount it for example with (assuming /mnt/sdcard is existing directory): sudo mount sdcard.img -o loop /mnt/sdcard To install apk file use adb: adb install your_app.apk A: DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files. A: Drag & Drop To install apk in avd, just manually drag and drop the apk file in the opened emulated device The same if you want to copy a file to the sd card A: if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command adb install apklocation.apk A: I have used the following procedure. Android Studio 3.4.1 View>Tool Windows>Device File Explorer A: * *switch to DDMS perspective *select the emulator in devices list, whose sdcard you want to explore. *open File Explorer tab on right hand side. *expand tree structure. mnt/sdcard/ refer to image below To install apk manually: copy your apk to to sdk/platform-tools folder and run following command in the same folder adb install apklocation.apk A: I have used the following procedure. Procedure to install the apk files in Android Emulator(AVD): Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator. Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools * *Go to Start -> Run -> cmd *Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools” *Type adb install example.apk *After getting success command *Go to Application icon in Android emulator, we can see the your application A: //in linux // in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img that is your sdcard file. //To install apk in linux $adb install ./yourfolder/myapkfile.apk A: Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.
{ "language": "en", "url": "https://stackoverflow.com/questions/10680992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: Saving variables in swing Text field I know how to make a text field but I have no idea how to take the info inputted un the text field and save it into a variable. also be able to save only after pressing enter. import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class scratch1 { public static void main(String args[]) { JFrame frame = new JFrame("Chat Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); JPanel panel = new JPanel(); // the panel is not visible in output JLabel label = new JLabel("Enter Base:"); JTextField tf = new JTextField(2); // accepts upto 2 characters panel.add(label); // Components Added using Flow Layout panel.add(tf); frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.setVisible(true); } A: Try this code, read the comments to understand the code. I hope this code helps you. import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; class main { static String var; // The text input gets stored in this variable public static void main(String args[]) { JFrame frame = new JFrame("Chat Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); JPanel panel = new JPanel(); JLabel label = new JLabel("Enter Base:"); JTextField tf = new JTextField(2); panel.add(label); panel.add(tf); frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.setVisible(true); tf.addActionListener(new ActionListener() { // Action to be performed when "Enter" key is pressed @Override public void actionPerformed(ActionEvent e) { var = tf.getText(); // Getting text input from JTextField(tf) } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/70822819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Allow others to develop plugins for my app I'm developing a home screen replacement for Android with search functionality in the app drawer. I not only want to allow (not force) users to search for installed apps, but also other content like Stack Overflow, Wikipedia or their local files. Currently I'm developing these so-called "Lenses" myself, but I thought it'd be a cool idea if others could develop them as well. So what I'm wondering is if there's any way to allow other developers to do just that; Developing additional lenses for my app. All lenses should inherit from the following class; Lens.java public abstract class Lens { protected Context context; protected Lens (Context context) { this.context = context; } public abstract List<LensSearchResult> search (String str) throws IOException, JSONException; public abstract String getName (); public abstract String getDescription (); public void onClick (String url) { if (url.startsWith ("http://") || url.startsWith ("https://")) { Intent intent = new Intent (Intent.ACTION_VIEW); intent.setData (Uri.parse (url)); this.context.startActivity (intent); } else { throw new UnsupportedOperationException (); } } public void onLongPress (String url) { } protected String downloadStr (String url) throws IOException, JSONException { // Not important. Provided for convenience. } protected Drawable downloadImage (String url) throws IOException, JSONException { // Not important. Provided for convenience. } } The developer should pass Context from their constructor to the superclass, implement List<LensSearchResult> search (String str), String getName (), and String getDescription (). If we're talking about a URL, that's all they need to do. Otherwise they should also override void onClick (String url) and if they wish to do so void onLongPress (String url). That's basically what a "Lens" would consist of. So what would I have to do (if at all possible) to make it possible for other developers to create "Lenses" for my app? Ideally they would be able to distribute them in, for example, the Google Play Store, but if necessary I can develop my own platform where others could upload their lenses. Either way I'd still need some way to run someone else's code from within my app. A: If you can think of a better way (perhaps like what DashClock does) I'm all ears :) Design your API around IPC. Have third-party plugins implement a Service, a ContentProvider, and/or a BroadcastReceiver that your host app works with. While a bound service using AIDL would seem to be the most natural way of converting your existing API to one that uses IPC, bound services for plugins have all sorts of issues (e.g., API versioning) that are messy to deal with over time. In your own app, you might wrap the low-level IPC plumbing in some classes that resemble your existing API. And if you wanted to have third-party developers use some library that you publish to have them create their plugins, you're welcome to do that too. You'll want to create a few plugins yourself, to test out your API and provide samples for third-party developers. Given all of that, there are any number of ways that you can discover when plugins are installed and removed. ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED broadcasts, for example, can tell you when other apps are added and removed. You can then use PackageManager to see if they are one of your plugins (e.g., do they implement your IPC endpoint?). Or, use methods on PackageManager like queryIntentServices() to poll for plugin implementations, if that makes more sense. A: An actual app that uses plugins might give you ideas. Here is the plugin developer page of an app that uses them: http://www.twofortyfouram.com/developer
{ "language": "en", "url": "https://stackoverflow.com/questions/26977827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Play is showing wrong API level After uploading my APK in Google Play it shows in APK details : API levels : 14-17 and publicly showing "4.0 and up" in play store. Although my previous version has API levels 14+ but i changed my app and set following minSDK and targetSDK: <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="12" android:maxSdkVersion="17"/> But after uploading new APK GOOGLE PLAY is showing wrong API level. It shows "API levels : 14-17". I am tired about this fact. Why not it shows 11-17 and publicly "3.0 and up". Would anybody knows the real fact ?
{ "language": "en", "url": "https://stackoverflow.com/questions/17501745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: D8: Program type already present: com.MyCompany.Game.BuildConfig I get this error after i add GoogleMobileAds plugin into my project. I have shared codes of AndroidManifest.xml of GoogleMobileAds plugin. Can anyone please help ? (UnityEngine.GUIUtility:processEvent(Int32, IntPtr) (at C:/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:179)) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.MyCompany.Game" android:versionName="1.0" android:versionCode="1"> <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28" /> <application> <uses-library android:required="true" android:name="org.apache.http.legacy" /> <activity android:isGame="true" android:hardwareAccelerated="true" android:name="com.unity3d.player.UnityPlayerNativeActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="unityplayer.UnityActivity" android:value="true" /> <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" /> </activity> <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-1010101010101010~1010101010" /> </application> </manifest>
{ "language": "en", "url": "https://stackoverflow.com/questions/59334839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: For Azure Data Factories is there a way to 'Validate all' using powershell rather than the GUI? * *A working Azure Data Factory (ADF) exists that contains pipelines with activities that are dependent on database tables *The definition of a database table changes *The next time the pipeline runs it fails *Of course we can set up something so it fails gracefully but ... *I need to proactively execute a scheduled Powershell script that iterates through all ADFs (iterating is easy) to do the equivalent of the 'Validate All' (validating is impossible?) functionality that the GUI provides *I do realise that the Utopian CI/CD DevOps environment I dream about will one day in the next year or so achieve this via other ways *I need the automation validation method today - not in a year! I've looked at what I think are all of the powershell cmdlets available and short of somehow deleting and redeploying each ADF (fraught with danger) I can't find a simple method to validate an Azure Data Factory via Powershell. Thanks in advance A: In the ".Net" SDK, each of the models has a "Validate()" method. I have not yet found anything similar in the Powershell commands. In my experience, the (GUI) validation is not foolproof. Some things are only tested at runtime. A: I know it has been a while and you said you didn't want the validation to work in an year - but after a couple of years we finally have both the Validate all and Export ARM template features from the Data Factory user experience via a publicly available npm package @microsoft/azure-data-factory-utilities. The full guidance can be found on this documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/56160306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to delete a saved project in Advanced REST client standalone app? I'm trying to delete unused projects in ARC as they are stacking up. I couldn't find any setting related to this. I found deleting an API call in ARC standalone app(how to delete a saved request in chrome's arc (Advanced REST Client) extension?) but not for saved project A: I found it upon clicking kebab menu (vertical ellipsis) next to the project I want to delete and selected 'open details' and then there is 'delete project' button
{ "language": "en", "url": "https://stackoverflow.com/questions/56346295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to open specific web browsers using hyperlinks? I have a simple app which contains a link, I want on mobile apps eg LinkedIn people to click this link and open it in a browser eg safari I tried this <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' When I click this link it opens in a native LinkedIn app browser in iPhone what do I need to change to get this working? A: The browser that gets used is a user setting on the device based on what they have installed, not something you can control. Best you can do is recommend that it works best in Safarior or whichever browser. A: Excerpt from Quora: The short answer you can't specify that a specific browser will be opened by a hyperlink. If you are viewing a web page or an app or something that shows a hyperlink and you click on that link then the operating system will receive an event that indicates a hyperlink was launched. It will then look for the default browser, launch that browser and then pass the URL to the browser. You can change the default browser at any time but the operating system will only open that specify browser. If you were really determined you might be able to write multiple browser launcher browsers that you would register with the operating system. Then any time you clicked on a link your browser would launch and you could present yourself with a list of alternative browsers to open the link with. FYI Safari has an option to open the current web page in another browser. It is in menu bar near developer tools. A: you can configure the edge browser such way- but i couldnt found any solution for other browsers <a href="microsoft-edge:https://meed.audiencevideo.com">May open on edge</a>'
{ "language": "en", "url": "https://stackoverflow.com/questions/58221788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django: How to show the updated information on the page without reloading I am working in Djnago and I want to update the information without reloading the page. At first, I have used Ajax for post method so that the page should not reload after submitting the form, and it is working properly. Then I used Ajax for get method, and it is working too but to see the new information on the page, I have to refresh the page. The view.py file: def bfs_view(request): form = BFSForm(request.POST or None) if form.is_valid(): form.save() form = BFSForm() try: image_url_info = None num_states_explored = None final_solution = None text_file = open("BFS\outputs\maze.txt", "w") field_name = 'description' input_value = BFS.objects.latest('id') field_object = BFS._meta.get_field(field_name) field_value = field_object.value_from_object(input_value) field_string_value = str(field_value).split("\n") text_file.writelines(field_string_value) text_file.close() m = Maze("BFS\outputs\maze.txt") print("Maze:") m.print() print("Solving...") m.solve() print("States Explored:", m.num_explored) print("Solution:") m.print() image_url_info = "/../../../static/search/bfs/maze.png" num_states_explored = m.num_explored # final_solution = ''.join(m.end_result) final_solution = str(''.join(m.end_result)) print(''.join(m.end_result)) # BFS.objects.latest('id').delete() except: print("BFS ERROR: Error in the try session of BFS in view.py") context = { 'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored, 'solution': final_solution} return render(request, "BFS/bfs.html", context) def post_bfs_view(request): if request.method == "POST" and request.is_ajax(): bfs_view(request) return JsonResponse({"success":True}, status=200) return JsonResponse({"success":False}, status=400) def get_bfs_view(request): if request.method == "GET" and request.is_ajax(): try: image_url_info = None num_states_explored = None final_solution = None text_file = open("BFS\outputs\maze.txt", "w") field_name = 'description' input_value = BFS.objects.latest('id') field_object = BFS._meta.get_field(field_name) field_value = field_object.value_from_object(input_value) field_string_value = str(field_value).split("\n") text_file.writelines(field_string_value) text_file.close() m = Maze("BFS\outputs\maze.txt") m.print() m.solve() print("States Explored:", m.num_explored) print("Solution:") # final_solution = ''.join(m.end_result) final_solution = str(''.join(m.end_result)) print(''.join(m.end_result)) # bfs_view(request) # BFS.objects.latest('id').delete() bfs_view(request) except: print("BFS ERROR: Error in the try session of BFS in view.py") return HttpResponse(final_solution) The main bfs.html file: <form id = "contactForm" method='POST' >{% csrf_token %} {{ form.as_p }} <input type='submit' value='Search' class="submit-btn poppins"/> </form> <div onload="myFunction()"> <h1>"The value is: " <pre><span id="myText"></span></pre></h1> </div> The Ajax for post operation: <script type="text/javascript"> $(document).ready(function(){ $("#contactForm").submit(function(e){ // prevent from normal form behaviour e.preventDefault(); // serialize the form data var serializedData = $(this).serialize(); $.ajax({ type : 'POST', url : "{% url 'BFS:contact_submit' %}", data : serializedData, success : function(response){ //reset the form after successful submit $("#contactForm")[0].reset(); }, error : function(response){ console.log(response) } }); }); }); </script> The Ajax for get operation: <script> $.ajax({ url: "{% url 'BFS:get_user_info' %}", type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { var number = data; document.getElementById("myText").innerHTML = number; }, failure: function(data) { alert('Got an error dude'); } }); </script> The urls.py file: app_name = 'BFS' urlpatterns = [ path('bfs/', bfs_view), # path('ajax/get_user_info', get_bfs_view, name='get_user_info'), path('ajax/contact', post_bfs_view, name ='contact_submit'), path('ajax/get_user_info', get_bfs_view, name = 'get_user_info'), ] The models.py file: from django.db import models from django.urls import reverse # Create your models here. class BFS(models.Model): description = models.TextField(blank=True, null=True) def __str__(self): return self.description The forms.py file: from django import forms from .models import BFS class BFSForm(forms.ModelForm): description = forms.CharField( required=False, label=False, widget=forms.Textarea( attrs={ 'id': 'TA1', 'rows': '10vh', 'cols': '8vw', 'placeholder': 'Enter Your Map Here', 'class': 'textfield-style', 'style': 'max-width: 100%; max-height: 100%;outline: none; border: none; background-color: white; width: 100%; padding: 12px 20px; margin: 8px 0; box-sizing: border-box; font-size: 20px; spellcheck="false";', } ) ) class Meta: model = BFS fields = [ 'description' ] def __init__(self, *args, **kwargs): super(BFSForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs.update({ 'class': 'form-control'}) A: I'd suggest you wrapping what you have used to get the update in a function then do the function call after you hit the success method after submitting the form... In your js for example: $(document).ready(function(){ $("#contactForm").submit(function(e){ // prevent from normal form behaviour e.preventDefault(); // serialize the form data var serializedData = $(this).serialize(); $.ajax({ type : 'POST', url : "{% url 'BFS:contact_submit' %}", data : serializedData, success : function(response){ //reset the form after successful submit $("#contactForm")[0].reset(); // This will then call for the get request to update the id "myText" live_update(); }, error : function(response){ console.log(response) } }); }); function live_update(){ $.ajax({ url: "{% url 'BFS:get_user_info' %}", type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { var number = data; document.getElementById("myText").innerHTML = number; }, error: function() { alert('Got an error dude'); } }); } }); Also, for the success method within the live_update function... You could also use, success: function(data) { $("#myText").hide(); $("#myText").html(data); $("#myText").fadeIn(1000); }, That should give it a nice little fade in effect as it updates. :) A: This might be the time to introduce a frontend framework to your pipeline as it will make life easier to refresh pages upon DOM state changes. I had challenges myself trying to implement similar functionality with Django alone some years back until i introduced React Js. Here is something that could help you without learning another software altogether: Update DOM without reloading the page in Django However, you will notice that the marked answer there still uses Javascript i.e jQuery. So there is no denying the fact that you will need to implement javascript to achieve what you want. Which is why i mentioned React Js. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/68209153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bash running python inline in shell script still not working I am on Windows and using GitBash to run shell scripts in bash that run python scripts. I'm trying to run python inline in a bash shell script using the answer from How to execute Python inline from a bash shell. I'm using a specific python environment, and the path is defined with an alias. This is a file called .pyalias: alias mypython='C:/users/name/mypath/python.exe test.sh' This is a file called test.sh: # misc notes at top, like a docstring print("Hello") # real file will instead say myPyScript.py etc. Here is the problem: This is a file called main_run_all.sh: # misc notes at top, like a docstring shopt -s expand_aliases source ./.pyalias mypython test.sh mypython -c print("Hello Again") When I run sh main_run_all.sh, it prints "Hello" to the console (good, it is successfully running the test.sh script), but then it doesn't run the inline command, returning the following error: test.sh: line 8: syntax error near unexpected token `(' test.sh: line 8: `mypython -c print("Hello Again")' A: You need to put the python code in quotes so the shell doesn't try to parse it like shell code: mypython -c 'print("Hello Again")' # ..........^....................^ If you get python code that contains both double and single quotes, quoting can be a real pain. That's the point when you use a quoted here-doc: python <<'END_PYTHON' print("Hello") print('World') END_PYTHON
{ "language": "en", "url": "https://stackoverflow.com/questions/73573871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Code I have written for Burger, Coca and Salad price calculation doesn't work I have written a code to calculate Burger, Coca and Salad price. The code should return a number (or a factor) based on the number or each ordered item. I can't figure out which part of the code is not right. it doesn't work when I change the number of items. var BurgNum = document.getElementById('Bnum').value, CocNum = document.getElementById('Cnum').value, SalNum = document.getElementById('Snum').value, Totalprice; function getValue(n) { return n >= 2 && n < 5 ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1; } var XBurgNum = getValue(BurgNum); var XCocNum = getValue(CocNum); var XSalNum = getValue(SalNum); Totalprice = XBurgNum * 10 + XCocNum * 5 + XSalNum * 4 document.getElementById('price').value = Totalprice; <html> How many Burgers you want to order? <input type="number" id="Bnum" value="0" onchange="getValue(n);"></input> <br> How many Cocas you want to order? <input type="number" id="Cnum" value="0" onchange="getValue(n);"></input> <br> How many Salads you want to order? <input type="number" id="Snum" value="0" onchange="getValue(n);"></input> <br> Price: <input type="number" id="price" readonly="readonly"></input> </html> A: That is because you are not calling right statement on 'onchange' event. You just call the getVAlue(n) function which does nothing except return a value that you also use for var XBurgNum = getValue(BurgNum); var XCocNum = getValue(CocNum); var XSalNum = getValue(SalNum); But you are not updating the output on change event. A: You are calling a function onchange which returns a value, but does nothing with it. Instead, your onchange function can get the values needed for the calculation and update the price accordingly. var burg = document.getElementById('Bnum'), coc = document.getElementById('Cnum'), sal = document.getElementById('Snum'), totalPrice = 0; document.getElementById('price').value = totalPrice; var updatePrice = function() { var burgNum = burg.value, cocNum = coc.value, salNum = sal.value; var xNums = []; [burgNum, cocNum, salNum].forEach(function(n, i) { xNums[i] = (n >= 2 && n < 5) ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1; }); totalPrice = xNums[0]*10 + xNums[1]*5 + xNums[2]*4; document.getElementById('price').value = totalPrice; } How many Burgers do you want to order? <input type="number" id="Bnum" value ="0" onchange="updatePrice()"/><br> How many Cocas do you want to order? <input type="number" id="Cnum" value ="0" onchange="updatePrice()"/><br> How many Salads do you want to order? <input type="number" id="Snum" value="0" onchange="updatePrice()"/><br> Price: <input type="number" id="price" readonly="readonly"/> A: Try this, It will help you... function getValue(val) { var BurgNum = parseInt(document.getElementById('Bnum').value); var CocNum = parseInt(document.getElementById('Cnum').value); var SalNum = parseInt(document.getElementById('Snum').value); BurgNum = (BurgNum>=2 && BurgNum<5)?BurgNum*0.9:(BurgNum<2)?BurgNum:BurgNum-1; CocNum = (CocNum>=2 && CocNum<5)?CocNum*0.9:(CocNum<2)?CocNum:CocNum-1; SalNum = (SalNum>=2 && SalNum<5)?SalNum*0.9:(SalNum<2)?SalNum:SalNum-1; Totalprice = BurgNum*10 + CocNum*5 + SalNum*4; document.getElementById('price').value = (Totalprice>0 && Totalprice!=='NaN')?Totalprice:0; } <html> How many Burgers you want to order? <input type="number" id="Bnum" value ="0" onChange="getValue(this.value);"></input> <br> How many Cocas you want to order? <input type="number" id="Cnum" value ="0" onChange="getValue(this.value);"></input> <br> How many Salads you want to order? <input type="number" id="Snum" value="0" onChange="getValue(this.value);"></input> <br> Price: <input id="price" readonly="readonly"></input> </html> Happy Coding...
{ "language": "en", "url": "https://stackoverflow.com/questions/45205033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compare integers by using for loop I'm python newbie and got a problem while doing some practices. Below is the code that I've got so far: def gt(nums, n): for c in nums: if n < c: return True elif c < n: return False else: break With above code, it does not return properly. The examples of correct answers here: gt([1,2,3],3) => False gt([1,2,3],2) => True A: A simpler and more readable solution would be the following: def gt(lst, n): return max(lst) > n A: using a one liner def gt(nums, n): return any(e > n for e in nums) this breaks when the first element bigger than n is found. A: Long-ish response to Niklas B.'s comment: I decided to test this, and here are the results. Blue dots are your function, green are Mario's; y axis is runtime in seconds, x axis is len(nums). As you said, both are O(n). Yours is faster up to about 45 items; for anything over 100 items, his is roughly twice as fast. It's mostly irrelevant - this seems to be more of a beginner syntax question than anything else - and, as you say, Python isn't a speed demon to begin with. On the other hand, who doesn't like a bit more speed (so long as readability doesn't suffer)? For those interested, here's the code I wrote to test this: from random import randint from timeit import Timer import matplotlib.pyplot as plt def gt1(nums, n): # based on Niklas B.'s answer - NOTE comparison is corrected return n < max(nums) def gt2(nums, n): # based on Mario Fernandez's answer return any(e > n for e in nums) def make_data(length, lo=0, hi=None): if hi is None: hi = lo + length - 1 elif lo > hi: lo,hi = hi,lo return [randint(lo, hi) for i in xrange(length)] def make_args(d): nums = make_data(d) n = randint(0,d) return "{}, {}".format(nums, n) def time_functions(fns, domain, make_args, reps=10, number=10): fns = [fn.__name__ if callable(fn) else fn for fn in fns] data = [[] for fn in fns] for d in domain: for r in xrange(reps): args = make_args(d) for i,fn in enumerate(fns): timer = Timer( setup='from __main__ import {}'.format(fn), stmt='{}({})'.format(fn, make_args(d)) ) data[i].extend((d,res) for res in timer.repeat(number=number)) return data def plot_data(data, formats=None): fig = plt.figure() ax = fig.add_subplot(111) if formats is None: for d in data: ax.plot([x for x,y in d], [y for x,y in d]) else: for d,f in zip(data, formats): ax.plot([x for x,y in d], [y for x,y in d], f) plt.show() def main(): data = time_functions([gt1, gt2], xrange(10, 501, 10), make_args) plot_data(data, ['bo', 'g.']) if __name__=="__main__": main() A: This could be better def gt(nums, n): for c in nums: if n < c: return True return False
{ "language": "en", "url": "https://stackoverflow.com/questions/12026747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I give an interval for a react application I am using react with antd framework. I have created a form and handling the submit: My forms.js: import React from 'react'; import { Form, Input, Button, notification } from 'antd'; import axios from 'axios'; class CustomForm extends React.Component { handleFormSubmit = (event, requestType, articleId) => { const title = event.target.elements.title.value; const content = event.target.elements.content.value; notification.open({ message: 'Success', description: 'Your Response is submitted', onClick: () => { console.log('Notification Clicked!'); }, onCancel: () => { } }); // eslint-disable-next-line switch (requestType) { case 'post': return axios.post('http://localhost:8000/api/', { title:title, content:content } ) .then (res => console.log(res)) .catch(err => console.error(err)) case 'put': return axios.put(`http://localhost:8000/api/${articleId}/`, { title:title, content:content }) .then (res => console.log(res)) .catch(err => console.error(err)) } } render(){ return ( <div> <Form onSubmitCapture={(event) => this.handleFormSubmit(event, this.props.requestType, this.props.articleId)} > <Form.Item label="Title"> <Input name='title' placeholder="Input some title" /> </Form.Item> <Form.Item label="Content"> <Input name='content' placeholder="Input some content" /> </Form.Item> <Form.Item> <Button type="primary" htmlType='submit' >{this.props.btntext}</Button> </Form.Item> </Form> </div> ) } }; export default CustomForm; Using this I can get input from the user and show a success notification. But I want to reload my page after 5 seconds when I get the notification when I try to use this code window.location.reload(true) in my handleFormSubmit it is not allowing the notification to take place. A: You can use setTimeout(() => window.location.reload(true), 5000); this code
{ "language": "en", "url": "https://stackoverflow.com/questions/63487401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: There is any way to encapsulate a SOAP object using WebClient framework? <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <ns1:Security xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0"> <ns1:UsernameToken> <ns1:Username>XXXXX</ns1:Username> <ns1:Password>XXXXXX</ns1:Password> </ns1:UsernameToken> </ns1:Security> </soapenv:Header> <soapenv:Body> <consultarPosicaoCotistaOnOfflineFundoRequest> <filtro> <cdCotista>2780008158</cdCotista> <icSnUltimaPosicao>S</icSnUltimaPosicao> <ictpSaldo>F</ictpSaldo> </filtro> </consultarPosicaoCotistaOnOfflineFundoRequest> </soapenv:Body> </soapenv:Envelope> I am trying to consume a webservice and I need to send in the body of my request this soap object above ... but I got this error below: Content type 'text/xml;charset=UTF-8' not supported for bodyType=com.sun.xml.messaging.saaj.soap.ver1_1.Message1_1Impl And that's the function I am trying to use: Mono<String> monoResponse = webClient() .post() .header("SOAPAction", "") .header("User-Agent", "Apache-HttpClient/4.5.5 (Java/12.0.1)") .header("Content-Type", "text/xml;charset=UTF-8") .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .acceptCharset(Charset.forName("UTF-8")) .bodyValue(soapMessage) .retrieve() .bodyToMono(String.class); monoResponse.block(); By any chance Do I can send this object through this way?! A: The namespace https://www.w3.org/2003/05/soap-envelope/ is SOAP 1.2, for which the correct content-type is application/soap+xml. Try changing the specified content type to this value. Content type text/xml is correct for SOAP 1.1.
{ "language": "en", "url": "https://stackoverflow.com/questions/68275855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get value of INT for a "STRING" variable I need output like 0 - os.O_APPEND - 1024 1 - os.O_CREATE - 64 2 - os.O_EXCL - 128 3 - os.O_RDONLY - 0 4 - os.O_RDWR - 2 5 - os.O_SYNC - 1052672 6 - os.O_TRUNC - 512 7 - os.O_WRONLY - 1 I am able to to do half of it with func main() { a := []int{os.O_APPEND,os.O_CREATE,os.O_EXCL,os.O_RDONLY,os.O_RDWR,os.O_SYNC,os.O_TRUNC,os.O_WRONLY} for index, value := range a { fmt.Printf("%d - - %d\n", index, value) } } which gave me output 0 - - 1024 1 - - 64 2 - - 128 3 - - 0 4 - - 2 5 - - 1052672 6 - - 512 7 - - 1 and the other half of it with func main() { a := []string{"os.O_APPEND","os.O_CREATE","os.O_EXCL","os.O_RDONLY","os.O_RDWR","os.O_SYNC","os.O_TRUNC","os.O_WRONLY"} for index, value := range a { fmt.Printf("%d - %-15s -\n", index, value) } } which gave me the output 0 - os.O_APPEND - 1 - os.O_CREATE - 2 - os.O_EXCL - 3 - os.O_RDONLY - 4 - os.O_RDWR - 5 - os.O_SYNC - 6 - os.O_TRUNC - 7 - os.O_WRONLY - How can I get the desired output ? Update As I'm thinking about it, I'm getting an idea for solving it with an array of empty interface and then type asserting on each element of the array of empty interface, once with string to get the string, and once with int to get the value of int, but I don't know how to do that. A: you could use map. func main() { var m map[string]int m = make(map[string]int) b := []int{os.O_APPEND,os.O_CREATE,os.O_EXCL,os.O_RDONLY,os.O_RDWR,os.O_SYNC,os.O_TRUNC,os.O_WRONLY} a := []string{"os.O_APPEND","os.O_CREATE","os.O_EXCL","os.O_RDONLY","os.O_RDWR","os.O_SYNC","os.O_TRUNC","os.O_WRONLY"} for index, value := range a { m[value] = b[index] } var i =0 for index,mapValue := range m{ fmt.Println(i," - ",index,"-",mapValue ) i++ } } out put will be: 0 - os.O_RDWR - 2 1 - os.O_SYNC - 1052672 2 - os.O_TRUNC - 512 3 - os.O_WRONLY - 1 4 - os.O_APPEND - 1024 5 - os.O_CREATE - 64 6 - os.O_EXCL - 128 7 - os.O_RDONLY - 0 or you could define custom struct type CustomClass struct { StringValue string IntValue int } func main() { CustomArray:=[]CustomClass{ {"os.O_APPEND",os.O_APPEND}, {"os.O_CREATE",os.O_CREATE}, {"os.O_EXCL",os.O_EXCL}, {"os.O_RDONLY",os.O_RDONLY}, {"os.O_RDWR",os.O_RDWR}, {"os.O_SYNC",os.O_SYNC}, {"os.O_TRUNC",os.O_TRUNC}, {"os.O_WRONLY",os.O_WRONLY}, } for k, v := range CustomArray { fmt.Println(k," - ", v.StringValue," - ", v.IntValue) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/56619323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JavaScript: shorthand for conditionally adding something to an array I am writing a Mocha test for a server at work. I get two potential phone numbers for a customer, at least one of which will be defined. var homePhone = result.homePhone; var altPhone = result.altPhone; I want to use underscore's _.sample function to pick one of these at random. However, one of them may be undefined. So what I was thinking was something like: //pseudocode var phone = _.sample([homephone || (doNothing), altphone || (doNothing)]); the _.sample function looks like this: http://underscorejs.org/#sample the problem of course, is there is no shorthand syntax that I know of to conditionally add something to an array. The verbose way to do what I want is: var phoneArray = []; if(homePhone){ phoneArray.push(homePhone); } if(altPhone){ phoneArray.push(homePhone); } var phoneSelection = _.sample(phoneArray); is there a more elegant way to do this in JavaScript? A: You could use .filter: _.sample([homephone, altphone].filter(_.identity)) Another way would be: _.sample([homephone, altphone]) || homephone || altphone; A: What about: var phone = (homephone && altphone)? _.sample([homephone, altphone]) : (homephone || altphone); A: Since you're already using underscore, I would suggest leveraging compact: var phone = _.sample(_.compact([homephone, altphone])); This is basically a shortened version of dave's answer, since compact is literally implemented as function(array) { return _.filter(array, _.identity); }. A: Array literals in JavaScript: [ 1, 2, 3 ] ...are a way to statically declare which things go in which positions in an array. In other words, when you write the code, you already know where things will go. In your scenario, the positions are only known dynamically. In other words, you don't know where they'll go until you run the program on a given set of inputs. So basically what you're asking for is impossible, barring any radical changes to how array literals work in future versions of JS. However, if all you want is to save typing, @dave's answer is pretty nice. I'm mainly just clarifying that array literals by themselves don't have this capability.
{ "language": "en", "url": "https://stackoverflow.com/questions/32215178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Consul KV data store http api write acquire lock and release session I'm using this command to store key value using session lock in Consul data store. curl -X PUT -d 300 http://10.0.0.10:8500/v1/kv/my-key-value?acquire=$session How can I release the lock acquired and can I do so in the same command line? A: consul kv put -release -session=sessionid my-key-value
{ "language": "en", "url": "https://stackoverflow.com/questions/53599239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Style Listviews Selector.SelectedItem I have ListView with SelectionMode=extended and style for ListViewItem thus: MainWindow.xaml: <Window x:Class="ListViewSelection.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type ListViewItem}"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Aqua"/> </Style.Resources> <!--<Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="Aqua" /> </Trigger> </Style.Triggers>--> </Style> </Window.Resources> <StackPanel> <ListView Name="MyListView" ItemsSource="{Binding MyList}" SelectionChanged="SelectionChanged" SelectionMode="Extended" /> <Label Name="MyLabel" /> </StackPanel> </Window> MainWindow.xaml.cs: using System.Windows; using System.Windows.Controls; using System.Collections.ObjectModel; namespace ListViewSelection { public partial class MainWindow : Window { public ObservableCollection<string> MyList { get; set; } public MainWindow() { InitializeComponent(); this.DataContext = this; MyList = new ObservableCollection<string>(); MyList.Add("Jane"); MyList.Add("Paul"); MyList.Add("Sally"); MyList.Add("Ian"); } private void SelectionChanged(object sender, SelectionChangedEventArgs e) { MyLabel.Content = (sender as ListBox).SelectedItem; } } } This sets the color fine for all selected items. But I need to also style the Selector.SelectedItem, which is the 'active' or first item in the selection. This is the one that the label displays. Any help? Thanks! A: You could expose IsFirstInSelection property in your ViewData class (I suppose you have it). Then you could place DataTrigger for monitoring changes like this: <Style.Triggers> <DataTrigger Binding="{Binding IsFirstInSelection}"> <Setter Property="Background" Value="Blue"/> </DataTrigger> </Style.Triggers> Also in your case I'd recommend to avoid changing HighlightBrushKey, but achieve your goal via changing Background property. You could also expose IsSelected property in ViewData class, so it looks this: public class ViewData: ObservableObject { private bool _isSelected; public bool IsSelected { get { return this._isSelected; } set { if (this._isSelected != value) { this._isSelected = value; this.OnPropertyChanged("IsSelected"); } } } private bool _isFirstInSelection; public bool IsFirstInSelection { get { return this._isFirstInSelection; } set { if (this._isFirstInSelection != value) { this._isFirstInSelection = value; this.OnPropertyChanged("IsFirstInSelection"); } } } } And your style sets Background based on both properties: <Style x:Key="TreeItemStyle" TargetType="{x:Type TreeViewItem}"> <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/> <Setter Property="IsFirstInSelection" Value="{Binding Path=IsFirstInSelection}"/> <Setter Property="Background" Value="Green"/> <Style.Triggers> <DataTrigger Binding="{Binding IsSelected}" Value="True"> <Setter Property="Background" Value="Red"/> </DataTrigger> <DataTrigger Binding="{Binding IsFirstInSelection}"> <Setter Property="Background" Value="Blue"/> </DataTrigger> </Style.Triggers> </Style> Of course in model or in view code behind you should monitor IsSelected property changed notifications and set/reset IsFirstInSelection according to selected items. I hope you understand my idea. ------- EDITED -------- At first I continue to insist that you should develop proper ViewData class: public class ViewData : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var ev = this.PropertyChanged; if (ev != null) { ev(this, new PropertyChangedEventArgs(propertyName)); } } public ViewData(string name) { this._personName = name; } private string _personName; public string PersonName { get { return this._personName; } set { if (this._personName != value) { this._personName = value; this.OnPropertyChanged("PersonName"); } } } private bool _isFirstSelected; public bool IsFirstSelected { get { return this._isFirstSelected; } set { if (this._isFirstSelected != value) { this._isFirstSelected = value; this.OnPropertyChanged("IsFirstSelected"); } } } } During handling SelectionChanged event you should modify property IsFirstSelected like this: public ObservableCollection<ViewData> MyList { get; set; } private void SelectionChanged(object sender, SelectionChangedEventArgs e) { var lb = sender as ListBox; if (lb != null) { MyLabel.Content = lb.SelectedItem; foreach (var item in this.MyList) { if (item == lb.SelectedItem) { item.IsFirstSelected = true; } else { item.IsFirstSelected = false; } } } } But default ListViewItem template doesn't react on Background setters so you should override its template in style: <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListViewItem"> <Grid Background="{TemplateBinding Background}"> <ContentPresenter Content="{Binding PersonName}"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="Yellow"/> </Trigger> <DataTrigger Binding="{Binding IsFirstSelected}" Value="True"> <Setter Property="Background" Value="Aqua" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> If this solution isn't acceptable, please tell me. I've some ideas but have no enough time to check them in code right now.
{ "language": "en", "url": "https://stackoverflow.com/questions/4825418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: convert HTML code from page source to regular page source - PHP I have a web page, that include another web page source. It looks like <html> .... <div id="content"> {"note":"\n<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<!--[if IE 9]>\n\t\t\t<script src=\"\/js\/PIE\/PIE_IE9.js\"><\/script>\n\t\t\t<link rel=\"stylesheet\"... </div> so I have a string like <!DOCTYPE html>\n<html>\n\t<head>\n\t\t<!--[if IE 9]>\n\t\t\t<script src=\"\/js\/PIE\/PIE_IE9.js\"><\/script>\n\t\t\t<link rel=\"stylesheet\"... and I would like to get <!DOCTYPE html><html><head><!--[if IE 9]><script src="\js\PIE\PIE_IE9.js"></script><link rel="stylesheet". Is there any PHP function that can remove this special chars like" \n, \t, \"... I just need a regular HTML code. Sorry for my english A: As has been pointed out, there are better ways to do this, however: $string = "<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<!--[if IE 9]>\n\t\t\t<script src=\"\/js\/PIE\/PIE_IE9.js\"><\/script>\n\t\t\t<link rel=\"stylesheet\""; echo preg_replace('/\r|\n|\t|\\\/', '', $string); this will replace the special chars \n, \t, \r and \
{ "language": "en", "url": "https://stackoverflow.com/questions/21981293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Could not find a valid gem install activerecord-sqlite3-adapter I'm a beginner to Ruby. I follow the steps on http://rubyonrails.org/download and installed Ruby on rails and created a project called "Blog" by following the youtube tutorial. http://www.youtube.com/watch?v=UQ8_VOGj5H8 But whenever I used the command rails s, it will give an error: C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.3.5/lib/bundler/rubygems_integ ration.rb:214:in `block in replace_gem': Please install the sqlite3 adapter: `ge m install activerecord-sqlite3-adapter` (sqlite3 is not part of the bundle. Add it to Gemfile.) (LoadError) This is happening to both of my laptop and PC, both are using Windows 7. I tried to run the command gem install activerecord-sqlite3-adapter, but then I gives me the error. C:\Users\Ouye\blog>gem install activerecord-sqlite3-adapter ERROR: Could not find a valid gem 'activerecord-sqlite3-adapter' (>= 0) in any repository ERROR: Possible alternatives: activerecord-jdbcsqlite3-adapter, activerecord-sq lserver-adapter, activerecord-bq-adapter, activerecord-simpledb-adapter, activer ecord-mysql2-adapter I tried all of the alternatives above and update my bundle install, some of the alternatives works and some don't. After I tried all of the alternatives above and run "rails s", I still get the same error of telling me to install sqlite3 adapter. This is what my gem file looks like source 'https://rubygems.org' gem 'rails', '3.2.13' gem 'sqlite3' group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' gem 'uglifier', '>= 1.0.3' end gem 'jquery-rails' And this is all bundles in the gem Gems included by the bundle: actionmailer (3.2.13) actionpack (3.2.13) activemodel (3.2.13) activerecord (3.2.13) activeresource (3.2.13) activesupport (3.2.13) arel (3.0.2) builder (3.0.4) bundler (1.3.5) coffee-rails (3.2.2) coffee-script (2.2.0) coffee-script-source (1.6.2) erubis (2.7.0) execjs (1.4.0) hike (1.2.2) i18n (0.6.1) journey (1.0.4) jquery-rails (2.2.1) json (1.7.7) mail (2.5.3) mime-types (1.23) multi_json (1.7.3) polyglot (0.3.3) rack (1.4.5) rack-cache (1.2) rack-ssl (1.3.3) rack-test (0.6.2) rails (3.2.13) railties (3.2.13) rake (10.0.4) rdoc (3.12.2) sass (3.2.9) sass-rails (3.2.6) sprockets (2.2.2) thor (0.18.1) tilt (1.4.1) treetop (1.4.12) tzinfo (0.3.37) I would be very grateful if anyone can solve my problem. A: I had the same issue as you are presenting, and after a lot of trial and error, i found some simple steps to fix it. First, add to your Gemfile: gem 'sqlite3', '1.3.5' Then run in your console: bundle install And then you should proceed normally A: Ruby 2.0 has problems with sqlite3 and can't run. If you need to use sqlite3 you'll have to downgrade to 1.9.3. I don't have the link to the documentation about this, but I know if you downgrade to 1.9.3 you'll be fine. I'll see if I can find the link. A: You cannot install activerecord-sqlite3-adapter as a gem, because this adapter is included with ActiveRecord already. The problem is not in activerecord-sqlite3-adapter, but in that you don't have sqlite3 as part of your Gem bundle (the error message tells us this at the end: "sqlite3 is not part of the bundle.") To fix it, add it to your Gemfile first: # in your Gemfile gem 'sqlite3' then run from command line: $ bundle install Ensure that sqlite3 installs correctly and shows up in your Gem bundle, and everything should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/16512908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: From text to formula I wan't to create a formula as a textstring from dynamically updated cells with a content of references to ranges in different sheets. This textstring needs then to be converted into a formula in another sheet. I guess I would be able to use the Evaluate function in excel. But in google spreadsheet this shouldn't work. the textstring looks like this: FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0) and more filter references can be added. {FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0);FILTER(DBDold!B2:F;LÆNGDE(DBDold!B2:B)>0);....} As for now I've mannaged to get the code right with a script and the formula seems to be generated right. But it won't do the calculation until I manually either put in a space at the end or in other way make a change to the formular. function addFormula(){ var formula = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Stamdata").getRange('E5').getValue(); var samlet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Samlet").getRange('B2'); var range = SpreadsheetApp.getActiveRange(); samlet.setFormula(formula); } Stamdata!E5 is: FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0) (LÆNGDE=LEN in english) In Samlet!B2 is created the formula =FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0) just as it should - but the result is #I/T (Fejl FILTER har forskellige intervalstørrelser. Forventede 249 rækker og 1 kolonner, men indeholder 1 rækker og 1 kolonner. = in english something like FILTER has different size. Expected 249 rows og 1 column, but has 1 row and 1 column.) If I in Samlet!B2 at the end of the new generated formula puts in a space everything is calculated correct. I've then tried to make a simple formula in Stamdata!E5 like 3*3. Then the formula is created and calculated without any manually 'intervention'. A: Simple solution: The formula needs to be a string that includes an "equals" (=) prefix. Cell E5 presently contains a formula (=E4) which yields: {FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0);FILTER(Platformen!B2:F;LÆNGDE(Platformen!B2:B)>0) Two things to note here: 1) the content is treated as text 2) there is no "equals sign" (=) at the beginning of the string. The content should look like this: ={FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0);FILTER(Platformen!B2:F;LÆNGDE(Platformen!B2:B)>0) How to fix it Edit Cell E5 (or Cell E4, whichever suits you) to insert an equals sign (=) to the left of the opening curly bracket. The result will still be treated as a string, so there is no danger involved ;) One proviso: I had to convert "LÆNGDE" to "LEN" in order for my test to work. But I think this is probably just an issue of "Display Language" which, for me, is English (Australia), and for you is probably Danish.
{ "language": "en", "url": "https://stackoverflow.com/questions/54731819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MSVC 2008 Immediate Window nonsense and some code confusion I've been fooling with the MSVC 2008 immediate window for the last few hours and I'm flabbergasted with both myself and Microsoft... It probably doesn't help that I stumbled on this mystery at bedtime and it's now 6 hours later. :) Please see the following: ? "1234567\\87654321\\" CXX0026: Error: bad format string I've tried the above several ways in the immediate window and... Nothing. No amount of backslashes gets rid of the error. Removing the backslashes is the only way to solve it. Does the expression evaluator have something against double backslash in a wide string? For what it's worth, the immediate window fooling was motivated by the following: Line 107 is: size_t endpos = str.find_last_not_of( L”\\/” ); file.cpp(107) : error C2017: illegal escape sequence file.cpp(107) : error C2017: illegal escape sequence file.cpp(107) : error C2065: 'L”' : undeclared identifier file.cpp(107) : error C2065: '”' : undeclared identifier My questions are: *What's up with the 4 errors on line 107? *What's up with the immediate window? I remember this kind of thing working there a year or so ago. I applied a service pack to MSVC 2008 about 6 months ago but I didn't use it heavily until now. A: size_t endpos = str.find_last_not_of( L”\\/” ); // no size_t endpos = str.find_last_not_of( L"\\/" ); // yes Beware of code that you copied off a website, maybe a blog post. The author may well have used a word processor, one that implements 'smart quotes'. If you look closely at the first and the second line you'll see the difference. Your compiler will only like the straight double-quotes. It doesn't quite explain your problem with the Immediate Window, it works when I try your string as shown. Maybe it doesn't quite look like it either.
{ "language": "en", "url": "https://stackoverflow.com/questions/4806567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: %s not working properly with my return value, in C As the title says %s is not working properly This is for a code wars so %s needs to be able to work with the array to pass the sample test cases; Cannot change function declaration of playPass. Using Ascii table. Also the for loop to print in main() works and gives me correct output. #include <stdio.h> #include <string.h> #include <stdlib.h> // takes a string and shifts letter n value; // lower cases every other element if it contains a letter // replaces number with a 9 complement // returns array with values reversed. char* playPass(char* s, int n) { int length = strlen(s); char *pass= (char *)malloc(length*sizeof(char)+1); char a; int letter, i; for(i=0; i< length; i++) { a = s[i]; letter = a; if( letter >= 65 && letter <=90 ) { letter +=n; if(letter >90) { letter -=90; letter +=64; } if((i+1) % 2 == 0 ) { letter += 32; } a = letter; } else if(letter >= 48 && letter <= 57) { letter -= 48; letter = 9 - letter; a = letter + '0'; } pass[length - i] = a; } return pass; } // answer should be int main (){ char* s ={"I LOVE YOU!!!"}; int length = strlen(s); int k = 1; s =playPass( s,k ); int i; printf(" %s", s); for(i = 0; i <= length; i++) { printf(" %c", s[i]); } } A: %s works only with null terminated char * char* playPass(char* s, int n) { … for() { … } pass[i] = '\0'; //Null terminate here. return pass; } A: so figured it out. the end where i assined the new value to the new array pass[length - i] = a; made it to where it never wrote a value to the first element so pass[0]= NULL; had to change it to pass[length - (i-1)] = a; thanks for the help everyone, I also cleaned up the code from the magic numbers Great tip @phuclv!
{ "language": "en", "url": "https://stackoverflow.com/questions/58926774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery dynamic created input sum and subtract on select option i'm working with jquery and need help to calculate the values of input depended on select option inserted dynamically. i want if select value is debit it will subtract from selected credit value and difference show in id diff as i inserted more ows all values calculate by debit and credit. <table class="vtable"> <tr> <td>Type</td> <td>Amount</td> </tr> <tr> <td> <select name="type" id="type"> <option>-type -</option> <option value="debit">debit</option> <option value="credit">credit</option> </select> </td> <td><input type="text" id="amount"></td> </tr> </table> My fiddle demo is below Demo Thanks A: DEMO Try this $(document).on('change', 'select', function () { var value = $(this).val(); var input = $(this).parents('td').next('td').find('input:text'); if (value == 'debit') { total -= parseInt(input.val()); } else if (value == 'credit') { total += parseInt(input.val()); } $('#diff').html('Differance:' + total); }); Hope this helps,Thank you A: $('select#type').on('change', function() { if($(this).val() === "debit"){ //Get the difference between 2 variables and store result in diff $("#diff").val(Math.abs(a - b)) }else if($(this).val() === "credit"){ //perform addition and store value in sum object $("#sum").val(x+y) } }); A: what about something like this? $('select[name="type"]').change(function() { if($(this).val() === 'credit') { $("#amount").val() += $('input[type="text"]').val() } else if($(this).val() === 'debit') { $("#amount").val() -= $('input[type="text"]').val() } }) I use the the change() function to trigger the change. I don't know if this is what you meant, but i hope it helped somehow. A: one issue corrected in more button click handlers. see the changes below: $("#more").click(function() { $(".vtable tr:last").clone().find("input, select").each(function() { $(this).attr({'id': function(_, id) { return id + 1 }}); }).end().appendTo(".vtable"); }); in order to handle the events for dynamically added select and input text, you can achieve it as follows. Note: .on() is used with your table as your are adding rows dynamically with select and input text. for select : $('.vtable').on('change', "select", function (e) { var valueSelected = this.value; alert(valueSelected); }); for input text $('.vtable').on('keyup', "input", function (e) { var valueEntered = this.value; alert(valueEntered ); });
{ "language": "en", "url": "https://stackoverflow.com/questions/19155632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to enable multiple Server.log(s) in Azerothcore I want to enable multiple Server.log so I can see what happened with the server before it restarted. What I mean is: saving separate Server.log files every time the server restarts, instead of rewriting the same file. A: The solution is enabling LogTimestamp in the worldserver.conf, which will make the core save every Server.log file with a different datetime in the file name, so you can check what happened. https://github.com/azerothcore/azerothcore-wotlk/blob/master/src/server/worldserver/worldserver.conf.dist#L451
{ "language": "en", "url": "https://stackoverflow.com/questions/56612159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Need a unity3d swarm generator script I'm trying to make a simple game where lots of flying and walking insects attack a player, and he has to shoot like mad to stay alive. I want them to attack together in varying attack patterns as group, like a swarm of bees, or like the way jet fighters attack in formation. Does anybody know of any script out there or something in the asset store that can do it? I saw this one at the link below, but i'm not sure if it can do the job as i cant get any response from the author. https://www.assetstore.unity3d.com/en/#!/content/40529 Has some live demos. anybody has any ideas? A: This reddit post links to a KvantSwarm which may be one way to approach it. You may also want to take a look at their flocking wiki for some code that you can drop in and test right away. Infrared5 posted a blog on swarming done for an aerial dogfight.
{ "language": "en", "url": "https://stackoverflow.com/questions/35466046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to make site show always in Portrait orientation? I'm doing a mobile site, and i need it to show screen as it always was in portrait orientation. Like Instagram app. works. How could i do this with codes ? if (window.orientation === 90 || window.orientation === -90) { window.orientation=0; } A: Not a good idea in general but you can find discussion here : Blocking device rotation on mobile web pages How do I lock the orientation to portrait mode in a iPhone Web Application? a solution could be to rotate the content using CSS3 on orientation change event.
{ "language": "en", "url": "https://stackoverflow.com/questions/24720583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LightInject Registration of Generic Query Handler I am pretty new to the CQRS pattern and am having issues tying all of this together with my dependency injection container of choice.(LightInject) What I have is a generic query object public interface IQuery<TResult> { } which is implemented by the GenericQuery public class GenericQuery<TSrcEntity> : IQuery<IEnumerable<TSrcEntity>> { public Expression<Func<TSrcEntity, bool>> Filter { get; set; } public Func<IQueryable<TSrcEntity>, IOrderedQueryable<TSrcEntity>> OrderBy { get; set; } public IEnumerable<string> IncludeProperties { get; set; } } I then handle all of this by way of a Query Dispatcher, which determines which handler to use through the dependency resolver public class QueryDispatcher:IQueryDispatcher { public TResult Dispatch<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult> { var handler = DependencyResolver.Get<IQueryHandler<TQuery,TResult>>(); return handler.Retreive(query); } } the Handler Implementation public class GenericQueryHandler<TSrcEntity> : IQueryHandler<GenericQuery<TSrcEntity>, IEnumerable<TSrcEntity>> where TSrcEntity : class { public IEnumerable<TSrcEntity> Retreive(GenericQuery<TSrcEntity> query) { return GetDocuments(); } My registration for LightInject looks like this class Program { static void Main(string[] args) { var container = new ServiceContainer(); //service container.Register<ITestService, TestService>(); //query container.Register(typeof(IQuery<>), typeof(GenericQuery<>)); //handler This one works, but I dont want to register everything explicity. container.Register(typeof(IQueryHandler<GenericQuery<Document>, IEnumerable<Document>>), typeof(GenericQueryHandler<Document>)); //dispatcher container.Register<IQueryDispatcher, QueryDispatcher>(); DependencyResolver.SetResolver(container); var service = container.GetInstance<ITestService>(); var a = service.GetDocuments(); } Everything is smooth as long as I explicitly register my handler as seen here //handler This one works, but I dont want to register everything explicity. container.Register(typeof(IQueryHandler<GenericQuery<Document>, IEnumerable<Document>>), typeof(GenericQueryHandler<Document>)); But I don't want to do this for each entity. Can someone who is more familiar with LightInject help? A sample program can be found at Generic Query Problem Thanks A: I know this is an old post, but I had the same problem and I found a solution. I found the solution here: https://github.com/seesharper/LightInject/issues/350 The code on that page is this: public static class ContainerExtensions { public static void RegisterCommandHandlers(this IServiceRegistry serviceRegistry) { var commandTypes = Assembly.GetCallingAssembly() .GetTypes() .Select(t => GetGenericInterface(t, typeof(ICommandHandler<>))) .Where(m => m != null); RegisterHandlers(serviceRegistry, commandTypes); serviceRegistry.Register<ICommandExecutor>(factory => new CommandExecutor((IServiceFactory)serviceRegistry)); serviceRegistry.Decorate(typeof(ICommandHandler<>), typeof(TransactionalCommandDecorator<>)); } public static void RegisterQueryHandlers(this IServiceRegistry serviceRegistry) { var commandTypes = Assembly.GetCallingAssembly() .GetTypes() .Select(t => GetGenericInterface(t, typeof(IQueryHandler<,>))) .Where(m => m != null); RegisterHandlers(serviceRegistry, commandTypes); serviceRegistry.Register<IQueryExecutor>(factory => new QueryExecutor((IServiceFactory)serviceRegistry)); serviceRegistry.Decorate(typeof(IQueryHandler<,>), typeof(QueryHandlerLogDecorator<,>)); } private static Tuple<Type, Type> GetGenericInterface(Type type, Type genericTypeDefinition) { var closedGenericInterface = type.GetInterfaces() .SingleOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == genericTypeDefinition); if (closedGenericInterface != null) { var constructor = type.GetConstructors().FirstOrDefault(); if (constructor != null) { var isDecorator = constructor.GetParameters().Select(p => p.ParameterType).Contains(closedGenericInterface); if (!isDecorator) { return Tuple.Create(closedGenericInterface, type); } } } return null; } private static void RegisterHandlers(IServiceRegistry registry, IEnumerable<Tuple<Type, Type>> handlers) { foreach (var handler in handlers) { registry.Register(handler.Item1, handler.Item2); } } } Hope it can help someone else too :) Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/29977733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to connect to db using jndi and only through xml files not through InitialContext Please guide me on this ?? As I have already worked on private void initializeDataSource() throws SystemException { // set up the parameters for the data source to be used by the // connection factory try { ctx = new InitialContext(); if (ctx == null) throw new SystemException("Unable to get Initial Context"); this.dataSource = (DataSource) ctx.lookup("java:/dbname); } catch (NamingException ne) { throw new SystemException(ne); }
{ "language": "en", "url": "https://stackoverflow.com/questions/45504615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get previous year start month/date and end month/date How can i get the previous year start date/month and end date/month Below is the code, i have tried, but its not working... var lastyear = new Date(new Date().getFullYear(), 0, 1); lastyear.setFullYear(lastyear.getFullYear() - 1); var start = (new Date(lastyear, 0, 1)).getTime(), end = (new Date(lastyear, 11, 31)).getTime(); Technically i want 01/01/2015 to 12/31/2015. What is the mistake i am doing here? A: You ran into issues because the you were using the Date() constructor incorrectly. According to http://www.w3schools.com/js/js_dates.asp, the Date constructor accepts the following inputs: new Date(year, month, day, hours, minutes, seconds, milliseconds) In your original code, you were passing a Date object into the "year" argument. I changed: new Date(lastyear, 0, 1) to new Date(lastyear.getFullYear(), 0, 1) which fixed the problem. var lastyear = new Date(new Date().getFullYear() - 1, 0, 1); var start = (new Date(lastyear.getFullYear(), 0, 1)).getTime(), end = (new Date(lastyear.getFullYear(), 11, 31)).getTime(); Is this the solution you are looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/39298443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google drive spreadsheet and calendar invite guest Okay, first of all, what I'm trying to do is updating Google sheet and calendar simultaneously. So, let say if there's an update to your spreadsheet there will also be an update to the calendar. However, here's all the things that I failed to do. * *If there's changes in the calendar , there will be no changes in the spreadsheet *I'm unable to find code to invite guest to the calendar. So far , all i know is that i need to to use " attendee[] " but I'm unable to find example to show me on how its done. I've found some java code but its different if I'm not mistaken. So, these will be the order for the spreadsheet Date Title Start Time End Time Location Description Guest EventID This one is the code on the google sheets. function onOpen() { var sheet = SpreadsheetApp.getActiveSpreadsheet(); var entries = [{ name : "Export Events", functionName : "exportEvents" }]; sheet.addMenu("Calendar Actions ", entries); }; function exportEvents() { var sheet = SpreadsheetApp.getActiveSheet(); var headerRows = 1; var range = sheet.getDataRange(); var data = range.getValues(); var calId = "email"; // calenderID var cal = CalendarApp.getCalendarById(calId); for (i in data) { if (i < headerRows) continue; var row = data[i]; var date = new Date(row[0]); var title = row[1]; var tstart = new Date(row[2]); tstart.setDate(date.getDate()); tstart.setMonth(date.getMonth()); tstart.setYear(date.getYear()); tstart.setMinutes( tstart.getMinutes() + 6) var tstop = new Date(row[3]); tstop.setDate(date.getDate()); tstop.setMonth(date.getMonth()); tstop.setYear(date.getYear()); tstop.setMinutes(tstop.getMinutes() + 6) var loc = row[4]; var desc = row[5]; var guest = row[6] var id = row[7]; try { var event = cal.getEventSeriesById(id); event.deleteEventSeries(); row[7] = ''; } catch (e) { } var newEvent = cal.createEvent(title, new Date(tstart), new Date(tstop), {description:desc,location:loc}).getId(); row[7] = newEvent; debugger; } range.setValues(data); } If possible , I would some guidance on this , since I'm stuck. A: For this, if you want to create a new event for each new entry in spread sheet you could use Calender class and create an event. If you want to edit an already created event and add new guests you could use CalendarEvent class and add guests. Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/29936870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sending emails jsp Glassfish What I'm trying to do is to send emails to clients via Gmail automatically as a reminder in a specific time. So I found a tutorial on YouTube: https://www.youtube.com/watch?v=gy2eEZhLihk, I made the same thing, same code but I didn't work. Here is my code, I'm using eclipse and Glassfish server. Page1: MailDispatcherServlet package com.hubberspot.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hubberspot.ejb.MailSenderBean; /** * Servlet implementation class MailDispatcherServlet */ @WebServlet("/MailDispatcherServlet") public class MailDispatcherServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ @EJB private MailSenderBean mailSender; public MailDispatcherServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); String toEmail = request.getParameter("Email"); String subject = request.getParameter("Subject"); String message = request.getParameter("Message"); // Properties ... String fromEmail = "[email protected]"; String username = "majjane.ma"; String password = "majjane.ma20"; try (PrintWriter out= response.getWriter()){ // Call to mail sender bean mailSender.sendEmail(fromEmail, username, password, toEmail, subject, message); //--------------------------- out.println("<!Doctype html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Mail Status</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Mail Status !!!</h1>"); out.println("<b>Mail sent successfully</b><br>"); out.println("Click <a href='emailClient.jsp'>here</a> to go back !!!"); out.println("</body>"); out.println("</html>"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*response.setContentType("text/html"); String toEmail = request.getParameter("Email"); String subject = request.getParameter("Subject"); String message = request.getParameter("Message"); // Properties ... String fromEmail = "[email protected]"; String username = "majjane.ma"; String password = "Majjane.Ma2"; try (PrintWriter out= response.getWriter()){ // Call to mail sender bean //--------------------------- out.println("<!Doctype html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Mail Status</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Mail Status !!!</h1>"); out.println("<b>Mail sent successfully</b><br>"); out.println("Click <a href='emailClient.jsp'>here</a> to go back !!!"); out.println("/body"); out.println("</html>"); } */ } } Page2: MailSenderBean package com.hubberspot.ejb; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; @Stateless public class MailSenderBean { public void sendEmail(String fromEmail,String username, String password, String toEmail, String subject,String message) { try { Properties props = System.getProperties(); props.put("mail.smtp.host","smtp.gmail.com"); props.put("mail.smtp.auth","true"); props.put("mail.smtp.port","465"); props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.port","465"); props.put("mail.smtp.socketFactory.fallback","false"); Session mailSession = Session.getDefaultInstance(props, null); mailSession.setDebug(true); Message mailMessage = new MimeMessage(mailSession); mailMessage.setFrom(new InternetAddress(fromEmail)); mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); mailMessage.setContent(message, "text/html"); mailMessage.setSubject(subject); Transport transport = mailSession.getTransport("smtp"); transport.connect("smtp.gmail.com",username ,password); transport.sendMessage(mailMessage, mailMessage.getAllRecipients()); } catch (Exception ex) { Logger.getLogger(MailSenderBean.class.getName()).log(Level.SEVERE, null, ex); } } } Page3: emailClient This page has a form where I enter message, subject and the client adress. These parameters will be sent to the action page "MailDispatcherServlet", the method is Get. This is what is displayed on my console: 2015-08-13T10:08:11.264+0100|Infos: DEBUG: setDebug: JavaMail version 1.5.0 2015-08-13T10:08:11.264+0100|Infos: DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle] 2015-08-13T10:08:11.264+0100|Infos: DEBUG SMTP: useEhlo true, useAuth true 2015-08-13T10:08:11.264+0100|Infos: DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false 2015-08-13T10:08:13.441+0100|Grave: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1963) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654) at javax.mail.Service.connect(Service.java:345) at javax.mail.Service.connect(Service.java:226) at com.hubberspot.ejb.MailSenderBean.sendEmail(MailSenderBean.java:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081) at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153) at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695) at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822) at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582) at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822) at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582) at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163) at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822) at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369) at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667) at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88) at com.sun.proxy.$Proxy222.sendEmail(Unknown Source) at com.hubberspot.ejb.__EJB31_Generated__MailSenderBean__Intf____Bean__.sendEmail(Unknown Source) at com.hubberspot.servlet.MailDispatcherServlet.doGet(MailDispatcherServlet.java:61) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:744) Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868) at sun.security.ssl.Handshaker.process_record(Handshaker.java:804) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323) at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927) ... 67 more Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385) at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) at sun.security.validator.Validator.validate(Validator.java:260) at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326) at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231) at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323) ... 78 more Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196) at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268) at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380) ... 84 more Please let me know if you need any other details. Thank you, Benz A: Transport transport = mailSession.getTransport("smtps");// change smtp to smtps and disable your PC antivirus and firewall then try and turn on 'Access for less secure apps' https://www.google.com/settings/security/lesssecureapps then will able to send mail successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/31985526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loading many images simultaneously causes Activity/Fragment to lag I'm new to developping android TV applications. I am building a quizz game which needs a lot of images, videos, mp3 and gifs to show up simultaneously at a given time depending on the business logic of the game. I am using: * *glide to show images / gifs (images are High Definition); *android Async and Handler / Thread / Runnable pattern to play sounds; *android video player to play videos (videos are High Definition); *nested RelativeLayout / LinearLayout to display the views; *View.setVisibility(GONE) to hide views and View.setVisibility(VISIBLE) to show it. My problem is this: On a Samsung galaxy tab 4 device, the game is smooth! But on a TV device, TCL 1920x1080 40dpi that should run the game, it is laggy. I have read a lot of blog posts about how to optimize code ; like using ConstraintLayout instead of nested layouts, using View.setVisibility(INVISIBLE) instead of View.setVisibility(GONE) and I am also planning to use Picasso instead of Glide to get some fps but I'm not confident about all those. Can anyone give me advices on how to optimise my code to get some more fps (I mean getting like 10 or 15 fps not just 2 or 3)? Thanks in advance guys, cheer up! A: in android manifest I added: android:hardwareAccelerated="true" solved the problem got 15fps higher.
{ "language": "en", "url": "https://stackoverflow.com/questions/66579264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jackson Serialise a Scala Set I have a question related to fasterxml jackson in serialising a scala class Genre with a Set as one of the fields Set[Type] where Type is a case class with single param value class Type(val value: String) extends AnyVal case class Genre(name: String, types: Set[Type]) When I try to serialise it , it gives something like {"genre":{"name":"xxxxxx","types":[{"value":"aaaaa"}, {"value":"bbbb"}, {"value":"ccccc"}]}} But I don't want the generated json to contain the param name of the class and it should contain only param value . It should simply look like a comma separated values ["aaaaa","bbbb","ccccc"] something like {"genre":{"name":"xxxxxx","types":["aaaaa","bbbb","ccccc"]}} Is there any way , using jackson, to serialise a Set of classes with simply values in it but not param names ? My mapper looks like this private val mapper = new ObjectMapper mapper.registerModule(DefaultScalaModule) Thanks in Advance ! A: It should simply look like a comma separated values ["aaaaa","bbbb","ccccc"] That is Set[String], but what you have is Set[Type]. Jackson is doing exactly what it's supposed to do. You need to change your class signature to: case class Genre(name: String, types: Set[String]) import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule object TestObject { def main(args: Array[String]): Unit = { val mapper = new ObjectMapper() mapper.registerModule(DefaultScalaModule) val genre = Genre("xxxxxx", Set(new Type("aaaaa"), new Type("bbbb"), new Type("ccccc"))) println("Genre: " + mapper.writeValueAsString(genre)) val anotherGenre = AnotherGenre("xxxxxx", Set("aaaaa", "bbbb", "ccccc")) println("AnotherGenre: " + mapper.writeValueAsString(anotherGenre)) } } class Type(val value: String) extends AnyVal case class Genre(name: String, types: Set[Type]) case class AnotherGenre(name: String, types: Set[String]) Output: Genre: {"name":"xxxxxx","types":[{"value":"aaaaa"},{"value":"bbbb"},{"value":"ccccc"}]} AnotherGenre: {"name":"xxxxxx","types":["aaaaa","bbbb","ccccc"]}
{ "language": "en", "url": "https://stackoverflow.com/questions/41147862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine cursor visibility for a thread in Win32? Each thread have their own cursor count that is incremented/decremented by ShowCursor calls. Is there a way to query that counter to determine if the cursor is currently visible? This pattern is supposed to work but there are some problems with that: ShowCursor (FALSE); bool visible = (ShowCursor (TRUE) >= 0); * *The windows app compatibility layer might silently not allow the counter to decrease below 0 so the first ShowCursor call does nothing and the second corrupts the counter. *It has some unwanted side effects like potential and needless cursor hiding/unhiding A: You can test for cursor visibility directly with GetCursorInfo() bool IsCursorVisible() { CURSORINFO ci = { sizeof(CURSORINFO) }; if (GetCursorInfo(&ci)) return ci.flags & CURSOR_SHOWING; return false; } I'm not sure what it means for this call to fail so I just have it returning false if it fails.
{ "language": "en", "url": "https://stackoverflow.com/questions/57513069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keyword "Click Element" doesn't always work correct I'm facing problem, that keyword "Click Element" doesn't always work correct. For example, I want to go to the link on the web-site. xpath for the Link is the: ${xpathIMButton} xpath=//a/span[contains(text(),"${exprIM}")] ${exprIM} Infrastructure Management To click on the Link with Mouse Over I use following: Wait Until Page Contains Element ${xpathIMButton} Mouse Over ${xpathIMButton} Click Element ${xpathIMButton} don't wait That's pretty simple, but what I see on the Logs is confusing: The screenshot from HTML-source of the button: So, the Robot finds the link (Wait Until Page Contains Element and Mouse Over) are OK, but the Click Element fails. On the screenshot I can see, that the button actually exists. So what is the problem? Why I get those confusing error? I'm using: RFW 2.7.5 SeleniumLibrary 2.8.1 Firefox 12 A: Try this: Wait Until Page Contains Element ${xpathIMButton} Mouse Over ${xpathIMButton} Click Element ${xpathIMButton} don't wait A: Click Element started to fail for me when I upgraded to Selenium 2.35, SeleniumLibrary 2.9.1 and Selenium2Library 1.2. My browser was Firefox 22. The Click Element was pressing a Save button. The same exact code worked 2 times and the third time said it worked but the confirm page never showed up. I solved my issue by putting a Focus keyword before my Click Element Focus ${saveRule} Click Element ${saveRule} Now the code works the three times it is called. Hope this helps. A: It may be a little late to provide an answer, but I had exactly this problem. What I did was to provide a bit waiting time for the page to fully load, then my button was successfully found. A: It seems that your Mouse Over could cause the issue. The Mouse Over could cause the element to be hidden in DOM. But this was 6 years ago with Selenium 1 Library. Now, we are using Selenium2Library in ROBOT Framework, so if you give a try or already done it, just let us know.
{ "language": "en", "url": "https://stackoverflow.com/questions/13762033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add a text to taken screenshot in Selenium WebDriver? My question might be a little bit reckless, but I would like to know if anybody had an experience with adding a text to a taken screenshot using Selenium WebDriver or any other Java library? Currently I'm utilizing: File screenShotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenShotFile, new File("C:\\XXX\\XXX\\SeleniumScreenshots\\" + "png")); in order to take a screenshot and it's working fine, but sometimes I need to add a descritive text to the screenshot smth like: "This is failed because of this..." What I need exactly is certain location of the page (e.g. global footer, header, burger menu, certain image) that may be found with xpath expression, take the screenshot of that location and add a text with the problem description. If anybody has an idea how this may be implemented please respond with a sample code. A: To directly draw on the screenshot returned by the driver: WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com/"); // take the screenshot byte[] img_bytes = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES); BufferedImage img = ImageIO.read(new ByteArrayInputStream(img_bytes)); // add some text and draw a rectangle Graphics g = img.getGraphics(); g.setColor(Color.red); g.setFont(new Font( "SansSerif", Font.BOLD, 14)); g.drawString("My text", 10, 10); g.drawRect(5, 5, 50, 50); g.dispose(); // save the image ImageIO.write(img, "png", new File("screenshot.png")); If the targeted element is off-screen then you'll probably have to scroll it into the window beforehand: ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element); A: Nothing Much! Tweaking the code from the link provided by @andrucz WebElement failedElement = driver.findElement(<locate your element>); File screenShotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); final BufferedImage image = ImageIO.read(screenShotFile); Graphics g = image.getGraphics(); g.setFont(g.getFont().deriveFont(30f)); g.drawString("Failed because of this!!", failedElement.getSize().getX(), failedElement.getSize().getY()); //Top-left coordinates of your failed element g.dispose(); ImageIO.write(image, "png", new File("test.png"));
{ "language": "en", "url": "https://stackoverflow.com/questions/35845941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pass all arguments to another function I have two functions like this: function mysql_safe_query($format) { $args = array_slice(func_get_args(),1); $args = array_map('mysql_safe_string',$args); $query = vsprintf($format,$args); $result = mysql_query($query); if($result === false) echo '<div class="mysql-error">',mysql_error(),'<br/>',$query,'</div>'; return $result; } function mysql_row_exists() { $result = mysql_safe_query(func_get_args()); return mysql_num_rows($result) > 0; } The problem is that the second function won't work because it passes the args to the first one as an array, when it expects them as different parameters. Is there any way to get around this, preferably without modifying mysql_safe_query? A: How about using: $args = func_get_args(); call_user_func_array('mysql_safe_query', $args); A: N.B. In PHP 5.6 you can now do this: function mysql_row_exists(...$args) { $result = mysql_safe_query(...$args); return mysql_num_rows($result) > 0; } Also, for future readers, mysql_* is deprecated -- don't use those functions. A: Depending on the situation, following might also work for you and might be a little faster. function mysql_safe_query($format) { $args = func_get_args(); $args = is_array($args[0]) ? $args[0] : $args; // remove extra container, if needed // ... Which now allows for both types of calling, but might be problematic if your first value is supposed to be an actual array, because it would be unpacked either way. You could additionally check on the length of your root-array, so it might not be unpacked if if there are other elements, but as mentioned: It is not really that "clean" in general, but might be helpful and fast :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/936192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Why is this regular expression accepting special characters and numbers? I've created a simple regular expression for email. It is: /[a-z]+@{1}[a-z]{2,}/ Now the problem is that it's accepting an email like something;;99@asd when tested. But it shouldn't allow ;;99 ? I want letters only. Secondly, please tell me about beginning (^) and end ($) symbols used in regular expression. I read about them on codeacademy but couldn't understand their purpose. Do they have something to do with my original problem? EDIT: Here's the whole jQuery: <script type="text/javascript"> $(document).ready(function(){ var $pat1=/[a-zA-Z0-9]{5}/; var $pat2=/[a-z]+@{1}[a-z]{2,}/; $(".savebutton").click(function(){ var $name=$("input[name='pname']").val(); var $email=$("input[name='pmail']").val(); var $pswd=$("input[name='pswd']").val(); if(($name!="" && $email!="") && $pswd!=""){ if($pat1.test($name)&&$pat2.test($email)){ //ACTIONS } } }) }) </script> A: Try this regex /^[a-z]+@{1}[a-z]{2,}$/g Your string must start with a-z (^) and end in a-z($) ^ and $ are for beginning and end A: Your Regular Expression looks fine. I tested it on few test cases. * *Symbol ^ Matches the beginning of the string, or the beginning of a line if the multiline flag (m) is enabled. This matches a position, not a character. *Symbol $ Matches the end of the string, or the end of a line if the multiline flag (m) is enabled. This matches a position, not a character. For example, if you have to match pattern of exactly length 3, Then you can use ^ and $ to denote beginning and end of the pattern. A: An example of email regex is like this /^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/m for your question, Please tell me about beginning (^) and end ($) symbols used in regular expression... In my example regex above, both symbols are best used if your using the multiline (m) modifier in you regex. (^) is used to identify the beginning of the line and ($) is used to identify the end of the line. It does affect your original problem but I would suggest you use this symbols in your regular expression. Hope me help well.
{ "language": "en", "url": "https://stackoverflow.com/questions/38432233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying laravel api rest on ubuntu and nginx I have a REST API with Laravel 5.5 LTS that I want to deploy to my ubuntu server and use nginx. I have uploaded the api to my ubuntu server and the updated my nginx config file like this: server { listen 80; listen [::]:80; root /myservername/api/public; index index.php index.html index.htm; server_name myservername.com www.myservername.com; location /api { try_files $uri/ /server.php?$query_string; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } I then have an endpoint route configured as: Route::get('/api/mail/send', 'MailController@index'); now when I go to myservername.com/api/mail/send I get a 404 not found. The MailController just does a var_dump(): class MailController extends Controller { /** * @param Request $request * @return \Illuminate\Http\JsonResponse */ protected function index(Request $request) { var_dump('hi'); } } Anyone know what I am missing? My second location block I basically copy pasted, do i need it? as I notice that unix path does not exist (/var/run/php/php7.2-fpm.sock)
{ "language": "en", "url": "https://stackoverflow.com/questions/54678194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am trying to open specific comments related to post using Jquery I am trying to open specific Comments related to post but when i click to view more comments so all comments is opening but i want to open comments related to post not all please help me how can resolved that ? thank u html view <div class="comment-box"> @foreach ($communityPosts->communityPostReply as $communityPostReplies) <div class="user-comment-box"> <div class="d-flex pt-3"> <div class="notification-text ms-3 w-100"> <span class="username fw-bold">{{$communityPostReplies->users->full_name}}</span> <p class="mt-2 mb-0">{{$communityPostReplies->reply_body}}</p> <span class="text-muted small">{{$communityPostReplies->created_at->diffForHumans()}}</span> </div> </div> </div> @endforeach <a style="cursor: pointer;" class="see-more">View More Comments</a> Here is my Jquery $(function(){ $(".user-comment-box").slice(-5).show(); // select the first 5 hidden divs $(".see-more").click(function(e){ // click event for load more e.preventDefault(); var done = $('<div class="see-more=done"></div>'); $(".user-comment-box:hidden").slice(-5).show(); // select next 5 hidden divs and show them if($(".user-comment-box:hidden").length == 0){ // check if any hidden divs $(".see-more").replaceWith(done); // if there are none left } }); }); A: You should limit your selectors to just the current .comment-box div. $(function() { $(".user-comment-box").slice(-5).show(); // select the first 5 hidden divs $(".see-more").click(function(e) { // click event for load more e.preventDefault(); let current_post = $(this).closest(".comment-box"); var done = $('<div class="see-more=done"></div>'); current_post.find(".user-comment-box:hidden").slice(-5).show(); // select next 5 hidden divs and show them if (current_post.find(".user-comment-box:hidden").length == 0) { // check if any hidden divs $(this).replaceWith(done); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/72309646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bad Padding Exception :pad block corrupt when calling dofinal I am working on encryption and decryption. I am very new to cryptography and i am facing pad block corrupt exception when using bouncy castle Here is my encryption/decryption code. private AESFastEngine engine; private BufferedBlockCipher cipher; private final KeyParameter key=setEncryptionKey("testinggtestingg"); public KeyParameter setEncryptionKey(String keyText) { // adding in spaces to force a proper key keyText += " "; // cutting off at 128 bits (16 characters) keyText = keyText.substring(0, 16); byte[] keyBytes = keyText.getBytes(); //key = new KeyParameter(keyBytes); engine = new AESFastEngine(); cipher = new PaddedBufferedBlockCipher(engine); return new KeyParameter(keyBytes); } public String encryptString(String plainText) { try { byte[] plainArray = plainText.getBytes(); cipher.init(true, key); byte[] cipherBytes = new byte[cipher .getOutputSize(plainArray.length)]; int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); cipher.doFinal(cipherBytes, cipherLength); return (new String(cipherBytes)); } catch (DataLengthException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (InvalidCipherTextException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } // else return null; } public String decryptString(String encryptedText) { try { byte[] cipherBytes = encryptedText.getBytes(); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher .getOutputSize(cipherBytes.length)]; int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); cipher.doFinal(decryptedBytes,decryptedLength); String decryptedString = new String(decryptedBytes); // crop accordingly int index = decryptedString.indexOf("\u0000"); if (index >= 0) { decryptedString = decryptedString.substring(0, index); } return decryptedString; } catch (DataLengthException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (InvalidCipherTextException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } // else return null; } A: All you needed is to precise the charset. Here you go : import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; public class Main { private BufferedBlockCipher cipher; private final KeyParameter key = setEncryptionKey("testinggtestingg"); private static final String CHARSET = "ISO-8859-1"; public static void main(String[] argv) { Main main = new Main(); String plain = "trallalla"; System.out.println("initial : " + plain); String encrypted = main.encryptString(plain); System.out.println("after encryption : " + encrypted); String decrypted = main.decryptString(encrypted); System.out.println("after decryption : " + decrypted); } public KeyParameter setEncryptionKey(String keyText) { // adding in spaces to force a proper key keyText += " "; // cutting off at 128 bits (16 characters) keyText = keyText.substring(0, 16); byte[] keyBytes = keyText.getBytes(); // key = new KeyParameter(keyBytes); AESFastEngine engine = new AESFastEngine(); cipher = new PaddedBufferedBlockCipher(engine); return new KeyParameter(keyBytes); } public String encryptString(String plainText) { try { byte[] plainArray = plainText.getBytes(); cipher.init(true, key); byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)]; int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); cipher.doFinal(cipherBytes, cipherLength); return (new String(cipherBytes, CHARSET)); } catch (DataLengthException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (InvalidCipherTextException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } // else return null; } public String decryptString(String encryptedText) { try { byte[] cipherBytes = encryptedText.getBytes(CHARSET); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); cipher.doFinal(decryptedBytes, decryptedLength); String decryptedString = new String(decryptedBytes); // crop accordingly int index = decryptedString.indexOf("\u0000"); if (index >= 0) { decryptedString = decryptedString.substring(0, index); } return decryptedString; } catch (DataLengthException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (InvalidCipherTextException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } // else return null; } } But why are you using this external library ? Here is the code I use and which does not need any external libraries: import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.*; import javax.crypto.spec.*; public class Encryption { private static final String ALGORITHME = "Blowfish"; private static final String TRANSFORMATION = "Blowfish/ECB/PKCS5Padding"; private static final String SECRET = "kjkdfjslm"; private static final String CHARSET = "ISO-8859-1"; public static void main(String[] argv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { Encryption main = new Encryption(); String plain = "trallalla"; System.out.println("initial : " + plain); String encrypted = main.encrypt(plain); System.out.println("after encryption : " + encrypted); String decrypted = main.decrypt(encrypted); System.out.println("after decryption : " + decrypted); } public String encrypt(String plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(SECRET.getBytes(CHARSET), ALGORITHME)); return new String(cipher.doFinal(plaintext.getBytes()), CHARSET); } public String decrypt(String ciphertext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(SECRET.getBytes(), ALGORITHME)); return new String(cipher.doFinal(ciphertext.getBytes(CHARSET)), CHARSET); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/14397672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android string resource vs application size Is there a cost to using the android string.xml resources? If I want to keep my application size down, which of the following is better * *Declare my string literals within the layout files, as in <TextView android:text="Hello"> *Use only one string file to store all strings as resources, as in strings.xml *Use one string file per activity (so to speak), as in strings_activity_hello.xml A: There's no cost as far as I know, and these are two major benefits that I know of: * *If you use the same string in multiple layouts or classes, you can change it in strings.xml and it will be updated everywhere (you'll never forget to change it somewhere). *You can give people the strings.xml for translation, and create files like strings-es.xml (for Spanish) that Android will use for automatically displaying a translated version of your app based on the device's default language. I'm sure it affects compilation time but I think the SDK combines and optimizes all of your strings somewhere in the actual APK.
{ "language": "en", "url": "https://stackoverflow.com/questions/17797042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Oracle sys_refcursor returned stored procedure resultset in c# using entity framework I have a stored procedure which returns select result set using sys_refcursor. Now I want to show these results in c# windows form application by Entity Framework (Model-First) function import feature, but EF Model Designer can not recognize return type of the procedure. I have installed Oracle Developer Tools for Visual Studio 2017. Also I have Created Model From Database and imported the stored procedure. My Oracle Version is 12.2. CREATE OR REPLACE PROCEDURE GET_EMPLOYEE_INFO(ID_EMPLOYEE IN NUMBER) AS EMP_INFO SYS_REFCURSOR; BEGIN OPEN EMP_INFO FOR SELECT * FROM HR.EMPLOYEE WHERE ID=ID_EMPLOYEE; DBMS_SQL.RETURN_RESULT(EMP_INFO); END; So I want a complete instruction on how to map imported function return types correctly. Also I want to have a access to EMPLOYEE table's columns like object properties (fields).
{ "language": "en", "url": "https://stackoverflow.com/questions/54052447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Timestamp columns and InvalidOperationException I've recently added a timestamp column to a table in a linq-to-sql DBML file. It caused an InvalidOperationException when the entire web service loaded (no queries were even run). The exception is: [InvalidOperationException: System.Data.Linq.Binary cannot be serialized because it does not have a parameterless constructor.] [InvalidOperationException: Cannot serialize member 'server.DBHandlers.TableName.RowStamp' of type 'System.Data.Linq.Binary', see inner exception for more details.] System.Xml.Serialization.StructModel.CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type) +1549853 System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo) +189 System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo) +146 System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) +1237 System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter) +631 System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) +1719 What's the cause? How can it be fixed? Posting the entire stack trace as per leppie's request: [InvalidOperationException: System.Data.Linq.Binary cannot be serialized because it does not have a parameterless constructor.] [InvalidOperationException: Cannot serialize member 'server.DBHandlers.TableName.RowStamp' of type 'System.Data.Linq.Binary', see inner exception for more details.] System.Xml.Serialization.StructModel.CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type) +1549853 System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo) +189 System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo) +146 System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) +1237 System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter) +631 System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) +1719 [InvalidOperationException: There was an error reflecting type 'server.DBHandlers.TableName'.] System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) +1516787 System.Xml.Serialization.XmlReflectionImporter.CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArrayItemAttributes attributes, Type arrayElementType, String arrayElementNs, RecursionLimiter limiter) +412 System.Xml.Serialization.XmlReflectionImporter.ImportArrayLikeMapping(ArrayModel model, String ns, RecursionLimiter limiter) +337 System.Xml.Serialization.XmlReflectionImporter.ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +6535 System.Xml.Serialization.XmlReflectionImporter.ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, String ns, RecursionLimiter limiter) +210 System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) +1295 [InvalidOperationException: There was an error reflecting property 'TableName'.] System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) +3631 System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter) +631 System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) +1719 [InvalidOperationException: There was an error reflecting type 'server.DBHandlers.RelatedTableName'.] System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) +1516787 System.Xml.Serialization.XmlReflectionImporter.ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +9555 System.Xml.Serialization.XmlReflectionImporter.ImportMemberMapping(XmlReflectionMember xmlReflectionMember, String ns, XmlReflectionMember[] xmlReflectionMembers, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +963 System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, String ns, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +418 [InvalidOperationException: There was an error reflecting 'getRelatedTable'.] System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, String ns, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +1504534 System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(String elementName, String ns, XmlReflectionMember[] members, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, XmlMappingAccess access) +195 System.Web.Services.Protocols.SoapReflector.ImportMembersMapping(XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, Boolean serviceDefaultIsEncoded, Boolean rpc, SoapBindingUse use, SoapParameterStyle paramStyle, String elementName, String elementNamespace, Boolean nsIsDefault, XmlReflectionMember[] members, Boolean validate, Boolean openModel, String key, Boolean writeAccess) +388 System.Web.Services.Protocols.SoapReflector.ReflectMethod(LogicalMethodInfo methodInfo, Boolean client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, String defaultNs) +3366 [InvalidOperationException: Method ServiceName.getRelatedTable can not be reflected.] System.Web.Services.Protocols.SoapReflector.ReflectMethod(LogicalMethodInfo methodInfo, Boolean client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, String defaultNs) +841901 System.Web.Services.Description.SoapProtocolReflector.ReflectMethod() +142 System.Web.Services.Description.ProtocolReflector.ReflectBinding(ReflectedBinding reflectedBinding) +1610 System.Web.Services.Description.ProtocolReflector.Reflect() +710 System.Web.Services.Description.ServiceDescriptionReflector.ReflectInternal(ProtocolReflector[] reflectors) +565 System.Web.Services.Description.ServiceDescriptionReflector.Reflect(Type type, String url) +153 System.Web.Services.Protocols.DocumentationServerType..ctor(Type type, String uri) +203 System.Web.Services.Protocols.DocumentationServerProtocol.Initialize() +388 System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response) +75 System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) +143 [InvalidOperationException: Unable to handle request.] System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) +458731 System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +285 [InvalidOperationException: Failed to handle request.] System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +401482 System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +281 System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +89 System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +425 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +263 A: Or change timestamp's type to Byte[]. More [info]:http://geekswithblogs.net/frankw/archive/2008/08/29/serialization-issue-with-timestamp-in-linq-to-sql.aspx A: It can be fixed by changing the ReadOnly property on the timestamp column, in the DBML, to true.
{ "language": "en", "url": "https://stackoverflow.com/questions/3957531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get route not found in laravel I have registered get route like below: Route::get('/user/verify?email={email}&token={token}', 'UserController@verifyEmail'); But when I try to access this route with the following: website.com/user/[email protected]&token=38757e18aad8808832ace900f418b03763789755 It says 404 not found. What is wrong here? A: your route would be : Route::get('/user/verify', 'UserController@verifyEmail'); Now can access : website.com/user/[email protected]&token=38757e18aad8808832ace900f418b0376378975 In your controller you can get the parameter value like that : public function show(Request $request) { $email = $request->email ?? null; $token = $request->token ?? null; } A: You can run php artisan route:list in your console and check how exatctly every route looks like. Query params like that: ?email={email}&token={token} in this url: '/user/verify?email={email}&token={token}' are ignored by laravel router.
{ "language": "en", "url": "https://stackoverflow.com/questions/63545388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tuple Comparison I`ve a dictionary defined like this : d = {"date": tuple(date),"open":tuple(open),"close":tuple(close),"min":tuple(min),"max":tuple(max),"MA":tuple(ma)} Each one of those tuples contains a list of values ( same number of values for each tuple ), how can I iterate trough each value of paticular keys to compare if "close" is superior to "MA" ? A: what am I missing? d['close'] > d['MA']? Edit: Re, your comments [...] what I want to return is how many times one element of "close" is > to the matching element of MA . (same tuple index) sum( pair[0] > pair[1] for pair in zip(d['close'], d['MA']) ) A: From the Python docs: Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length. If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]). So as @TokenMacGuy says, you can simply use d['close'] > d['MA'] to compare the respective tuples.
{ "language": "en", "url": "https://stackoverflow.com/questions/4405122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I change the delimiter used in CSV file? UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2219: character maps to <undefined I would appreciate your help A: From CSV Examples: Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open: import csv with open('some.csv', newline='', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: print(row) The same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.
{ "language": "en", "url": "https://stackoverflow.com/questions/68823133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiplication division using DFSORT utility in Mainframe There are two files FILE1.DATA and FILE2.DATA To calculate percentage (Number of records in FILE1/Number of records in FILE2)*100 using DFSORT in Mainframe. And setting Return Code if it crossing a threshold (90%). //********Extracting Unique records data***************** //SORTT000 EXEC PGM=SORT //SYSOUT DD SYSOUT=* //SORTIN DD DSN=SAMPLE.DATA1,DISP=SHR //SORTOUT DD DSN=FILE1.DATA, // SPACE=(2790,(5376,1075),RLSE), // UNIT=TSTSF, // DCB=(RECFM=FB,LRECL=05,BLKSIZE=0), // DISP=(NEW,CATLG,DELETE) //SYSIN DD * SORT FIELDS=(10,5,CH,A) OUTREC FIELDS=(1:10,5) SUM FIELDS=NONE /* //************Getting count of records***************** //STEP001 EXEC PGM=ICETOOL //TOOLMSG DD SYSOUT=* //DFSMSG DD SYSOUT=* //SYSOUT DD SYSOUT=* //SYSPRINT DD SYSOUT=* //IN1 DD DISP=SHR,DSN=FILE1.DATA //IN2 DD DISP=SHR,DSN=FILE2.DATA //OUT1 DD DSN=FILE1.DATA.COUNT, // SPACE=(2790,(5376,1075),RLSE), // UNIT=TSTSF, // DCB=(RECFM=FB,LRECL=06,BLKSIZE=0), // DISP=(NEW,CATLG,DELETE) //OUT2 DD DSN=FILE2.DATA.COUNT, // SPACE=(2790,(5376,1075),RLSE), // UNIT=TSTSF, // DCB=(RECFM=FB,LRECL=06,BLKSIZE=0), // DISP=(NEW,CATLG,DELETE) //TOOLIN DD * COUNT FROM(IN1) WRITE(OUT1) DIGITS(6) COUNT FROM(IN2) WRITE(OUT2) DIGITS(6) /* //*******Calculating percentage and if above 90% setting RC 04***** //STEP002 EXEC PGM=SORT //SYSOUT DD SYSOUT=* //SORTIN DD DSN=FILE2.DATA.COUNT,DISP=SHR // DD DSN=FILE1.DATA.COUNT,DISP=SHR //SORTOUT DD DSN=FILE.DATA.COUNT.OUT, // SPACE=(2790,(5376,1075),RLSE), // UNIT=TSTSF, // DCB=(RECFM=FB,LRECL=80,BLKSIZE=0), // DISP=(NEW,CATLG,DELETE) //SETRC DD SYSOUT=* //SYSIN DD * INREC IFTHEN=(WHEN=INIT,BUILD=(1,6,X,6X'00',SEQNUM,1,ZD,80:X)), IFTHEN=(WHEN=(14,1,ZD,EQ,2),OVERLAY=(8:1,6)) SORT FIELDS=(7,1,CH,A),EQUALS SUM FIELDS=(8,4,BI,12,2,BI) OUTREC OVERLAY=(15:X,1,6,ZD,DIV,+2,M11,LENGTH=6,X, (8,6,ZD,MUL,+100),DIV,1,6,ZD,MUL,+100,EDIT=(TTT.TT)) OUTFIL FNAMES=SETRC,NULLOFL=RC4,INCLUDE=(23,6,CH,GT,C'090.00') OUTFIL BUILD=(05:C'TOTAL NUMBER RECRODS IN FILE2 : ',1,6,/, 05:C'TOTAL NUMBER RECRODS IN FILE1 : ',8,6,/, 05:C'PERCENTAGE : ',23,6,/, 80:X) //* * *The problem I am facing is datasets FILE1.DATA.COUNT and FILE1.DATA.COUNT are getting created of 15 record length despite mentioning LRECL 6. (note, this was the question that existed when the first answer was written and does not relate now to the above code). *Can we merge both steps into one? *What does this, (15:X,1,6,ZD,DIV,+2,M11,LENGTH=6,X, (8,6,ZD,MUL,+100),DIV,1,6,ZD,MUL,+100,EDIT=(TTT.TT)), mean specifically? A: The answer to your first question is simply that you did not tell ICETOOL's COUNT operator how long you wanted the output data to be, so it came up with its own figure. This is from the DFSORT Application Programming Guide: WRITE(countdd) Specifies the ddname of the count data set to be produced by ICETOOL for this operation. A countdd DD statement must be present. ICETOOL sets the attributes of the count data set as follows: v RECFM is set to FB. v LRECL is set to one of the following: – If WIDTH(n) is specified, LRECL is set to n. Use WIDTH(n) if your count record length and LRECL must be set to a particular value (for example, 80), or if you want to ensure that the count record length does not exceed a specific maximum (for example, 20 bytes). – If WIDTH(n) is not specified, LRECL is set to the calculated required record length. If your LRECL does not need to be set to a particular value, you can let ICETOOL determine and set the appropriate LRECL value by not specifying WIDTH(n). And: DIGITS(d) Specifies d digits for the count in the output record, overriding the default of 15 digits. d can be 1 to 15. The count is written as d decimal digits with leading zeros. DIGITS can only be specified if WRITE(countdd) is specified. If you know that your count requires less than 15 digits, you can use a lower number of digits (d) instead by specifying DIGITS(d). For example, if DIGITS(10) is specified, 10 digits are used instead of 15. If you use DIGITS(d) and the count overflows the number of digits used, ICETOOL terminates the operation. You can prevent the overflow by specifying an appropriately higher d value for DIGITS(d). For example, if DIGITS(5) results in overflow, you can use DIGITS(6) instead. And: WIDTH(n) Specifies the record length and LRECL you want ICETOOL to use for the count data set. n can be from 1 to 32760. WIDTH can only be specified if WRITE(countdd) is specified. ICETOOL always calculates the record length required to write the count record and uses it as follows: v If WIDTH(n) is specified and the calculated record length is less than or equal to n, ICETOOL sets the record length and LRECL to n. ICETOOL pads the count record on the right with blanks to the record length. v If WIDTH(n) is specified and the calculated record length is greater than n, ICETOOL issues an error message and terminates the operation. v If WIDTH(n) is not specified, ICETOOL sets the record length and LRECL to the calculated record length. Use WIDTH(n) if your count record length and LRECL must be set to a particular value (for example, 80), or if you want to ensure that the count record length does not exceed a specific maximum (for example, 20 bytes). Otherwise, you can let ICETOOL calculate and set the appropriate record length and LRECL by not specifying WIDTH(n). For your second question, yes it can be done in one step, and greatly simplified. The thing is, it can be further simplified by doing something else. Exactly what else depends on your actual task, which we don't know, we only know of the solution you have chosen for your task. For instance, you want to know when one file is within 10% of the size of the other. One way, if on-the-dot accuracy is not required, is to talk to the technical staff who manage your storage. Tell them what you want to do, and they probably already have something you can use to do it with (when discussing this, bear in mind that these are technically data sets, not files). Alternatively, something has already previously read or written those files. If the last program to do so does not already produce counts of what it has read/written (to my mind, standard good practice, with the program reconciling as well) then amend the programs to do so now. There. Magic. You have your counts. Arrange for those counts to be in a data set of their own (preferably with record-types, headers/trailers, more standard good practice). One step to take the larger (expectation) of the two counts, "work out" what 00% would be (doesn't need anything but a simple subtraction, with the right data) and generate a SYMNAMES format file (fixed-length 80-byte records) with a SORT-symbol for a constant with that value. Second step which uses INCLUDE/OMIT with the symbol in comparison to the second record-count, using NULLOUT or NULLOFL. The advantage of the above types of solution is that they basically use very few resources. On the Mainframe, the client pays for resources. Your client may not be so happy at the end of the year to find that they've paid for reading and "counting" 7.3m records just so that you can set an RC. OK, perhaps 7.3m is not so large, but, when you have your "solution", the next person along is going to do it with 100,000 records, the next with 1,000,000 records. All to set an RC. Any one run of which (even with the 10,000-record example) will outweigh the costs of a "Mainframe" solution running every day for the next 15+ years. For your third question: OUTREC OVERLAY=(15:X,1,6,ZD,DIV,+2,M11,LENGTH=6,X, (8,6,ZD,MUL,+100),DIV,1,6,ZD,MUL,+100,EDIT=(TTT.TT)) OUTREC is processed after SORT/MERGE and SUM (if present) otherwise after INREC. Note, the physical order in which these are specified in the JCL does not affect the order they are processed in. OVERLAY says "update the information in the current record with these data-manipulations (BUILD always creates a new copy of the current record). 15: is "column 15" (position 15) on the record. X inserts a blank. 1,6,ZD means "the information, at this moment, at start-position one for a length of six, which is a zoned-decimal format". DIV is divde. +2 is a numeric constant. 1,6,ZD,DIV,+2 means "take the six-digit number starting at position one, and divide it by two, giving a 'result', which will be placed at the next available position (16 in your case). M11 is a built-in edit-mask. For details of what that mask is, look it up in the manual, as you will discover other useful pre-defined masks at the time. Use that to format the result. LENGTH=6 limits the result to six digits. So far, the number in the first six positions will be divided by two, treated (by the mask) as an unsigned zoned-decimal of six digits, starting from position 16. The remaining elements of the statement are similar. Brackets affect the "precedence" of numeric operators in a normal way (consult the manual to be familiar with the precedence rules). EDIT=(TTT.TT) is a used-defined edit mask, in this case inserting a decimal point, truncating the otherwise existing left-most digit, and having significant leading zeros when necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/41949074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to access arguments.callee in CoffeeScript class? I have the following code class Foo a: -> console.log arguments.callee.name b: -> @a() c: -> @a() f = new Foo f.b() #=> should output 'b' f.c() #=> should output 'c' Question: How can I get the name of the calling function in my class? Here's a use case class Something extends Stream foo: -> _helper 'foo', 'a', 'b', 'c' bar: -> _helper 'bar', 'my neighbor totoro' dim: -> _helper 'dim', 1, 2, 3 sum: -> _helper 'sum', 'hello', 'world' _helper: (command, params...) -> @emit 'data', command, params... something = new Something something.foo() something.bar() # ... I don't want to have to duplicate sending the method name for each call to my private _helper method A: So to be clear, I think the second way you have it is totally reasonable and is the way to go. But to answer your question, you can generate each function dynamically to avoid having to retype the commands. class Foo commands = foo: ['a', 'b', 'c'] bar: ['my neighbor totoro'] dim: [1,2,3] for own name, args of commands Foo::[name] = -> @emit 'data', name, args... and assuming you want the functions to useful stuff, you can still use functions. // ... commands = foo: (args...) -> return ['a', 'b', 'c'] // ... for own name, cb of commands Foo::[name] = (command_args...) -> args = cb.apply @, command_args @emit 'data', name, args... A: This is what I would have done: class Something extends Stream constructor: -> @foo = helper.bind @, "foo", "a", "b", "c" @bar = helper.bind @, "bar", "my neighbor totoro" @dim = helper.bind @, "dim", 1, 2, 3 @sum = helper.bind @, "sum", "hello", "world" helper = (command, params...) -> @emit 'data', command, params... The advantages of this method are: * *The helper function is a private variable. It can't be accessed directly via an instance. *The helper function is only declared once and is shared between all instances. *The functions foo, bar, dim and sum are partial applications of helper. Hence they don't consume more memory for the function body. *It doesn't require a loop like @loganfsmyth's answer does. *It's cleaner. Edit: An even cleaner approach would be: class Something extends Stream constructor: -> @foo = @emit.bind @, "data", "foo", "a", "b", "c" @bar = @emit.bind @, "data", "bar", "my neighbor totoro" @dim = @emit.bind @, "data", "dim", 1, 2, 3 @sum = @emit.bind @, "data", "sum", "hello", "world" Sure, it's a little redundant but you can't expect more from a language like JavaScript. It's not Factor. However it is readable, clean, easily understandable, and above all - correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/13897882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JAXB Object to Clob How to create jaxb Object to Clob. When i tried the following not serializable error coming. public static void createClob(TestTo testTo){ PreparedStatement pst = null; Connection con = null; //Clob studentListClob = null; try { con = openOASDBcon(false); pst = con.prepareCall(INSERT_Clob); pst.setBytes(1, getByteArrayObject(testTo)); pst.setString(2, ""); pst.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { close(con, pst); } } private static byte[] getByteArrayObject(TestTo testTo){ byte[] byteArrayObject = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(testTo); oos.close(); bos.close(); byteArrayObject = bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); return byteArrayObject; } return byteArrayObject; } It's not possible to implement serializable. Is there any best way to implement jaxb object to clob. A: There are a couple of ways to approach sticking a JAXB object into a CLOB (or BLOB) column in a database. I think that you will have to do some custom insert and select logic to put the JAXB object into a column - the normal ORM model would be a row per object, with a column per field of the object (e.g., if you were using hibernate). Option 1: Configure xjc to generate Serializable JAXB classes (How to generate a Java class which implements Serializable interface from xsd using JAXB?). Then use the Serializable interface to read/write the object from the clob/blob's input/output streams. This stores the Java object representation in the database. Option 2: Use the JAXB-supplied XML marshal/unmarshal path to read/write the state of the object as XML text. This stores the XML representation of the object in the database. I personally would go with Option 2 - the XML representation. I think it is easier to manage changes in the XSD and make sure you can read old objects, rather than having to deal with Java's serial version ID. In addition, you might want to consider compressing the XML before putting it in the CLOB (see Compressing and decompressing streams).
{ "language": "en", "url": "https://stackoverflow.com/questions/21831031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a Dataset to input only Images I need a dataset object that contains only images for unsupervised learning in Chainer framework. I am trying to use DatasetMixin for this purpose. Images is a list containing images. class SimpleDataset(dataset.DatasetMixin): def __init__(self, Images): self.Images = Images def __len__(self): return len(self.Images) def get_example(self, i): return self.Images[i] The SimpleDataset Class seems to not able to read the images since when running trainer.run() I am getting error: call() missing 1 required positional argument: 'x' Do I need to process the image list furthur before putting it through DatasetMixin Class? Is there something wrong with using DatasetMixin to feed just images this way? What can I do to feed just images(without any labels or other things) to my model? class AutoEncoder(chainer.Chain): def __init__(self, n_in, n_out): super(AutoEncoder, self).__init__( l1 = L.Linear(n_in, n_out), l2 = L.Linear(n_out, n_in) ) self.add_param('decoder_bias', n_in) self.decoder_bias.data[...] = 0 def __call__(self, x): h1 = F.dropout(self.l1(x)) h2 = F.linear(h1, F.transpose(self.l1.W), self.decoder_bias) return F.sigmoid(h2) def encode(self, x): return F.dropout(self.l1(x)) def decode(self, x): return self.l2(x) model = L.Classifier(AutoEncoder(40000, 1000), lossfun=F.mean_squared_error) model.compute_accuracy = False A: If you are using Classifier, the dataset need to return in the format x0, x1, ... xk, y where x0, x1, ... xk will be fed into the predictor (in this case it is AutoEncoder class), and its output value y_pred and actual y is used for loss calculation specified by lossfun. In your case the answer y is also same with input. I think you can write following to return x and y which is actually same: def get_example(self, i): return self.Images[i], self.Images[i]
{ "language": "en", "url": "https://stackoverflow.com/questions/56421679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Specman - add bits in the beginning and end of list of bit I have the following list of bit which contains 8 bits (input to function): bs: list of bit; I have the following struct: struct uart_frame_s like any_sequence_item { %start_bit : bit; data_size : uint; %data[data_size] : list of bit; %stop_bit : bit; keep soft start_bit == 0; keep soft stop_bit == 1; keep soft data_size == 8; }; I have to execute the following: unpack(packing.low, bs, current_frame); The problem that bs size is 8, but current frame contains 10 bits.... So how can I add bits in the beginning and end of list of bit ('0' in the beginning and '1' in the end). Or alternatively verify that the bs will unpack to 1-8 bits in current frame. A: if you want to pack the bs into the frame data field, you can - unpack(packing.low, bs, current_frame.data);
{ "language": "en", "url": "https://stackoverflow.com/questions/49130951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get text from using Jsoup To be short. I have following code: elements.select("#offers_table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(2) > td:nth-child(1) > div > p.color-9.lheight16.marginbott5.x-normal").get(0).toString(); and I am getting <p class="color-9 lheight16 marginbott5 x-normal"> This is the text I would like to get </p> How to get This is the text I would like to get from here? A: Use element.text() where element is your Element.
{ "language": "en", "url": "https://stackoverflow.com/questions/31501959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Row merging based on two conditions I am currently cleaning my data set for a farm and I need to merge the records from 3 separate rows into one. I'd like the get all the records merged based on columns FARM and SHED. The dataset currently looks like this: Ideally, I wish to make it look like this: What is the best solution to have it cleaned up? I'd like to move columns 'Feed total' and 'Feed per bird' to fill the empty spaces in the rows above. Then I'd like to move around the columns 'Average weight 1A' to row, where the shed number is 1, 'Average weight 2A' to row, where the shed number is 2 etc... Thanks! EDIT: Sample dataset attached to give a bigger picture on the dataset Date Time Age Mortality day Mortality total Feed total Feed per bird Water total Water per bird Farm Shed DT Average weight 1A Average weight 1B Average weight 2A Average weight 2B Average weight 3A Average weight 3B Average weight 4A Average weight 4B Average weight 5A Average weight 6A Average weight 5B Average weight 6B Average Weight 6A1 Average weight 7A Average weight 8A 06/06/2022 23:50:01 -1.0 0.0 0.0 0.0 0.0 182.0 0.004 Park Farm 1 2022-06-06 23:50:00 06/06/2022 23:50:01 -1.0 0.0 0.0 0.0 0.0 105.0 0.003 Park Farm 2 2022-06-06 23:50:00 06/06/2022 23:50:01 -2.0 0.0 0.0 0.0 0.0 4.0 0.0 Park Farm 4 2022-06-06 23:50:00 06/06/2022 23:50:01 -1.0 0.0 0.0 0.0 0.0 82.0 0.003 Park Farm 3 2022-06-06 23:50:00 06/06/2022 23:50:01 Park Farm 1 2022-06-06 23:50:00 2494 0.0 2577.0 0.0 2460.0 0.0 2467.0 1972.0 06/06/2022 23:50:00 4.0 94.0 367.0 600.0 0.018 1473.0 0.044 Green Farm 1 2022-06-06 23:50:00 06/06/2022 23:50:00 4.0 72.0 239.0 340.0 0.01 1480.0 0.044 Green Farm 2 2022-06-06 23:50:00 06/06/2022 23:50:00 4.0 94.0 288.0 630.0 0.019 1443.0 0.043 Green Farm 3 2022-06-06 23:50:00 06/06/2022 23:50:00 3.0 88.0 176.0 290.0 0.009 487.0 0.015 Green Farm 4 2022-06-06 23:50:00 06/06/2022 23:50:00 3.0 105.0 248.0 520.0 0.016 365.0 0.011 Green Farm 5 2022-06-06 23:50:00 06/06/2022 23:50:00 3.0 72.0 168.0 560.0 0.017 289.0 0.009 Green Farm 6 2022-06-06 23:50:00 06/06/2022 23:50:00 Green Farm 1 2022-06-06 23:50:00 1861 1874.0 1990.0 2083.0 1959.0 2160.0 06/06/2022 23:50:01 27.0 40.0 1153.0 11649 0.249 Castle Farm 1 2022-06-06 23:50:00 06/06/2022 23:50:01 26.0 21.0 941.0 11289 0.261 Castle Farm 4 2022-06-06 23:50:00 06/06/2022 23:50:01 26.0 22.0 962.0 10277 0.236 Castle Farm 3 2022-06-06 23:50:00 06/06/2022 23:50:01 27.0 53.0 1004.0 12204 0.259 Castle Farm 2 2022-06-06 23:50:00 06/06/2022 23:50:01 6686.8 0.139 Castle Farm 1 2022-06-06 23:50:00 06/06/2022 23:50:01 6446.9 0.146 Castle Farm 4 2022-06-06 23:50:00 06/06/2022 23:50:01 6031.5 0.135 Castle Farm 3 2022-06-06 23:50:00 06/06/2022 23:50:01 6742.5 0.14 Castle Farm 2 2022-06-06 23:50:00 06/06/2022 23:50:01 Castle Farm 1 2022-06-06 23:50:00 1.508 06/06/2022 23:50:01 Castle Farm 4 2022-06-06 23:50:00 1.542 06/06/2022 23:50:01 Castle Farm 3 2022-06-06 23:50:00 1.493 06/06/2022 23:50:01 Castle Farm 2 2022-06-06 23:50:00 1.542 06/06/2022 23:50:01 24.0 36.0 1211.0 6380.0 0.156 9769.0 0.24 Blue Farm 1 2022-06-06 23:50:00 06/06/2022 23:50:01 24.0 31.0 1317.0 5860.0 0.144 9775.0 0.24 Blue Farm 2 2022-06-06 23:50:00 06/06/2022 23:50:01 24.0 29.0 1431.0 6470.0 0.159 9571.0 0.236 Blue Farm 2 2022-06-06 23:50:00 06/06/2022 23:50:01 24.0 28.0 947.0 5710.0 0.139 9755.0 0.238 Blue Farm 4 2022-06-06 23:50:00 06/06/2022 23:50:01 24.0 29.0 1089.0 6020.0 0.136 10399 0.234 Blue Farm 5 2022-06-06 23:50:00 06/06/2022 23:50:01 24.0 30.0 1489.0 5640.0 0.128 10303 0.234 Blue Farm 6 2022-06-06 23:50:00 06/06/2022 23:50:01 Blue Farm 15 2022-06-06 23:50:00 1289.0 1267.0 1268.0 1243.0 06/06/2022 23:50:01 Blue Farm 5 2022-06-06 23:50:00 1418 1257.0 1462.0 1320.0 1332.0 1309.0 877.0 1248.0 06/06/2022 23:50:38 1.0 0.0 0.0 0.0 0.0 Upper Farm 38 2022-06-06 23:50:00 06/06/2022 23:50:38 1.0 0.0 0.0 0.0 0.0 Upper Farm 3 2022-06-06 23:50:00 06/06/2022 23:50:38 Upper Farm 1 2022-06-06 23:50:00 2.849 06/06/2022 23:50:35 1.0 0.0 0.0 0.0 0.0 34.0 0.001 Seaside Farm 1 2022-06-06 23:50:00 06/06/2022 23:50:35 1.0 0.0 0.0 0.0 0.0 35.0 0.001 Seaside Farm 2 2022-06-06 23:50:00 06/06/2022 23:50:35 1.0 0.0 0.0 0.0 0.0 26.0 0.001 Seaside Farm 3 2022-06-06 23:50:00 06/06/2022 23:50:35 1.0 0.0 0.0 0.0 0.0 35.0 0.001 Seaside Farm 4 2022-06-06 23:50:00 06/06/2022 23:50:35 Seaside Farm 5 2022-06-06 23:50:00 39 40.0 43.0 42.0 45.0 46.0 46.0 46.0 A: I would start like this, this is assuming you only want one row/record per farm-shed. import pandas as pd import functools # dataframe is df # First combine horizontally: get the average weight into one column weight_cols = [col for col in df.columns if col.startswith("Average weight")] df2 = ( df.assign(**{ 'Average weight': lambda df: functools.reduce(pd.Series.combine_first, [df[col] for col in weight_cols]) }) .drop(columns=weight_cols) ) # Get first value from each column in each group grouped_by = ['Farm', 'Shed'] remaining_cols = df2.columns.difference(grouped_by, sort=False) (df2.groupby(grouped_by) .agg({col: "first" for col in remaining_cols}) .reset_index()) If you want to safeguard against duplicated data, more checks are needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/72516824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: tracking button click as goal in Google Analytics I am trying to do button click in GA, but getting this This Goal would have a 0% conversion rate based on your data from the past 7 days. Although in the Real Time report, there are conversations. I found this post and I have done exactly this. Goal type: Event Event conditions: Category; Equals to: button Action; Equals to: click Label; Equals to: trial-button and this is my html <a onclick="ga('send', 'event', 'button', 'click', 'trial-button');" href="https://www.ecanvasser.com/signup.php" target="_blank"><img src="/content/images/2016/10/button-1.PNG" alt="" title=""></a> Unlike the user in that post, I am not using yoat plugin. but still its not working. UPDATE I just checked the GA and now it's showing This Goal would have a 1.47% conversion rate based on your data from the past 7 days. What does this mean? Does it mean that I have implemented it correctly ?
{ "language": "en", "url": "https://stackoverflow.com/questions/39959282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to send a html file with css as a response to a connecting client using express So I've been trying to figure this out for a while now and the answers that I have found are just confusing, vague without explanation and or, do not work - (At least for me). First here is my project structure. .. denotes a folder - denotes a file while four | denote a sub directory or file in parent folder ..public |||| ..html&css |||| |||| ..main |||| |||| |||| - main.html |||| |||| |||| - main.css |||| ..javascript |||| |||| -server.js Hopefully the above project structure is understandable, Stack Overflows formatting is tough to work with. Here is my code - server.js let express = require('express'); let app = express(); app.use(express.static('../html&css')); let server = app.listen(8080, function () { app.get(function (req, res) { res.sendFile(); }); }); let port = server.address().port; console.log(`Express app listening at ${port}`); I have seen a few ways to send the files when someone connects to the server, and have managed to get html to send but never both html and css. From researching I've seen a few ways to do this but the way in which they are explained is confusing and no answers I found explain in detail how to accomplish my question along with what and why your doing the things they are saying to accomplish it. I have just been getting a lot about routes, static, app.get this and app.get that, res.sendFile and some other mumbojumbo but not any of it is really making sense. It also doesn't help that most of the answers don't have the persons complete project structure. If they did understanding which routes were doing what would be much easier. This link seemed to be the best answer I came across but because of lack of project structure I cannot implement it into my own project and thus understand how it works. If someone could even just explain how that works with a project structure implemented in their answer I would be grateful, otherwise if they have another way of doing it through the use of the fs module and express or something else. I hope my question is understandable clear. Thank you for your time. A: I am going to explain how it works. But the code you have written is correct. Even I ran the code. let express = require('express'); let app = express(); app.use(express.static('../html&css')); let server = app.listen(8080, function () { app.get(function (req, res) { res.sendFile(); }); }); let port = server.address().port; console.log(`Express app listening at ${port}`); Now, what express.static do? it exposes the particular folder and makes auto routes. If you want to access main.css it will be hosted on localhost:8080/main/main.css In the main.html to use that CSS you just add a link. <link rel="stylesheet" href="main.css"> or <link rel="stylesheet" href="/main/main.css"> But, you cannot HTTP GET let's say localhost:8080/main that will not work. So, you need to run the server by typing node javascript/server.js and it will run just fine. But as the server.js is a backend code do not put it in the public folder. Maybe make a folder called src and put it there. A: Let's look a a few things. First, folder structure: According to your setup, you have your server.js file embedded within the public folder, albeit one level down. If you think of an MVC framework, see this sample tutorial, you want to put your server at the root of your application (not inside of the JavaScript folder inside public where you would serve any client-side javascript. Second, regarding middleware: When you call the express.static middleware, you will want to use the path module to create an absolute rather than relative path to the public folder, which is especially important for deployment. app.use(express.static(path.join(__dirname, 'public'))); Now, you will be able to access all the files in your public folder like so: http://localhost:8080/main/* http://localhost:8080/javascript/* Of course * refers to whatever files are there. Third, regarding app.listen: The callback to app.listen is expecting to be returned a server object. See the documentation. Rather than setting up a listener on a route here, you should establish that outside of the app.listen call. For instance, you may want to set up a basic get route to serve your main.html page on /. That's up to you. The express.static middleware is already serving this page as /main/main.html. app.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'public', 'main.html')); }); let server = app.listen(8080);
{ "language": "en", "url": "https://stackoverflow.com/questions/51658834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server reporting services version issue I am facing following error during deployment of SSRS report on server. The definition of this report is not valid or supported by this version of Reporting Services. I have been trying to find out issue on internet for two days but no luck. Reporting Services version on Server:12.0.2000.8 On my local machine I have SQLManagementStudio_x64_ENU 2014, SQLEXPR_x64_ENU and VS2012 BIDS. We have few other reports already running on server. When I create a new one and try to deploy on server I got the above error. Please help. A: The version of SSRS (Reporting Services) is 12.0.2000.8 which according to https://sqlserverbuilds.blogspot.com/ is SQL Server 2014. If the version of SSRS is 2014 then it is not possible to deploy an SSRS report created using Visual Studio 2012 BIDS. As an alternatively you can use Visual Studio 2017 which can deploy to SSRS 2008, 2008 R2 2012, 2014, and 2016 upwards. See this answer for a screenshot of where you can make the changes. This is the method I used to deploy SSRS reports to a 2012 and then a 2016 installation of SSRS.
{ "language": "en", "url": "https://stackoverflow.com/questions/59661768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can a SignalR Application run on IIS 8.5 on Windows Server 2012 R2? Plain and simple: Is it even possible for a SignalR Application to run off IIS 8.5 on Windows Server 2012 R2, or is this not a compatible setup? There are tons of threads all over Stack Overflow that pose the same issue, that the dynamically generated script located at signalr/hubs is 404ing, but the threads with solutions are not using my iis/server setup. I tried following the tutorial at https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr but it seems that it only works in Visual Studio's IIS Express. As soon as I move the application to our server, I get the error everyone else on SO is getting. Here's the supported platforms for Signalr on the official documentation: https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/supported-platforms It stops short of Windows Server 2012 R2, but the documentation is dated. Any advice is appreciated. A: Yes, Windows Server 2012 R2 and Windows Server 2016 both support SignalR. Just ensure WebSocket support is enabled and you're all set. IIS Express is a cut-down version of IIS (which frustratingly does not work with IIS Manager), but internally it uses the same execution engine (including HTTP.sys integration) so it uses the same web.config files as the full-fat IIS too, so it supports SignalR too. ("IIS Express" is a thing because previously VS shipped with a simple web-server called Cassini, which used ASP.NET System.Web.dll for everything, which worked for simple applications but for more complex applications there was sufficient differing behaviour that it made development difficult)
{ "language": "en", "url": "https://stackoverflow.com/questions/42169544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }