text:
Q: Android rest template - GET request - Too many redirects I have a REST GET request that triggers redirects or so it seems...
Here is the log output:
D/AndroidRuntime( 1353): Shutting down VM
W/dalvikvm( 1353): threadid=1: thread exiting with uncaught exception (group=0xb2ab3b90)
E/AndroidRuntime( 1353): FATAL EXCEPTION: main
E/AndroidRuntime( 1353): Process: com.thalasoft.learnintouch.android, PID: 1353
E/AndroidRuntime( 1353): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thalasoft.learnintouch.android/com.thalasoft.learnintouch.android.AdminActivity}: org.springframework.web.client.ResourceAccessException: I/O error: Too many redirects: 21; nested exception is java.net.ProtocolException: Too many redirects: 21
The REST client code:
public class AdminActivity extends Activity {

    private static final String REST_HOST = "10.0.2.2";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.admin_layout);
    }

    @Override
    public void onStart() {
        super.onStart();

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        HttpHeaders httpHeaders = Common.createAuthenticationHeaders("joethebouncer" + ":" + "mypassword");
        Admin admin = null;
        try {
            ResponseEntity<Admin> responseEntity = restTemplate.exchange("http://" + REST_HOST + ":8080/learnintouch-rest/admin/" + 623L, HttpMethod.GET, new HttpEntity<Object>(httpHeaders), Admin.class);

            if (responseEntity != null) {
                admin = responseEntity.getBody();
                if (admin != null) {
                    TextView textView = (TextView) this.findViewById(R.id.id);
                    textView.setText(Long.toString(admin.getId()));

                    textView = (TextView) this.findViewById(R.id.email);
                    textView.setText(admin.getEmail());

                    textView = (TextView) this.findViewById(R.id.firstname);
                    textView.setText(admin.getFirstname());

                    textView = (TextView) this.findViewById(R.id.lastname);
                    textView.setText(admin.getLastname());

                    textView = (TextView) this.findViewById(R.id.login);
                    textView.setText(admin.getLogin());

                    textView = (TextView) this.findViewById(R.id.password);
                    textView.setText(admin.getPassword());

                    textView = (TextView) this.findViewById(R.id.passwordSalt);
                    textView.setText(admin.getPasswordSalt());
                }
            }
        } catch (HttpClientErrorException e) {
            Log.e("Msg", ">>>>>>>>>>>>>>>> Could not request the rest service " + e.getLocalizedMessage());
        }
    }

}

Here is the Spring REST controller:
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseEntity<Admin> findOne(@PathVariable Long id, UriComponentsBuilder builder) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json; charset=utf-8");
    OneAdminEvent oneAdminEvent;
    try {
        oneAdminEvent = adminService.findById(new GetOneAdminEvent(id));
    } catch (NotFoundException e) {
        return new ResponseEntity<Admin>(responseHeaders, HttpStatus.NOT_FOUND);
    }
    responseHeaders.setLocation(builder.path("/admin/{id}").buildAndExpand(oneAdminEvent.getEventAdmin().getId()).toUri());
    Admin admin = adminResourceAssembler.toResource(oneAdminEvent.getEventAdmin());
    ResponseEntity<Admin> responseEntity = new ResponseEntity<Admin>(admin, responseHeaders, HttpStatus.FOUND);
    return responseEntity;
}

I can manually test my server side REST service with a curl request:
curl --user joethebouncer:mypassword http://localhost:8080/learnintouch-rest/admin/623
{"links":[{"rel":"self","href":"http://localhost:8080/learnintouch-rest/admin/623"}],"id2":null,"firstname":"Stephane","lastname":"Eybert","email":"joethebouncer@thalasoft.com","login":"joethebouncer","password":"e41de4c55873f9c000f4cdaac6efd3aa","passwordSalt":"7bc7bf5f94fef7c7106afe5c3a40a2"}

And it does not do any redirect.
Here is the server side console output when running the Andoid app REST GET request:
2013-12-05 11:12:13,446 DEBUG  [DispatcherServlet] Successfully completed request
2013-12-05 11:12:13,446 DEBUG  [ExceptionTranslationFilter] Chain processed normally
2013-12-05 11:12:13,446 DEBUG  [SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completed
2013-12-05 11:12:13,471 DEBUG  [AntPathRequestMatcher] Checking match of request : '/admin/623'; against '/admin/**'
2013-12-05 11:12:13,471 DEBUG  [FilterChainProxy] /admin/623 at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2013-12-05 11:12:13,471 DEBUG  [HttpSessionSecurityContextRepository] No HttpSession currently exists
2013-12-05 11:12:13,471 DEBUG  [HttpSessionSecurityContextRepository] No SecurityContext was available from the HttpSession: null. A new one will be created.
2013-12-05 11:12:13,471 DEBUG  [FilterChainProxy] /admin/623 at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter'
2013-12-05 11:12:13,471 DEBUG  [FilterChainProxy] /admin/623 at position 3 of 9 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2013-12-05 11:12:13,471 DEBUG  [BasicAuthenticationFilter] Basic Authentication Authorization header found for user 'joethebouncer'
2013-12-05 11:12:13,471 DEBUG  [ProviderManager] Authentication attempt using com.thalasoft.learnintouch.rest.security.CustomAuthenticationProvider
2013-12-05 11:12:13,471 DEBUG  [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-12-05 11:12:13,471 DEBUG  [JpaTransactionManager] Creating new transaction with name [com.thalasoft.learnintouch.data.service.jpa.AdminServiceImpl.findByLogin]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
2013-12-05 11:12:13,471 DEBUG  [JpaTransactionManager] Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@1812c48] for JPA transaction
2013-12-05 11:12:13,471 DEBUG  [DriverManagerDataSource] Creating new JDBC DriverManager Connection to [jdbc:log4jdbc:mysql://127.0.0.1:3306/db_integration]
2013-12-05 11:12:13,478 DEBUG  [JpaTransactionManager] Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@e9ac75]
Hibernate:
    select
        admin0_.id as id14_,
        admin0_.version as version14_,
        admin0_.address as address14_,
        admin0_.city as city14_,
        admin0_.country as country14_,
        admin0_.email as email14_,
        admin0_.firstname as firstname14_,
        admin0_.lastname as lastname14_,
        admin0_.login as login14_,
        admin0_.password as password14_,
        admin0_.password_salt as password11_14_,
        admin0_.post_login_url as post12_14_,
        admin0_.preference_admin as preference13_14_,
        admin0_.profile as profile14_,
        admin0_.super_admin as super15_14_,
        admin0_.zip_code as zip16_14_
    from
        admin admin0_
    where
        admin0_.login=? limit ?
2013-12-05 11:12:13,480 TRACE  [BasicBinder] binding parameter [1] as [VARCHAR] - joethebouncer
2013-12-05 11:12:13,481 DEBUG  [sqlonly]  org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
282. select admin0_.id as id14_, admin0_.version as version14_, admin0_.address as address14_, admin0_.city
as city14_, admin0_.country as country14_, admin0_.email as email14_, admin0_.firstname as
firstname14_, admin0_.lastname as lastname14_, admin0_.login as login14_, admin0_.password
as password14_, admin0_.password_salt as password11_14_, admin0_.post_login_url as post12_14_,
admin0_.preference_admin as preference13_14_, admin0_.profile as profile14_, admin0_.super_admin
as super15_14_, admin0_.zip_code as zip16_14_ from admin admin0_ where admin0_.login='joethebouncer'
limit 2
2013-12-05 11:12:13,484 TRACE  [BasicExtractor] found [623] as column [id14_]
2013-12-05 11:12:13,485 TRACE  [BasicExtractor] found [0] as column [version14_]
2013-12-05 11:12:13,486 TRACE  [BasicExtractor] found [] as column [address14_]
2013-12-05 11:12:13,486 TRACE  [BasicExtractor] found [] as column [city14_]
2013-12-05 11:12:13,487 TRACE  [BasicExtractor] found [] as column [country14_]
2013-12-05 11:12:13,488 TRACE  [BasicExtractor] found [joethebouncer@thalasoft.com] as column [email14_]
2013-12-05 11:12:13,488 TRACE  [BasicExtractor] found [Stephane] as column [firstname14_]
2013-12-05 11:12:13,489 TRACE  [BasicExtractor] found [Eybert] as column [lastname14_]
2013-12-05 11:12:13,489 TRACE  [BasicExtractor] found [joethebouncer] as column [login14_]
2013-12-05 11:12:13,490 TRACE  [BasicExtractor] found [e41de4c55873f9c000f4cdaac6efd3aa] as column [password14_]
2013-12-05 11:12:13,491 TRACE  [BasicExtractor] found [7bc7bf5f94fef7c7106afe5c3a40a2] as column [password11_14_]
2013-12-05 11:12:13,491 TRACE  [BasicExtractor] found [null] as column [post12_14_]
2013-12-05 11:12:13,492 TRACE  [BasicExtractor] found [false] as column [preference13_14_]
2013-12-05 11:12:13,492 TRACE  [BasicExtractor] found [] as column [profile14_]
2013-12-05 11:12:13,493 TRACE  [BasicExtractor] found [true] as column [super15_14_]
2013-12-05 11:12:13,493 TRACE  [BasicExtractor] found [] as column [zip16_14_]
2013-12-05 11:12:13,496 DEBUG  [JpaTransactionManager] Initiating transaction commit
2013-12-05 11:12:13,496 DEBUG  [JpaTransactionManager] Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@1812c48]
2013-12-05 11:12:13,499 DEBUG  [JpaTransactionManager] Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@1812c48] after transaction
2013-12-05 11:12:13,499 DEBUG  [EntityManagerFactoryUtils] Closing JPA EntityManager
2013-12-05 11:12:13,499 DEBUG  [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-12-05 11:12:13,499 DEBUG  [JpaTransactionManager] Creating new transaction with name [com.thalasoft.learnintouch.data.service.jpa.AdminServiceImpl.checkPassword]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
2013-12-05 11:12:13,499 DEBUG  [JpaTransactionManager] Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@97f1ff] for JPA transaction
2013-12-05 11:12:13,499 DEBUG  [DriverManagerDataSource] Creating new JDBC DriverManager Connection to [jdbc:log4jdbc:mysql://127.0.0.1:3306/db_integration]
2013-12-05 11:12:13,507 DEBUG  [JpaTransactionManager] Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@16354d0]
2013-12-05 11:12:13,507 DEBUG  [JpaTransactionManager] Initiating transaction commit
2013-12-05 11:12:13,507 DEBUG  [JpaTransactionManager] Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@97f1ff]
2013-12-05 11:12:13,509 DEBUG  [JpaTransactionManager] Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@97f1ff] after transaction
2013-12-05 11:12:13,509 DEBUG  [EntityManagerFactoryUtils] Closing JPA EntityManager
2013-12-05 11:12:13,509 DEBUG  [BasicAuthenticationFilter] Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@833e8985: Principal: joethebouncer; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN
2013-12-05 11:12:13,509 DEBUG  [FilterChainProxy] /admin/623 at position 4 of 9 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2013-12-05 11:12:13,509 DEBUG  [FilterChainProxy] /admin/623 at position 5 of 9 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2013-12-05 11:12:13,509 DEBUG  [FilterChainProxy] /admin/623 at position 6 of 9 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2013-12-05 11:12:13,509 DEBUG  [AnonymousAuthenticationFilter] SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@833e8985: Principal: joethebouncer; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN'
2013-12-05 11:12:13,509 DEBUG  [FilterChainProxy] /admin/623 at position 7 of 9 in additional filter chain; firing Filter: 'SessionManagementFilter'
2013-12-05 11:12:13,509 DEBUG  [HttpSessionSecurityContextRepository] HttpSession being created as SecurityContext is non-default
2013-12-05 11:12:13,509 DEBUG  [HttpSessionSecurityContextRepository] SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl@833e8985: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@833e8985: Principal: joethebouncer; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN'
2013-12-05 11:12:13,510 DEBUG  [FilterChainProxy] /admin/623 at position 8 of 9 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2013-12-05 11:12:13,510 DEBUG  [FilterChainProxy] /admin/623 at position 9 of 9 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2013-12-05 11:12:13,510 DEBUG  [FilterSecurityInterceptor] Secure object: FilterInvocation: URL: /admin/623; Attributes: [hasRole('ROLE_ADMIN')]
2013-12-05 11:12:13,510 DEBUG  [FilterSecurityInterceptor] Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@833e8985: Principal: joethebouncer; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN
2013-12-05 11:12:13,510 DEBUG  [AffirmativeBased] Voter: org.springframework.security.web.access.expression.WebExpressionVoter@115654d, returned: 1
2013-12-05 11:12:13,510 DEBUG  [FilterSecurityInterceptor] Authorization successful
2013-12-05 11:12:13,510 DEBUG  [FilterSecurityInterceptor] RunAsManager did not change Authentication object
2013-12-05 11:12:13,510 DEBUG  [FilterChainProxy] /admin/623 reached end of additional filter chain; proceeding with original chain
2013-12-05 11:12:13,510 DEBUG  [DispatcherServlet] DispatcherServlet with name 'dispatcher' processing GET request for [/learnintouch-rest/admin/623]
2013-12-05 11:12:13,510 DEBUG  [RequestMappingHandlerMapping] Looking up handler method for path /admin/623
2013-12-05 11:12:13,511 DEBUG  [RequestMappingHandlerMapping] Returning handler method [public org.springframework.http.ResponseEntity<com.thalasoft.learnintouch.rest.domain.Admin> com.thalasoft.learnintouch.rest.controller.AdminController.findOne(java.lang.Long,org.springframework.web.util.UriComponentsBuilder)]
2013-12-05 11:12:13,511 DEBUG  [DefaultListableBeanFactory] Returning cached instance of singleton bean 'adminController'
2013-12-05 11:12:13,511 DEBUG  [DispatcherServlet] Last-Modified value for [/learnintouch-rest/admin/623] is: -1
2013-12-05 11:12:13,511 DEBUG  [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-12-05 11:12:13,511 DEBUG  [JpaTransactionManager] Creating new transaction with name [com.thalasoft.learnintouch.data.service.jpa.AdminServiceImpl.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
2013-12-05 11:12:13,511 DEBUG  [JpaTransactionManager] Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@b410a] for JPA transaction
2013-12-05 11:12:13,512 DEBUG  [DriverManagerDataSource] Creating new JDBC DriverManager Connection to [jdbc:log4jdbc:mysql://127.0.0.1:3306/db_integration]
2013-12-05 11:12:13,520 DEBUG  [JpaTransactionManager] Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@a709f3]
2013-12-05 11:12:13,520 DEBUG  [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-12-05 11:12:13,520 DEBUG  [JpaTransactionManager] Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl@b410a] for JPA transaction
2013-12-05 11:12:13,520 DEBUG  [JpaTransactionManager] Participating in existing transaction
Hibernate:
    select
        admin0_.id as id14_0_,
        admin0_.version as version14_0_,
        admin0_.address as address14_0_,
        admin0_.city as city14_0_,
        admin0_.country as country14_0_,
        admin0_.email as email14_0_,
        admin0_.firstname as firstname14_0_,
        admin0_.lastname as lastname14_0_,
        admin0_.login as login14_0_,
        admin0_.password as password14_0_,
        admin0_.password_salt as password11_14_0_,
        admin0_.post_login_url as post12_14_0_,
        admin0_.preference_admin as preference13_14_0_,
        admin0_.profile as profile14_0_,
        admin0_.super_admin as super15_14_0_,
        admin0_.zip_code as zip16_14_0_
    from
        admin admin0_
    where
        admin0_.id=?
2013-12-05 11:12:13,522 TRACE  [BasicBinder] binding parameter [1] as [BIGINT] - 623
2013-12-05 11:12:13,523 DEBUG  [sqlonly]  org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
284. select admin0_.id as id14_0_, admin0_.version as version14_0_, admin0_.address as address14_0_,
admin0_.city as city14_0_, admin0_.country as country14_0_, admin0_.email as email14_0_, admin0_.firstname
as firstname14_0_, admin0_.lastname as lastname14_0_, admin0_.login as login14_0_, admin0_.password
as password14_0_, admin0_.password_salt as password11_14_0_, admin0_.post_login_url as post12_14_0_,
admin0_.preference_admin as preference13_14_0_, admin0_.profile as profile14_0_, admin0_.super_admin
as super15_14_0_, admin0_.zip_code as zip16_14_0_ from admin admin0_ where admin0_.id=623
2013-12-05 11:12:13,527 TRACE  [BasicExtractor] found [0] as column [version14_0_]
2013-12-05 11:12:13,528 TRACE  [BasicExtractor] found [] as column [address14_0_]
2013-12-05 11:12:13,529 TRACE  [BasicExtractor] found [] as column [city14_0_]
2013-12-05 11:12:13,529 TRACE  [BasicExtractor] found [] as column [country14_0_]
2013-12-05 11:12:13,531 TRACE  [BasicExtractor] found [joethebouncer@thalasoft.com] as column [email14_0_]
2013-12-05 11:12:13,532 TRACE  [BasicExtractor] found [Stephane] as column [firstname14_0_]
2013-12-05 11:12:13,532 TRACE  [BasicExtractor] found [Eybert] as column [lastname14_0_]
2013-12-05 11:12:13,533 TRACE  [BasicExtractor] found [joethebouncer] as column [login14_0_]
2013-12-05 11:12:13,534 TRACE  [BasicExtractor] found [e41de4c55873f9c000f4cdaac6efd3aa] as column [password14_0_]
2013-12-05 11:12:13,535 TRACE  [BasicExtractor] found [7bc7bf5f94fef7c7106afe5c3a40a2] as column [password11_14_0_]
2013-12-05 11:12:13,536 TRACE  [BasicExtractor] found [null] as column [post12_14_0_]
2013-12-05 11:12:13,537 TRACE  [BasicExtractor] found [false] as column [preference13_14_0_]
2013-12-05 11:12:13,537 TRACE  [BasicExtractor] found [] as column [profile14_0_]
2013-12-05 11:12:13,538 TRACE  [BasicExtractor] found [true] as column [super15_14_0_]
2013-12-05 11:12:13,539 TRACE  [BasicExtractor] found [] as column [zip16_14_0_]
2013-12-05 11:12:13,543 DEBUG  [JpaTransactionManager] Initiating transaction commit
2013-12-05 11:12:13,543 DEBUG  [JpaTransactionManager] Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@b410a]
2013-12-05 11:12:13,546 DEBUG  [JpaTransactionManager] Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@b410a] after transaction
2013-12-05 11:12:13,546 DEBUG  [EntityManagerFactoryUtils] Closing JPA EntityManager
2013-12-05 11:12:13,555 DEBUG  [HttpSessionSecurityContextRepository] SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl@833e8985: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@833e8985: Principal: joethebouncer; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN'
2013-12-05 11:12:13,556 DEBUG  [HttpSessionSecurityContextRepository] SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl@833e8985: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@833e8985: Principal: joethebouncer; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN'
2013-12-05 11:12:13,556 DEBUG  [HttpEntityMethodProcessor] Written [links: [<http://10.0.2.2:8080/learnintouch-rest/admin/623>;rel="self"]] as "application/json;charset=utf-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@b72a5e]
2013-12-05 11:12:13,556 DEBUG  [DispatcherServlet] Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling
2013-12-05 11:12:13,556 DEBUG  [DispatcherServlet] Successfully completed request
2013-12-05 11:12:13,556 DEBUG  [ExceptionTranslationFilter] Chain processed normally
2013-12-05 11:12:13,556 DEBUG  [SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completed

Also, wireshark shows only these two frames repeatedly:
No.     Time           Source                Destination           Protocol Length Info
    320 20.659878000   127.0.0.1             127.0.0.1             HTTP     375    GET /learnintouch-rest/admin/623 HTTP/1.1

Frame 320: 375 bytes on wire (3000 bits), 375 bytes captured (3000 bits) on interface 0
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1 (127.0.0.1), Dst: 127.0.0.1 (127.0.0.1)
Transmission Control Protocol, Src Port: 57253 (57253), Dst Port: http-alt (8080), Seq: 1, Ack: 1, Len: 309
Hypertext Transfer Protocol

No.     Time           Source                Destination           Protocol Length Info
    427 20.741684000   127.0.0.1             127.0.0.1             HTTP     71     HTTP/1.1 302 Found  (application/json)

Frame 427: 71 bytes on wire (568 bits), 71 bytes captured (568 bits) on interface 0
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1 (127.0.0.1), Dst: 127.0.0.1 (127.0.0.1)
Transmission Control Protocol, Src Port: http-alt (8080), Dst Port: 57253 (57253), Seq: 615, Ack: 310, Len: 5
[2 Reassembled TCP Segments (619 bytes): #425(614), #427(5)]
Hypertext Transfer Protocol
JavaScript Object Notation: application/json

No.     Time           Source                Destination           Protocol Length Info
    429 20.794399000   127.0.0.1             127.0.0.1             HTTP     375    GET /learnintouch-rest/admin/623 HTTP/1.1

Frame 429: 375 bytes on wire (3000 bits), 375 bytes captured (3000 bits) on interface 0
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1 (127.0.0.1), Dst: 127.0.0.1 (127.0.0.1)
Transmission Control Protocol, Src Port: 57253 (57253), Dst Port: http-alt (8080), Seq: 310, Ack: 620, Len: 309
Hypertext Transfer Protocol

No.     Time           Source                Destination           Protocol Length Info
    517 20.872213000   127.0.0.1             127.0.0.1             HTTP     71     HTTP/1.1 302 Found  (application/json)

Frame 517: 71 bytes on wire (568 bits), 71 bytes captured (568 bits) on interface 0
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1 (127.0.0.1), Dst: 127.0.0.1 (127.0.0.1)
Transmission Control Protocol, Src Port: http-alt (8080), Dst Port: 57253 (57253), Seq: 1234, Ack: 619, Len: 5
[2 Reassembled TCP Segments (619 bytes): #515(614), #517(5)]
Hypertext Transfer Protocol
JavaScript Object Notation: application/json

Any clue ?
Kind Regards,

A: The http status code FOUND 302 is used to trigger a redirection on a moved temporarily resource. Not what I wanted here. Instead, I will use the OK 200 status code.
Here is how the REST controller response now looks like:
ResponseEntity<Admin> responseEntity = new ResponseEntity<Admin>(admin, responseHeaders, HttpStatus.OK);


text:
Q: flutter: Convert Text and other widgets to JSON (or another solution to add parameters to routes when generating programmatically)? I have a bunch of Activitys that keep track of the state of user activities in the app. Ideally, I'd also like to add information about how the Activity should appear as a MenuButton. I tried adding the first aspect, a simple Text Widget, but it immediately failed since the Text widget cannot be converted to JSON.
class Activity {
  String state;
  bool visible;
  DateTime visibleAfter;
  bool firstView;
  Widget text;   // <----- this doesn't work

  Activity(this.state, this.visible, this.visibleAfter, this.firstView, this.text);

  Map<String, dynamic> toJson() => {
        'state': state,
        'visible': visible,
        'visibleAfter': visibleAfter.toIso8601String(),
        'firstView': firstView,
        'text': text,   // <----- this doesn't work
      };

  factory Activity.fromJson(Map<String, dynamic> json) {
    return new Activity(
        json['state'], json['visible'], DateTime.parse(json['visibleAfter']), json['firstView'], json['text']);
  }
}

My fallback has been to have a Map in the main page that I could use to build the MenuMain buttons. However, it now appears to be insufficient now that I wish to pass a callback function to certain routes. When I try and add a callback function in the Map, I get an error "Only static members can access initializers".
TLDR: Not sure how I can add parameters to call routes programatically.

A: You can use Dart converter library to parse your Json, you don't need to create your own implementation. According to the docs Dart Convert library you can use Json Decoder and Encoder to do that.
Also for passing callback as parameters, you should try to create a Function attribute in your Activity class, if it makes sense to you.
eg.
final Function callback;

Then you can pass this Function attribute to another route using Navigator:
  Navigator.of(ctx).pushNamed('/yourroute', arguments: {
  'callback': activity.callback
});

And then in your other route you can get the callback/function attribute like this:
    final routeArgs =
    ModalRoute.of(context).settings.arguments as Map<String, String>;
final activityCallback = routeArgs['callback'];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Making changes to multiple copies of the same file in a repository I'm new to github and have created a repository with multiple folders. Each folder has a copy of the same file (say abc.txt). I've linked my account to github desktop, so I have a matching local repository.
I constantly make changes to abc.txt in one of my local folders, but I want to push that change on to ALL copies of abc.txt in my online repository. The obvious alternative is to just copy and replace all copies of abc.txt on my local machine by the latest version, and push my entire local repository online, but surely there's a better way?


text:
Q: Vortex equation on Riemann surface and a similar equation Let's take a Riemann surface $(X,\omega)$ and a holomorphic line bundle $L$ on it with a hermitian metric $h$ on $L$. $g$ be a real valued smooth function on $X$ and we consider the following two sets of equations on $X$ for sections $\phi,\psi$ and connections $A,B$ compatible with $h$ on $L$.
\begin{equation}
\bar\partial\phi=0, F_A=\frac{i}{4}(|\phi|^2-a)\omega, a>>0
\end{equation}
\begin{equation}
\bar\partial\psi=0, F_B=\frac{i}{4}(e^g|\psi|^2-b)\omega, b>>0
\end{equation}
The first on is the well known Vortex equations and the second one is similar to it and both can be solved (upto gauge) using similar technique, e.g., using Kadzan-Warner's equation. My question is: can we get solutions of the second set of equations from the first one, maybe with $a=b,$ or with some sort of similar assumption, at least up to gauge?


text:
Q: Video width is different in different devices I have a special video when i want to get this video's width code returns different value for Samsung galaxy s6 and Samsung note 3. I tested many different codes and libraries, but result is the same.
in Samsung galaxy s6: 640x480
in Samsung note 3: 853x480
when I open this video with Gspot program it shows:

Recommended Display Size: 853x480

and this is the same value is returned by our IOS app tested in Iphone 7. aspect radio is not the same and this is big problem.
here is some of codes I tested:
(1)
    MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
    metaRetriever.setDataSource(path);
    Bitmap bmp = metaRetriever.getFrameAtTime(-1);

    int height = bmp.getHeight();
    int width = bmp.getWidth();

(2)
    MediaPlayer myMediaPlayer= MediaPlayer.create(ApplicationLoader.applicationContext,
                                     Uri.fromFile(new File(path)));

    width = myMediaPlayer.getVideoWidth();
    height = myMediaPlayer.getVideoHeight();

(3)
 MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
        metaRetriever.setDataSource(path);
 String heights = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
        String widths = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
    int height = Integer.valueOf(heights);
        int width = Integer.valueOf(widths);

(4)
  MediaPlayer myMediaPlayer= MediaPlayer.create(ApplicationLoader.applicationContext, Uri.fromFile(new File(path)));
            myMediaPlayer.setOnVideoSizeChangedListener((mp, width, height) -> {
        int videoWidth = width;
        int videoHeight = height;
    );
            myMediaPlayer.setDataSource(path);
            myMediaPlayer.prepare();

FFmpegMediaMetadataRetriever, FFmpeg Java, ExoPlayer and some other libraries returns the same result.

A: try to scale images with DPI scale of device, i had same problem with premade bitmaps original pixel width was scaled like that.


text:
Q: How to return JSON data in separate li elements I'm trying to map through the below json file and display the 'list' array in separate
 elements on the page but the entire list array just displays in one
 element altogether. Is there a way to separate them into their own
 elements?
Here is what the 'blog' JSON file looks like:
[
  {
    "id": 1,
    "title": "This is a title",
    "list": [
      "hello test 1",
      "hello test 2",
      "hello test 3"
    ]
  }
]

Here is how I'm displaying them in React:

  {Blog.map((blogDetail, index) => {
     return
{blogDetail.list}

  })}

A:

  {Blog.map((blogDetail, index) => {
     return (
       <>
       {blogDetail.list.map((each) => {
          return
{each}

        })}
       </>
     )
  })}


text:
Q: How delete all files in a folder except last 5 items with Python I am looking for a way how to clean a folder from files, except last newest five items with Python.
I am quite new to Python, so I was able to keep the last one only with max() function, but I am not able to find out how to keep 5 last files.
Does anyone have similar issue?
Thank you for any idea.

A: User os.listdir to get the name of the files. As this returns an iterator you can easily sort the way you want in python itself. then use list indexing to keep the last five ones.
then use os.remove to remove the files
import os
for filename in sorted(os.listdir("foldername"))[:-5]:
    filename_relPath = os.path.join("foldername",filename)
    os.remove(filename_relPath)

A: At Python standard library level, os.scandir retrieves both the file name and its attributes. It is then easy to sort the files according to their modification time:
filenames = [entry.name for entry in sorted(os.scandir(path),
                                            key=lambda x: x.stat().st_mtime, reverse=True)]

Will return a list of all filenames in path folder sorted from newest to oldest. You can then iterate on filenames[5:] to remove all the files except the 5 newest ones.

A: you can try with this if you are on linux:
import os

directory = /path/to/directory

os.system("cd " + directory + " ls -t1 | tail -n +5 | xargs rm -r")

you can try with this if you are on windows:
import os

directory = /path/to/directory

os.system('for /r "skip=5 delims=" %%a in ("dir ' + directory + ' ") do echo del /f "%%a"')

or just run this on cmd:
for /r "skip=5 delims=" %%a in ('dir /path/to/folder') do echo del /f "%%a"


text:
Q: How to search with radio Button in c# Table Form
I'm trying to filter this table with RadioButton when DateDePublication is Checked and the value of the search text equals for example 2000 table should return all books who have DateDePublication equals to 2000
this is Search Button code :
private void RechBtn_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = repository.GetAllLivres(rechtext.Text);

        }

and search method code to return all books :
public List<Livre> FilterDateDePublication(string date)
    {
        using (var connection = factory.CreateConnection())
        {
            var livres = new List<Livre>();
            connection.ConnectionString = connectionString;
            connection.Open();
            var command = factory.CreateCommand();
            command.Connection = connection;
            command.CommandText = "select * from livre where date_publication like '%" + date + "%'";
            using (DbDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Livre l = new Livre();
                    l.Isbn = reader["isbn"].ToString();
                    l.Titre = reader["titre"].ToString();
                    l.DatePublication = DateTime.Parse(reader["date_publication"].ToString());
                    l.NombrePage = Int32.Parse(reader["nombre_page"].ToString());
                    l.Couverture = reader["couverture"].ToString();
                    l.Prix = Double.Parse(reader["nombre_page"].ToString());
                    l.QuantiteDisponible = Int32.Parse(reader["quantite_disponible"].ToString());
                }
            }
            return livres;

        }

A: your function GetAllLivres just looks for books with a specifc string in their title.
command.CommandText = "select * from livre where titre like '%" + mc + "%'";

You should change that to search on the pub date. Can says how that should look because we dont know your database scheme.
By the way , do not build SQL like that, its a huge security hole. Use parametrized queries

A:
I know i have 4 radio buttons when one of them is checked Search function should look up by each of radio button.

Well again not seeing the UI its hard to say but my guess is you have something like this
   |-search by: --------| <<< group box
   | ( ) Author         |  << radio buttons
   | ( ) title          |
   | (*) Year           |
   ----------------------
   Search for :_________________: <<== text box
   [Start Search]                 <<== button

I hope so.
So do this
 if(radioYear.Checked){
        FilterDateDePublication(searchText.Text);
 }
 else if(radioAuthor.Checked)
    .......

Note that the date the user enters might not match the format of the date in the database, in that case you need to do some massaging
I would however refactor your code, you have surely noticed that 90% of your FilterDateDePublication is the same as the title one.
You should do
public List<Livre> ReadBooks(string query)
{
    using (var connection = factory.CreateConnection())
    {
        var livres = new List<Livre>();
        connection.ConnectionString = connectionString;
        connection.Open();
        var command = factory.CreateCommand();
        command.Connection = connection;
        command.CommandText = query;
        using (DbDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                Livre l = new Livre();
                l.Isbn = reader["isbn"].ToString();
                l.Titre = reader["titre"].ToString();
                l.DatePublication = DateTime.Parse(reader["date_publication"].ToString());
                l.NombrePage = Int32.Parse(reader["nombre_page"].ToString());
                l.Couverture = reader["couverture"].ToString();
                l.Prix = Double.Parse(reader["nombre_page"].ToString());
                l.QuantiteDisponible = Int32.Parse(reader["quantite_disponible"].ToString());
            }
        }
        return livres;

    }

and then have
   List<Livre> GetByDate(string date){
        return GetBooks("select * from livre where date_publication like '%" + date + "%'";

    }

even better would be to use sql parameters. I will update this answer later


text: Q: Given an array $A$ of length $N<10^6,$ how many subarrays have $\text{max}(A[x:y]) - \text{min}(A[x:y]) {\le} K$? Given any K and an array of length $N$ what is the most efficient way to find the number of unique subarrays that satisfy this constraint? I believe there is an $O(N)$ solution using monotonic queues but am unsure of the specifics. Unique refers to the range of the original array that the subarray covers.


text:
Q: ORDER BY Alphanumeric sort I want to ORDER BY data in the following sequence:

*

*Number-Number

*Alpha-Number

*Alpha with no dash

I have the following sort:

*

*120-1

*120-2

*120-10

*Digital-1

*Digital-10

*Digital-2

*Wedding

This is the order I'm looking for, except the Digital (Alpha with dash) entries are not sorted by numbers after the dash.
After many attempts, here's my current sql statement:
SELECT SessionID, Identifier FROM Session
ORDER BY
CASE
  WHEN CAST(Identifier AS INTEGER) THEN SUBSTR(Identifier,0, INSTR(Identifier, '-')) + CAST(SUBSTR(Identifier, INSTR(Identifier, '-')+1, 999) AS INTEGER)
ELSE Identifier END

What am I doing wrong?
Thanks.

A: 1) Order by strings having - in them so they appear first
2) Order by the first part before - in the strings containing - casting them as integers where applicable, Else order by the column itself
3) Order by the second part after - in the strings containing - casting them as integers where applicable, Else order by the column itself
select val
from t
order by
 case when val like '%-%' then 1 else 2 end
,case when substr(val,1,instr(val,'-')-1) glob '*[0-9]*'
      then cast(substr(val,1,instr(val,'-')-1) as integer)
      when substr(val,1,instr(val,'-')-1) glob '*[a-zA-Z]*'
      then substr(val,1,instr(val,'-')-1)
 else val end
,case when val like '%-%' then cast(substr(val,instr(val,'-')+1) as integer)
 else val end

SQL Fiddle

A: Your logic is somehow reconstructing the strings, but for the order by, you want something like this:
order by (case when CAST(Identifier AS INTEGER)  <> 0 then 1
               when Identifier like '%-%' then 2
               else 3
          end),
         identifier

Note:  This assumes that the numbers are never 0.


text:
Q: combobox always on top properites  haw to make combobox always on top properites on vs 2008 c# .

A: If I understood your question correctly, I feel "Z-index" property should work for you.

A: Z-index, IE and combobox....was some time ago, but those three didn't play along so well...
Or maybe your problem can be fixed by setting the rendermode of the combobox to block?
More info, please?!


text:
Q: Python - Pronote I'm a french student and my high school have a website call Pronote use for write homework, if I'm present, etc... The problem: the site is often down, and it's impossible to recover the homework.
So, I wan't to create a Python script witch save sometimes a screenshot of the website. But he's coded in JavaScript and when I use python urllib2, Pronote return "Please use Google Chrome or Mozilla Firefox...". So if you know how to do it, without open a windows, thanks for you're answer.
( I use Python 2.7, Windows 10 (x64), and I know the Pronote IP. )


text:
Q: Recursively create directories in python while skipping existing directories I'm trying to create the following directories:
/autofs/homes/008/gwarner/test1/test2/

/autofs/homes/008/gwarner/test1/test3/

where /autofs/homes/008/gwarner/ already exists and I don't have write access for all of /autofs/homes/008/. When I try running:
dir = '/autofs/homes/008/gwarner/test/test1/test4/test5/'

for root, dirs, files in os.walk(dir, topdown = True):

    print root

I get no output at all.

A: I assume you've tried os.makedirs(), right?  Perhaps I'm misunderstanding your requirements, but you say you want to:

Recursively create directories

And the docs for os.makedirs() starts with:

Recursive directory creation function.

A: You could use the os.path.exists modules.
I would be careful and use both os.path.isdir and os.path.exists to check if the path is a directory before trying to write inside the directory and os.path.exists before overwriting a path.
For example:
>>> import os
>>> os.path.isdir('/home')
True
>>> os.path.isdir('/usr/bin')
True
>>> os.path.isdir('/usr/bin/python')
False
# writing a single, non-recursive path
>>> if not os.path.exists('/home/cinnamon'):
...     os.mkdir('/home/cinnamon')
# writing a single, recursive path
>>> if not os.path.exists('/home/alex/is/making/a/really/long/path'):
...     os.makedirs('/home/alex/is/making/a/really/long/path')
# now to script the latter
>>> paths = ['/home/alex/path/one', ...]
>>> for path in paths:
>>>     if not os.path.exists(path):
>>>        os.makedirs(path)

This way, you do not overwrite anything exists, you check if something is a directory before you write in the directory. By design, the system throws an OSError if the path exists, because it does not know HOW you want to handle it.
Do you want to overwrite the path (shutil.rmtree), do you want to store that the path has already been set, or do you want to just skip it? This is for you, the coder, to decide.


text:
Q: Banshee doesn't seem to play any song, but works in audacious? I've just downloaded Banshee to use as my main audio UI, and when I imported everything over onto the UI it won't seem to play any of my songs.  I'm using Lubuntu 14.04 LTS and have looked at the previous similar topics on this question and it doesn't seem to work.
I've tried this:
sudo apt-get install ubuntu-restricted-extras

Just to see if the files weren't corrupted or anything, I burned an audio cd and the cd works perfectly fine.  Also I see the term "idle" displayed below where the track "ticker" (I guess) is; to the right of where the skip/play buttons are.
Any ideas of what I can do to get songs to play on here?  Just was concerned if Banshee is still all the way functional or not, or maybe I got the wrong version?

A: You need tell us how it fails.
Maybe it is playing but your output channel is silent/muted. I have seen that.  You can't tell in base gui sometimes, a button says volume is not muted. However, that may not track the method (channel)the player is wanting to use. Because there are many audio frameworks loaded at once, watch out!. New installs may have Pulseaudio, alsa or some other, who knows what else. Depends on your sound card too. Ubuntu recommends Rhythmbox, often it ok. Banshee not in base, possibly because of config problem.  Some players only work with one, alsa or oss. Jargon changes over time.
I had no sound from rhythmbox, because out channel was off. Pretty consistently, if I use Record My Desktop I cannot hear playback without hacking a while.
Here's how to tell.
Install pavucontrol to get control, see if output is muted. Pavucontrol is more modern gui, but if player is sending to wrong device, you see/fix that in alsamixer. Pavucontrol has meter on output to show if player is making noise. In alsa mixer, you can see if simpler old style programs are blocked.
Sad, but true. Multimedia has been a mess for a long time. I've been in Linux 20 years and is only thing that stays consistently difficult.
There is a good reason Ubuntu does not ship a lot of those player programs anymore. And when you start installing others, there are likely sideeffects on base tools. It is only area in Ubuntu where I follow distro leaders' advice. It probable easier to change desktop evnironment than figure out sound.
Sorry I so gloomy. Long day at work.


text:
Q: Exceptions in javascript, should I use them and how? I've been told a few times that it's "bad" to use exceptions in javascript. Haven't really been told why it's bad, but inestead that I should use break, continue and return instead.
Which is fine, except I don't need to return/break/continue, I need to throw. I have a case where I have iterator functions nested in each other, each one returns the next value on call, so I use an exception to indicate that there's nothing more to iterate : seems like a logical way to do it, makes the code clean and works perfectly in practice. Is there really any reason not to use exceptions in js?
Second question, when I'm using exceptions, what kind of objects should I throw? For errors I'll obviously throw instances of Error, but for special cases (stop iteration, etc) I needed a quick way to check for those specific exceptions, and what I did is simply define an empty named function (function StopIteration(){}) and since functions are compared by reference I can always check if it's my special case or I should just rethrow. Is there a better or more idomatic way to do this in js? Should I really try to refactor my code avoid using exceptions?
Thank you

A: It sounds like you're searching through a multidimensional space using nested loops, which is a fairly common thing to program.  It's tempting to throw an exception from the innermost loop when the target is found which then gets caught by a "catch" block around the outermost loop but this often considered poor practice.
Language designers are aware of this pitfall so they allow us to give labels (names) to loop structures so that we can break from them (or continue to them).  Consider this example:
function findValueInMatrix(value, matrix) {
  var r, c, coords, rows=matrix.length, cols=matrix[0].length;
  found: // Label the outer loop as "found" so we can break from it.
  for (r=0; r<rows; r++) {
    for (c=0; c<cols; c++) {
      if (matrix[r][c] == value) {
        coords = [r, c]
        break found; // Exit the loop labeled "found".
      }
    }
  }
  return coords;
}

You can find more information in this post about breaking from nested loops.
This jsPerf test case also demonstrates that breaking to a label is nominally faster than throwing an exception (presumably in most browsers).

A: exception handling is in general slower than normal evaluation and only for exceptional situations
for stopping iterations you are better of defining a hasNext or isEmpty function for an ending condition or return a sentinel value (like undefined) when there are no more elements so the loop becomes
//with hasNext
while(it.hasNext()){
var val = it.next();
//...
}
//or with a sentinal undefined
while( (val = it.next()) !== undefined){
//...
}

A: For some people, throwing exceptions to indicate that there is no more values is a bad style; exceptions are made for exceptional behaviour.
Moreover, exception handling is generally slower than simple tests.
The difference is really minor (and maybe does not even exist) if the thrown instance is not created everytime. So having a constant StopIteration and throwing it is in fact quite fast.
For your problem, you might want to see https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators (they use exceptions to stop iteration).
I found that in dynamically typed languages exceptions are used for this kind of purposes too.

A: Throwing an exception to break out of a nested recursive search/walk is the easiest and more elegant way to go.
Say you walk a tree, recursivelly calling a function to handle the current node, calling again for each of its children and so on.
As you process each node, you might want to completelly break the whole call stack and return the found value (or stop iterating in general), breaking out of all the loops that are waiting in previous calls. Mind you that these previous calls might be costly in processing & memory, but useless if you "found" your result. Throwing an Exception is the most efficient and simple way to achieve this, but of course it needs attention.
For simple (even nested) loops its a overkill and is rightly touted as an anti-pattern.


text:
Q: How to deploy laravel project on Server? I built a linux server on digitialocean and installed require software and clone laravel files from github to /var/www/html/. I get this error
 "The 138.68.81.200 page isn't working" in http://138.68.81.200/socialNetwork/public/

Even though uploading migrations and create .env files and storage/* 777 permission.
How can I solve this problem ?

A: Assuming that you have installed all php packages and dependencies and all project vendors via composer. You just need to add this to /etc/apache2/sites-available/000-default.conf
Alias /socialNetwork /var/www/html/socialNetwork/public/
<Directory "/var/www/html/socialNetwork/public">
        AllowOverride All
        Order allow,deny
        allow from all
</Directory>

And then add this in your /var/www/html/socialNetwork/public/.htaccess :
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

After that:
sudo service apache2 restart


text:
Q: How can I make a div holding smaller divs to hold 3 on one line and then go on to the next line? I have a parent div which I am filling with divs of a certain size, whenever I get to 3 divs (and at the same time the parent's div width is filled with those smaller divs within) I want to get on the next line/row. How can I do that? I am generating the divs with JavaScript.
Basically what I want is to add elements to that parent div horizontally and when there is no more space on the sepcific line to move to the bottom one and add elements there.

A: This can be accomplished with a CSS grid with auto-placment:

function addDiv() {
  const newDiv = document.createElement('div');
  newDiv.classList.add('grid-div');
  const myGrid = document.querySelector('.my-grid');
  myGrid.appendChild(newDiv);
}
.my-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.grid-div {
  width: 50px;
  height: 50px;
  background-color: red;
  margin: 10px;
}
<div class="my-grid">
</div>

<button onclick="addDiv()">Add DIV</button>


text:
Q: How to get the paths in the recursion call A child is running up a staircase with n steps, and can go either 1 steps, 2 steps, or 3 steps at a time. Now write a program to count how many possible ways the child can run the stairs.
the solution looks like this ( DP can be used to save time )
public static int countDP(int n) {
 if (n<0)
   return 0;
 else if (n==0)
   return 1;
 else {
   map[n] = countDP(n-1) + countDP(n-2) + countDP(n-3);
 return map[n]; }
}

Now the question is how to get those paths? for example for n=4 this function returns 7, how to get all the possible paths? (in this example 1111 - 121 - 112 - 211 - 31 - 13 - 22 )
Is there any way to do so by changing the current program?
This is not a homework question, it's coming from the Recursion and Dynamic Programming chapter of Cracking Coding Interview book - chapter 9 - Question 1.

A: Yes there are ways to find all paths, that can be implemented into your existing code.
First of all, this will be very costly, space-wise. Even for n=4, you need to create 7 paths.
I think, the best way is to create a ternary tree and assign each possible way that the path can go to each child node.
So, here is a simple pseudo code:
root.value = 0;
root.left.value = 1;
root.middle.value = 2
root.right.value = 3;

Then when you do recursion, you would pass each child to an appropriate recursive call.
You would need to take care of some corner cases.
Also, think about where you should define this ternary tree, considering you are using recursion.
NOTE: I didn't want to post actual code or give full answer, because several people (including myself) think it might be a homework question.  Because of that, I tried to help out with this question and lead the person to a solution without just handing it out.


text:
Q: JPG files are too small when converted from PDF with imagemagick I'm on Ubuntu 10.04 with imagemagick. I used this command:
convert myfile.pdf -density 300 file.jpg

This works well, but the JPGs are only about an inch high.  How can I preserve the paper size in the conversion process?

A: I don't know if Imagemagick can sense the correct height automatically. However if you can come up with the correct height in pixel you can set the height manually.
According to http://www.indigorose.com/forums/archive/index.php/t-13334.html an A4 paper has the height of 3508 pixels in 300 dpi so then you can do
convert myfile.pdf -density 300 -geometry x3508 file2.jpg

This command sets the width to 3508 pixels and preserves aspect radio. See http://www.imagemagick.org/script/command-line-processing.php#geometry for details on the -geometry argument.

A: You can set the -density before you read the source pdf, so you can do
convert -density 300 myfile.pdf myfile.jpg

and it'll read the pdf at 300dpi, then render out the jpg at the original size of the pdf, whatever that was.


text:
Q: IIS7 Application Request Routing HTTPS I have a reverse proxy that routes traffic to my app server..
I have login feature on my public website that is served through HTTPS. The SSL certificates are installed in the reverse proxy server only. My app server doesn't have SSL certificate. SSL Offloading is enabled in the reverse proxy server.
This works perfectly so far, I can access the login page and the member area via HTTPS. But, I notice that my session cookie is not secure...
I'm using .NET Membership Provider for authentication and this will generate ASPXAUTH session cookie as you all know. I tried to enable the httponly and secure flag for this cookie by:

*

*adding requiressl=true for the forms authentication variable in the web.config

*adding httpcookie variable with httponly and requiressl=true.

The first setting always gave me 502 error when I tried to login.
502 - Web server received an invalid response while acting as a gateway or proxy server.
The second setting gave me the httponly flag but not the secure flag (I disabled the first setting when testing this).
How to solve this..some questions:

*

*Do I need to install SSL in all servers, including my app server?

*Is there any workaround for this?

Please advise.
P.S.
I'm using IIS 7.5 (Reverse Proxy)
Application Request Routing (Reverse Proxy)
IIS UrlRewrite Module (Reverse Proxy)
IIS 8 (app server)

A: Some applications are programmed to detect whether or not you are using HTTPS and since the actual web server is handling an HTTP request with your offloading enabled, it will think the request is not secure and often end up in a redirect loop.
You can fix this by setting up a single wildcard certificate on each content server and disable ssl offloading.

[ARR01 - ssl certificate] - [ARR02 - ssl certificate]   <-- Visitors will see this SSL Certificate in their browser
  |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
  [Content01 - wildcard ssl certificate] - [Content02 - wildcard ssl certificate] <-- This certificate remains hidden and thus can be a shared single wildcard cert.


text:
Q: How to highlight a pressed cardView on IceCreamSandwich (Android 4.0.4) This is my CardView layout :
<it.gmariotti.cardslib.library.view.CardView
        xmlns:card="http://schemas.android.com/apk/res-auto"
        android:id="@+id/list_cardId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="3dp"
        card:card_layout_resourceID="@layout/cardview_history"
        style="@style/list_card.base"/>

Based on that layout, my CardViews layout is correctly displayed but don't get highlighted when pressed.
On IceCreamSandwich (API 15 : 4.0.4) and unlike later OS versions, if we click on a CardView, it won't be highlighted. So I tried to explicitly add a background card_selector to my CardView.
android:background="@drawable/card_selector"

I'm using the default existing drawable available in the cardslib resource (card_selector.xml) :
<selector xmlns:android="http://schemas.android.com/apk/res/android"
          android:exitFadeDuration="@android:integer/config_mediumAnimTime">

    <item android:state_activated="true" android:drawable="@drawable/activated_background_card"/>
    <item android:state_pressed="true" android:drawable="@drawable/pressed_background_card"/>
    <item android:drawable="@drawable/card_background"/>
</selector>

But here is how my CardViews layout become, and as you can see, one of them is pressed but not correctly highlighted.
Is there a solution to make my CardView highlight correctly when pressed?


text:
Q: Gremlin: Find all the paths between two nodes and transform the query result into JSON format I'm writing Gremlin python queries on a Neptune database
I want to find all the paths between a node A and a node B.
Then I would like to write the data into a JSON format that looks like this:
{ "nodes": [
    { "id": 1, "name": "A", "color":"red"},
    { "id": 2, "name": "B", "color":"green"},
    { "id": 3, "name": "C", "color":"green"}
  ],
  "links": [
    { "source": 1, "target": 2, "color":"blue" }
    { "source": 1, "target": 3, "color":"purple" }
    { "source": 3, "target": 2, "color":"blue" }
  ]}

So that it's compatible with d3.js graph library and I could load the result into the d3 graphing library.
(In this case between A and B there would be the paths A->B and A->C->B)
I think I could use GraphSONWriter for this? Is that right?

A: Various Gremlin steps can yield a result that is deserialized as a dict in Python (essentially JSON). The steps to look at include group, project, elementMap and valueMap - Gremlin itself only yields raw JSON if you call the HTTP endpoint (not the recommended way).
To achieve a result such as the one above would likely use elementMap combined with project or union perhaps.
When I am working with libraries like D3.js or Vis.js (that use JSON to build their visual models) I typically return the result from Gremlin as close as I can get it to the final form (within reason) and then in my code create the final JSON. A common flow that I use is this one.
(1) Web client --> (2) API Gateway --> (3) Lambda --> (4) Neptune

The steps in that flow are as follows

*

*Javascript calls the REST API, gets back a JSON result and creates the visualization.

*REST API endpoint that routes calls to Lambda functions

*Lambda functions (written in Gremlin Python) that call into Neptune and then translate the results into JSON before sending back to the client.

*Neptune endpoint - runs the Gremlin queries


text:
Q: How to use fragments with skmaps? I'm looking for some really good example to implements skobbler maps on my app. But my app uses a lot of fragments and I want the map be held in a fragment. But there is no guide of how to implement skobbler maps using fragments. There is just the original example from skobbler that use activities.
I know there is SKMapFragment but, what's the right way to use it, I don't know. Hope someone can help me.
Thanks.

A: Currently fragment support is very limited - you can pull it off but you must carefully design your app so that you don't have multiple maps visible on the screen at the same time (transitions also count).
If you have multiple maps in different activities - make sure that you properly set the required flags (documentation here).
As for the SKMapFragment - here is the documentation


text:
Q: C++: Auto-interrupt a getch() call Problem
My program has multiple threads, with two currently important ones; The "Keyboard" thread is a getch() call wrapped by a while loop, and the "Conductor" thread imitates a user's input on a schedule for automation purposes. I need to find a way for the Conductor to interrupt the Keyboard thread without any intervention from the user.
Solutions
I have a couple of strategies that I anticipate the answer may take the form of.
A: A timed getch() call
I wonder if it may be possible to have the getch() call timeout after some time and continue execution of the program without any input from user.  This would allow the loop to check for input from the user for some amount of time, and then check for input from the Conductor (which would otherwise not be able to communicate with the Keyboard thread because the getch() call would still be running).  This could leave a potential bug in the program, if the user happens to hit the keyboard while the Keyboard thread isn't listening via getch(), but it would be one solution.
B: Insert data into input stream
It may be possible for the Conductor to send information to the Keyboard thread by using the input stream that getch() uses.  I know very little about the specifics of getch() and input-output in general, but I think that there must be some way for the Conductor to imitate the user's keyboard and send a key that will be picked up by getch().  If possible, this would be the preferred solution (no foreseeable bugs, and would simplify the design of the Conductor).
Any help would be greatly appreciated, thank you!


text:
Q: File not found while parsing a json file in Xamarin Forms I have a problem in a Xamarin.Forms application that I am developing. I need to read the content of a .json file, to be showed in a CarouselView. I am using Newtonsoft.Json library to parse the file.
However, it continously gives to me an error that it cannot find the file. The c# code is as follows:
using System.Net.Http;
using System.Collections.ObjectModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using PalazzoVecchioDemo.Models;
using Newtonsoft.Json;
using System.IO;

namespace PalazzoVecchioDemo.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class VisitChoice : ContentPage
    {
        private const string _json = "rooms.json";

        public ObservableCollection<Room> Rooms { get; set; } = new ObservableCollection<Room>();

        public VisitChoice()
        {
            InitializeComponent();

            //necessary to do data binding to elements present in this page
            //(in particular to the observable collection of rooms)
            BindingContext = this;
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            string path = Directory.GetCurrentDirectory();
            string previousFolder = Path.Combine(path, @"..\");
            string jsonPath = Path.Combine(path, _json);

            var rooms = JsonConvert.DeserializeObject<Room[]>(File.ReadAllText(_json));

            Rooms.Clear();

            foreach(var room in rooms)
            {
                Rooms.Add(room);
            }
        }
    }
}

The .xaml code is as follows (I put only the significant part of it:
!-- Carousel view with all the contents -->
        <CarouselView Grid.Row="1"
                      ItemsSource="{Binding Rooms}"
                      Loop="False">
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Frame HasShadow="True"
                               BorderColor="DarkGray"
                               CornerRadius="5"
                               Margin="20"
                               HeightRequest="300"
                               HorizontalOptions="Center"
                               VerticalOptions="CenterAndExpand">
                            <StackLayout>
                                <Label Text="{Binding Name}"
                                       FontAttributes="Bold"
                                       FontSize="Large"
                                       HorizontalOptions="Center"
                                       VerticalOptions="Center"
                                       AutomationProperties.IsInAccessibleTree="True"/>
                            </StackLayout>
                        </Frame>
                    </StackLayout>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>

The project structure is as follows; I am writing the VisitChoice page (inside the Views folder) and the file I want to read is rooms.json.

Anyone could please help me?

A: When you add the json file in Xamarin.Forms project as Embedded resource, you could use the code below to read and deserialize.
1. Get the matched classes for the json data.
Copy your json string. Click Edit> Paste Special> Paste JSON As
Classes. After that, you could get the classes you want.
2. Use the code below to read the Embedded resourcejson file and deserialize.
 string _json = "rooms.json";
        Room ObjList = new Room();

        var assembly = typeof(Page20).GetTypeInfo().Assembly;
        Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{_json}");
        using (var reader = new StreamReader(stream))
        {
            var jsonString = reader.ReadToEnd();

            ObjList = JsonConvert.DeserializeObject<Room>(jsonString);
        }

A: I would suggest the following points:

*

*in Visual Studio, it's possible to copy a file in the output folder. Please check the property windows when you click on the JSON file. Maybe it will not copy to the bin folder where your EXE or code is running.

*Before you are starting with DeserializeObject, I would check the path if the file really exists. File. Exists() Method.

*When you access the file, check if you are in the right folder. Maybe your file is in another subfolder, and you are one folder above.

*For accessing, use total paths to avoid issues.

A: It's best practice to avoid embed files in the way that you're doing. For JSON, I recommend you to create the file while your app is running, even if it will create just one time.
For that, you can:

*

*Use, for example, App.xaml.cs to process your JSON (it will be one of the first classes to your project run). You can store your JSON (if it's static, seeing that you're trying to embed it) in a resx file to access the strings.

*Creating and updating a JSON file:
        public void SaveJSON(string jsonText)
        {
            File.WriteAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "myJson.json"), jsonText);
        }

*

*Get your JSON file to use it:

        public string GetJSON()
        {
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "myJson.json");
            string json = (File.Exists(path)) ? File.ReadAllText(path) : "";
            return json;
        }

If you don't want to create resx file, you can just, in your App.xaml.cs, pass for one time SaveJSON("") to create your JSON document.


text:
Q: Give table's every side a different color via Google Apps Script I have created a 2 rows and 4 columns table via FlexTable, and I want to give this table's every side a different color with Google Apps Script. How could I do? Thanks for help!

A: You need to use .setColumnStyle(...) or .setStyleAttribute(...) read a bit the documentation here
Very bad question, if i could i would rate it down.


text:
Q: printing the alphabet in order in a matrix by now I have this code
int main() {
int cols;
cout << "cols";
cin >> cols;
int rows;
cout << "rows";
cin >> rows;

char** charArray = new char*[rows];
for (int i = 0; i < rows; ++i) {
    charArray[i] = new char[cols];
}

// Fill the array
for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < cols; ++j) {
        charArray[i][j] = char('1' + i + j );
    }
}

// Output the array
for (int i = 0; i < rows; ++i) {
    for (int j = i; j < cols ; ++j) {
        cout << charArray[i][j];
    }
    cout << endl;
}

// Deallocate memory by deleting
for (int i = 0; i < rows; ++i) {
    delete[] charArray[i];
}

and the output is like
1 2 3
2 3 4
How can I make it to be
1 2 3
4 5 6
I tried a lot, im a newbie in programming so can you please explain me what's the matter with this problem! Thanks a lot!!

A: Just change this:
charArray[i][j] = char('1' + i + j );

by:
 charArray[i][j] = char('1' + i*cols + j);

BTW:
You have a typo in the output array loop:
for (int j = i; j < cols ; ++j) {

Should be:
for (int j = 0; j < cols ; ++j) {

A: Array filling loop should be
int count = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
    charArray[i][j] = char('1' +count );
count++;
}
}

try with above code

A: You are building a matrix, here right. So it's 2-dimensional.
What the output means is that your matrix looks like:
1 2 3
2 3 4

Which is only natural, since, while filling it, you wrote for each element at coordinate i,j to be value 1+i+j. That means if i and j both equal 1 (second line, second column, since index start at 0), you put value the 1+1+1=3.
If you want to get the matrix:
1 2 3
4 5 6

You'll have to fill it with
charArray[i][j] = char('1' + i*ncols + j );

This way when you fill the first line, i = 0, so it's the same.
But then on the second line, i=1, so you get 1 + 3 + 0 = 4. And then 1+3+1=5, etc.
Edit: people are fast here. By the time I write my answer, already 2 others posted theirs :D


text:
Q: Revert root passwd to its default "empty" It is said to be more secure.
Having root with a password, how do I revert it to be empty?
This documentation is pretty explanatory:
https://help.ubuntu.com/community/RootSudo
And the command would be sudo passwd -dl root
But I can not play around on these servers and I would like to know if this command is the right one to reset root to a empty password, just like at Ubuntu 14.04 (server) installation.

A: There's a difference between "empty" password (or no password - when you get asked for a password you type nothing and hit enter) and a locked account.
The "root" user on Ubuntu systems is locked by default, that means there is no password at all that would match, not even the empty password.
Your command sudo passwd -dl root is correct:

*

*The -d flag deletes the password, that means it reverts the password to the empty password. You log in by simply hitting Enter without typing anything.

*The -l flag locks the account. It adds a "!" character in front of the stored encrypted password hash. This way, no entered password can match any more, because "!" would normally not appear in any hash of the used type. That means it becomes impossible to log in using a root password.

You should use both -d and -l (or short -dl) together because otherwise your current password would still be saved. If someone unlocks the account later and the current password wouldn't have been deleted, that's what the new password would become. If you could not remember the old one then, you would wonder why the root account is still not accessible until you figure out that there could be an old password set and you would have to reset it somehow again.


text:
Q: Powers in non-commutative rings Let $a,b$ be elements of a non-commutative ring $R$ with $\operatorname{char}(R) =p > 0$ and suppose that $ab-ba=[a,b]=1$. My question is simply:

Could you give a formula for the element $(a^n b^m)^p$ in the form $\sum\limits_{i,j} c_{ij} a^i b^j$?

For example, $(ab)^2=abab=a(ab-1)b=a^2b^2-ab$. I've tried to find some patterns in order to use induction, but without much success. May be someone more familiar with manipulations like this could help. Thank you.

A: No doubt this is some nifty combinatorial problem or other with a well-known solution, but brute force can get us some of the way. Using $[A,BC]=[A,B]C+B[A,C]$, it is easy to check that
$$ [b,a^n] = [b,a^{n-1}]a+a^{n-1}[b,a] = [b,a^{n-1}]a-a^{n-1}, $$
and iterating gives us inductively
$$ [b,a^n] = -na^{n-1}. $$
Now, supposing initially that $n\geqslant m$, I believe one can similarly derive the following:
$$ [b^m,a^n] = \sum_{k=0}^{m-1} (-1)^{k+1} \binom{m}{k} \frac{n!}{(n-m+k)!} a^{n-m+k} b^k. $$
(if there's a more symmetric way of writing this, I'm happy to hear it...)


text:
Q: How to picture a quantum field? How do we picture/imagine a quantum field ? How is it different from a classical field ? How do we picture a particle arising out of an excitation of its respective quantum field ?
Please give an accurate and not pop-sci kind of answer. Even if the QF's aren't so simple so as to give them a mental picture, it is fine. Please explain as to what degree the picture you give for it is correct.

A:
How is it different from a classical field ?

For starters, a quantum field is operator valued rather than scalar, vector, tensor, etc. valued.  A quantum field assigns an operator to each event in spacetime.

How do we picture a particle arising out of an excitation of its
  respective quantum field ?

We have to be careful to distinguish the quantum (operator valued) field from the entity that is operated on and its quanta.  See, for example, this answer.
Also, from the first chapter of "Student Friendly Quantum Field Theory", section 1.8:

When the word "field" is used classically, it refers to an entity,
  like fluid wave amplitude, E, or B, that is spread out in space, i.e.,
  has different values at different places.
By that definition, the wave function of ordinary QM, or even the
  particle state in QFT, is a field. But, it is important to realize
  that in quantum terminology, the word "field" means an operator field,
  which creates and destroys particle states.
States (= particles = wave functions = kets) are not considered fields
  in that context.

Honestly, I do not know how to picture or even if it is possible to picture a quantum field and the quanta they create and destroy.
I will be very interested in other's answers as I too have long struggled to find a satisfying picture.

A: As Alfred Centauri mentioned in QFT a field can be thought of as an operator. This holds in the canonical approach to QFT. However, in the equivalent path integral approach, one deals with QFT by assigning an amplitude to a particular trajectory through field space. So if we measure a field at time 0 and then again at time T then we evaluate the amplitude for any particular measurement result at T by evaluating the amplitude for all trajectories through field space that go from the configuration we measured at time 0 and the proposed configuration at time T. The total amplitude is given by the sum of all these amplitudes. The probability is obtained by taking the square of the absolute value of the total amplitude. If you want a particle at time 0 at position x one puts in a delta function in the potential which is zero everywhere except at time 0 and position x. Alternatively, a plane wave will give a particle with a definite momentum. So particles are just fluctuations in the field.


text:
Q: How to use selector to locate each child in a foreach loop in Jquery I'm using Jquery and I want to use selector to locate each child in a foreach loop:
   $('div.parents').children('a').each(function(i) {
        setTimeout(function(){
            $(this).trigger( "click" );
        },2000 + i * 2000);
    });

However, $(this) seems not work at all. The list looks like this:
And if I change  $(this).trigger( "click" ); to  $('a').trigger( "click" ); it will open all the links at once.

...

Thanks for your help!

A: To let this inside setTimeout points to this outside of setTimeout,
you can use jQuery's $.proxy:
$('div.parents').children('a').each(function(i) {
        setTimeout($.proxy(function(){
            $(this).trigger( "click" );
        },this),2000 + i * 2000);
    });

Or .bind [works only in browsers compatible with ECMAScript 5]:
$('div.parents').children('a').each(function(i) {
        setTimeout(function(){
            $(this).trigger( "click" );
        }.bind(this),2000 + i * 2000);
    });

A: The problem is this inside the setTimeout callback does not point to the clicked element, you can use a closure variable to fix this issue
$('div.parents').children('a').each(function(i) {
    var $this = $(this)
    setTimeout(function(){
        $this.trigger( "click" );
    },2000 + i * 2000);
});


text:
Q: Add a class along with class specified in the skin We are using themes to style our control.
For textbox we have added like this in the skin
<asp:TextBox runat="server" CssClass="txt edit_txt" />

Now in some cases, we want to add another class along with this 2 classes.
when we added a textbox like this in aspx
<asp:TextBox ID="txtnameE" runat="server" MaxLength="30" CssClass="RequiredCheckClass"></asp:TextBox>

On rendering it didn't take the "RequiredCheckClass" class, but only the other 2 classes specified in the skin.
So is there any way to add a class along with the classes specified in the skin from an aspx page.
PS : now i am going to use @Curt suggestion or will use EnableTheming=false and will add all the required classes to this control. Please update if anyone got any other idea other than these....

A: One option would be to create another TextBox control in the Skin file like:
<asp:TextBox SkinID="Required" runat="server" CssClass="txt edit_txt RequiredCheckClass" />

And then use the following in your markup file:
<asp:TextBox ID="txtnameE" runat="server" MaxLength="30" SkinID="Required"></asp:TextBox>

Other than that I'm not sure. I've always avoided ASP.NET Themes since I found out how restrictive they are.

A: You can use the "class" property - just like you use it in a regular HTML element.
thats the bypass that i am using.
<asp:TextBox SkinID="Required" runat="server" class="RequiredCheckClass" CssClass="txt edit_txt" />


text:
Q: Searchable ListView with checkboxes I have a searchable ListView of adjectives (in Dutch) with checkboxes next to them. The list is searchable with an edittext on top. I'd like to be able to search the list and remember which checkboxes are checked and which are not. So when I search something, check it and go back to the complete list, it still has to be checked. Next, I have to be able to obtain what the user has checked.
The code I have so far: the Activity (cs), its ContentView (xml) and the ListItem (xml).
I'm sorry for the broad question and not providing specific chunks of code, but I don't know how to go about this. Can someone help me or steer me in the right direction?
Thanks in advance

A: filter your list like below in on text change, add text change listener.
inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            MainActivity.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }
    });

and when user check something from list, get a text from list view at then again check its index in the original list. I hope you get it, let me know if any confusion.


text:
Q: Cant have class in javascript innerHTML
Example Text.
 <button onclick="myFunction()">Click me</button>

I have a function that changes the inner html
myFunction() {

  document.getElementById('myDiv').innerHTML="

Example 1

Example 2

Example 3

"

}

And when i add the class i get an error: unexpected identifier. Why is this? if i have

A: Use single quotes '' for setting the class. If you use double quotes "" within double quotes you will get the problem you are experiencing.
myFunction() {

  document.getElementById('myDiv').innerHTML="

Example 1

Example 2

Example 3

"

}

A: in javascript , both "" and '' are valid for strings , but what happens if we do want to use "" or '' inside a string?
var str = "he said to me 'hi'"
there is no problem, as long the nested character (" or ') is different from the outer character (' or " respectivly)
so in your example :
myFunction() {
  document.getElementById('myDiv').innerHTML="

Example 1

Example 2

Example 3

"
}

A: Dont use "" inside "" without \ and you forgot to type function before myFunction()

Example Text.
 <button onclick="myFunction()">Click me</button>

.
function myFunction() {

  document.getElementById('myDiv').innerHTML="

Example 1

Example 2

Example 3

";

}


text:
Q: How to do I sum these postgresql two tables and group by week and year? I am trying to sum two tables sales + waste with results grouped by week and year. If I run each section by itself I get accurate results, but when I try my current query I get an error of "[42601] ERROR: subquery must return only one column"
This is what I currently have...
SELECT
(
    SELECT date_part('week', w."createdAt"),
        SUM("Quantity")
    FROM waste as w
     WHERE date_trunc('year', w."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1
)
    +
(
    SELECT date_part('week', sh."createdAt"),
           SUM(quantity)
    FROM sales_hourly as sh
    WHERE date_trunc('year', sh."createdAt"::timestamptz at time zone 'America/Denver') =
          date_trunc('year', current_date - interval '1 year')
    group by 1
) AS weekly_total

A: You can join both tables, but as both tables could have different weeks, you need a FULL OUTER JOIN which will cost time.
If it is guaranteed that both SELECTs have the same weeks , a INNER JOIN will suffice.

CREATE tABLE waste("createdAt" timestamp  , "Quantity" integer )

CREATE tABLE sales_hourly("createdAt" timestamp  , "Quantity" integer)

SELECT t1.week_t1,COALESCE(sum_t1,0) sum_waste,t2.week_t2,  COALESCE(sum_t2,0) sum_slaes
FROM
(
    SELECT date_part('week', w."createdAt") week_t1,
        SUM("Quantity") sum_t1
    FROM waste as w
     WHERE date_trunc('year', w."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1
) t1
    FULL OUTER JOIN
(
    SELECT date_part('week', sh."createdAt") week_t2,
        SUM("Quantity") sum_t2
    FROM sales_hourly as sh
     WHERE date_trunc('year', sh."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1) t2 ON t1.week_t1 = t2.week_t2

week_t1 | sum_waste | week_t2 | sum_slaes
:------ | --------: | :------ | --------:

db<>fiddle here


text:
Q: Jquery adds "?" on URL hi i have this ajax function
mainUrl = "http://someURL/POSMobileConnector/";
    parameter = "Event Materials";
    servEntity = "Product/"
    console.log("test");

    $.ajax({
        url: mainUrl + servEntity + 'loaditembycategory/',
        type: "GET",
        data: parameter ,
        dataType:'json',
        contentType: "application/json; charset=utf-8",
        ProcessData:false,
        //username:"admin",
        //password:"admin",
        //beforeSend : function(xhr) {
        //   xhr.setRequestHeader("Authorization", cred/*"Basic " + encodeBase64(credentials)*/);
        //},
        success: function (msg) {//On Successfull service call
                ServiceSucceeded(msg);
        },
        error: function(error){
              console.log(error);
        }
      });

My Question is when i look at firebug. the url result is http://url/service/Product/loaditembycategory/?Event%20Materials. Now i want to remove the "?" part because the right url is to be http://url/service/Product/Event%20Materials only.

A: The data: parameter is put in the query string.
It sounds like you don't want a query string, so you shouldn't use the data: parameter at all.
Instead, concatenate the URL string directly.

A: Then add it to the URL
 url: mainUrl + servEntity + 'loaditembycategory/' + Param,

The data param is for GET or POST params only.

A:     url: mainUrl + servEntity + 'loaditembycategory/' + Param,
    type: "GET",

A: $.ajax({
  //...
  url: mainUrl + servEntity + 'loaditembycategory/' + encodeURIComponent(Param)
  //...
});


text:
Q: imacros How do I use if statements to check the content of the page? How do I use if statements to check the content of the page, then perform an action based on the if statement? Here are the possible outcomes when it comes to clicking:
Picture 1
http://i.imgur.com/V9rnrVS.png
Picture 2
http://i.imgur.com/eeYhfXU.png
Picture 3
http://i.imgur.com/W6Tjd8l.jpg
So here's my mainline logic:
I will keep on clicking the box on the page [picture 1]

if it encounters [picture 2] click the box (i have the code for that)

else if it encounters [picture 3] refresh the page

else keep on clicking the box

If the images are not clear then feel free to comment and I'll try my best to upload more clear images.

So right now I tried to build the code but it doesn't seem to work.
Map.js
var test;

test ="CODE:";
test +="SET !ERRORIGNORE YES "+"\n";
test +="URL GOTO=http://tppcrpg.net/map.php?Map=11 "+"\n";

for (var i = 1; i < 10 ; i++)
{

iimSet("n",i)
iimPlay(test)
iimPlay("map1.iim")

}

map1.iim
TAG POS=1 TYPE=INPUT:IMAGE FORM=ACTION:/map.php?Map=11 ATTR=NAME:Find

It's giving me this error:

[Exception... "Component returned failure code: 0x80520001 (NS_ERROR_FILE_UNRECOGNIZED_PATH) [nsILocalFile.initWithPath]"  nsresult: "0x80520001 (NS_ERROR_FILE_UNRECOGNIZED_PATH)"  location: "JS frame :: resource://imacros/utils.js ::  :: line 192"  data: no], line: 188 (Error code: 991)

Using Expert Complete HTML Code I found out that if I encounter [Picture 3] has the following code:
TAG POS=1 TYPE=H2 ATTR=*
TAG POS=2 TYPE=P ATTR=CLASS:center

A: You have an example of imacros javacript scripting here.
Loop in Imacros using Javascript
You can declare 3 codes each containing iMacros code to a div on that page. And with if clause you can see which one is present on the page.
Edit:
In HTML you have element called DIV . Like this
<div class="some_div">
Some text
</div>

To click on that div the iMacros code is:
TAG POS=1 TYPE=DIV ATTR=CLASS:some_div

A: Maybe you can create a callback function that's always called when changes (like showing/hiding pictures) happen.
It's pretty hard to help with just the images. Can post some code or give more information? I have/had problems understanding your problem ;)

A: I've found when using iMacros that if I'm using creating a script with any sort of branching (ifs or loops), it's better to code it in JS and only use the iMacros language when doing something the JS can't easily do. You can use iimSet to pass variables to an iMacros script and iimGetLastExtract to get them back to the JS. The "content" variable in JavaScript is equal to the page's "window" object and "content.document" is equal to the page's "document" object.
Without knowing the code in question it's difficult to provide a concrete example. I hope this points you in the right direction and lets you harvest those Pokemon like a boss.


text:
Q: Removing a value from a custom linked list int SDI::LinkedList::removeValue(int removeValue)
{
SDI::Node* current = head;
SDI::Node* prev = head;
    while (current != nullptr)
    {
        if (current == head)
        {
            if (current->value == removeValue)
            {
                current = current->next; // track the next value
                delete head;
                head = current-> next;
                return 1;
            }

        }
        else
        {
            if (current->value != removeValue)
            {
                prev = current;  /// don't lose track of the previous value, saves working 1 ahead
                current  = current-> next; // let the loop deal with it

            }
        else
        {
            prev->next = current->next;
            delete current;
        }
            if (current->next != nullptr)
            {
                if (current->next->value == removeValue)
                {
                SDI::Node* temp = current->next;
                current->next = current->next->next;
                delete temp;
                return 1;
                }
            }
        }
    }
return 0;
}

All seems to work well, until it reaches the line:
"if (current->value != removeValue)"

It seems to just jump directly over it, yet current-> value DOES NOT equal removeValue as shown in the watcher.

A: It appears you have an infinite loop if current->value != removeValue on the first iteration of the loop as you'll never leave the if (current == head) condition since current will never update. If you change your first condition from if (current == head) to if (current == head && current->value == removeValue) it should now correctly reach the current->value != removeValue condition that you said was being skipped.
I don't see any additional errors beyond that without more details on the steps your program seems to be skipping.


text:
Q: Definitions of a homotopy Why are the following two definitions for a homotopy equivalent?

Let $f,g: X \to Y$ be maps. Then $f \simeq g$ if and only if there is a map $G:X \to Y^{I}$ such that $G(x)(0) = f(x)$ and $G(x)(1) = g(x),$ for all $x \in X$.

and

Suppose maps $f,g:X \to Y$ are maps. We say that $f$ is homotopic to $g$, written $f \simeq g$, if there is a continuous function $F: X \times I \to Y$ such that $$F(x,0), \quad F(x,1) = g(x), \quad \text{and} \quad F(*,t) = *.$$

In the first definition there is no mention of a base point as opposed to the second definition so I am wondering how that is possible.

A: $Y^I$ is the space of continuous functions from $I$ to $Y$.  The topology on it is the natural topology, which is the finest topology for which for every continuous function $H : X\times I \to Y$ there exists a continuous function $\hat{H} : X \to Y^I$ such that $H(x,t) = \hat{H}(x)(t)$.  We make it into a pointed space, by defining the point $*_{Y^I} = t \mapsto *_Y$.  So for any continuous function $F : X\times I \to Y$ we have a continuous function $\hat{F} : X \to Y^I$, but $\hat{F}$ will only be base point preserving only if $F(*_X,t) = *_Y$ as that means $\hat{F}(*_X) = (t \mapsto *_Y) = *_{Y^I}$.  No requirement is made for $F(x,t)$ when $x \neq *_X$.  If the first definition only required $G$ to be a continuous function then these definitions would not be equivalent.
However, to go the other way we need to be able to make a continuous function $G' : X\times I \to Y$ given a continuous function $G : X \to Y^I$ such that $G'(x,t)=G(x)(t)$.  Here the fact that $I$, the unit interval $[0,1]$, is compact Hausdorff means that it is locally compact which means that such a function always exists.  This also makes the natural topology on $Y^I$ the compact-open topology.  In other words, all this rambling about "natural topologies" and "locally compact", just means that we are assured that the function $H(x) = t \mapsto H'(x,t)$ is always continuous and that we can always find such a continuous function $H'$, namely $H'(x,t) = H(x)(t)$.  It's obvious that we can do this as plain functions, but it is not obvious that they will be continuous.


text:
Q: this в классе javascript Я новичок в javascipt и разбираюсь с контекстом и классами, с контекстом все вроде понятно, а вот с классами возникли вопросы
Почему в конструкторе класса мы присваиваем переменные через this.variable, и вызываем функции через this.function, как в этом примере?
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  getArea() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}

Через this можно объявить (присвоить) переменную экземпляру класса? Можете объяснить что происходит при вызове this.height и что происходит с классом? Как присваивается переменная?

A: this - можно понять как инстнс данного класа. То есть если создать объект по прототипу этого класа, this будет этим самым объектом, this.calcArea() - методом этого объекта, а this.height - пропом этого объекта.
const rect = new Rectangle(500, 500)

Здесь this - это rect, this.height = 500, а метод calcArea будет напрямую работать со значениями, полученными выше при присваивании и вернет 500 * 500.


text:
Q: Downloaded Bitmap is null I download a png file from link. But sometimes there is no file. And i have null problem.
How can check whether bitmap is downloaded or not.
mIcon = BitmapFactory.decodeStream(icon_url.openConnection() .getInputStream())

A: Simple as that:
if(mIcon==null){
// set fallback Image or retry
 }