Programs & Examples On #Spring security

Spring Security is the Spring Framework's application security solution. Spring security can be used to secure URLs and method invocations. It is widely used to secure standalone web applications, portlets and increasingly REST applications.

Spring Security exclude url patterns in security annotation configurartion

specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"

http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().

How to disable spring security for particular url

<http pattern="/resources/**" security="none"/>

Or with Java configuration:

web.ignoring().antMatchers("/resources/**");

Instead of the old:

 <intercept-url pattern="/resources/**" filters="none"/>

for exp . disable security for a login page :

  <intercept-url pattern="/login*" filters="none" />

Spring boot Security Disable security

Answer is to allow all requests in WebSecurityConfigurerAdapter as below.

you can do this in existing class or in new class.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }

Please note : If ther is existing GlobalMethodSecurityConfiguration class, you must disable it.

How to get active user's UserDetails

Spring Security is intended to work with other non-Spring frameworks, hence it is not tightly integrated with Spring MVC. Spring Security returns the Authentication object from the HttpServletRequest.getUserPrincipal() method by default so that's what you get as the principal. You can obtain your UserDetails object directly from this by using

UserDetails ud = ((Authentication)principal).getPrincipal()

Note also that the object types may vary depending on the authentication mechanism used (you may not get a UsernamePasswordAuthenticationToken, for example) and the Authentication doesn't strictly have to contain a UserDetails. It can be a string or any other type.

If you don't want to call SecurityContextHolder directly, the most elegant approach (which I would follow) is to inject your own custom security context accessor interface which is customized to match your needs and user object types. Create an interface, with the relevant methods, for example:

interface MySecurityAccessor {

    MyUserDetails getCurrentUser();

    // Other methods
}

You can then implement this by accessing the SecurityContextHolder in your standard implementation, thus decoupling your code from Spring Security entirely. Then inject this into the controllers which need access to security information or information on the current user.

The other main benefit is that it is easy to make simple implementations with fixed data for testing, without having to worry about populating thread-locals and so on.

Handle spring security authentication exceptions with @ExceptionHandler

Customize the filter, and determine what kind of abnormality, there should be a better method than this

public class ExceptionFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    String msg = "";
    try {
        filterChain.doFilter(request, response);
    } catch (Exception e) {
        if (e instanceof JwtException) {
            msg = e.getMessage();
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON.getType());
        response.getWriter().write(JSON.toJSONString(Resp.error(msg)));
        return;
    }
}

}

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.

At least then it's only in once place if you need to later refactor.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Unit testing with Spring Security

The problem is that Spring Security does not make the Authentication object available as a bean in the container, so there is no way to easily inject or autowire it out of the box.

Before we started to use Spring Security, we would create a session-scoped bean in the container to store the Principal, inject this into an "AuthenticationService" (singleton) and then inject this bean into other services that needed knowledge of the current Principal.

If you are implementing your own authentication service, you could basically do the same thing: create a session-scoped bean with a "principal" property, inject this into your authentication service, have the auth service set the property on successful auth, and then make the auth service available to other beans as you need it.

I wouldn't feel too bad about using SecurityContextHolder. though. I know that it's a static / Singleton and that Spring discourages using such things but their implementation takes care to behave appropriately depending on the environment: session-scoped in a Servlet container, thread-scoped in a JUnit test, etc. The real limiting factor of a Singleton is when it provides an implementation that is inflexible to different environments.

When to use Spring Security`s antMatcher()?

You need antMatcher for multiple HttpSecurity, see Spring Security Reference:

5.7 Multiple HttpSecurity

We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.

@EnableWebSecurity
public class MultiHttpSecurityConfig {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) { 1
      auth
          .inMemoryAuthentication()
              .withUser("user").password("password").roles("USER").and()
              .withUser("admin").password("password").roles("USER", "ADMIN");
  }

  @Configuration
  @Order(1)                                                        2
  public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
      protected void configure(HttpSecurity http) throws Exception {
          http
              .antMatcher("/api/**")                               3
              .authorizeRequests()
                  .anyRequest().hasRole("ADMIN")
                  .and()
              .httpBasic();
      }
  }    

  @Configuration                                                   4
  public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
                  .anyRequest().authenticated()
                  .and()
              .formLogin();
      }
  }
}

1 Configure Authentication as normal

2 Create an instance of WebSecurityConfigurerAdapter that contains @Order to specify which WebSecurityConfigurerAdapter should be considered first.

3 The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/

4 Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after ApiWebSecurityConfigurationAdapter since it has an @Order value after 1 (no @Order defaults to last).

In your case you need no antMatcher, because you have only one configuration. Your modified code:

http
    .authorizeRequests()
        .antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
        .antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
        .somethingElse() // for /high_level_url_A/**
        .antMatchers("/high_level_url_A/**").authenticated()
        .antMatchers("/high_level_url_B/sub_level_1").permitAll()
        .antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
        .somethingElse() // for /high_level_url_B/**
        .antMatchers("/high_level_url_B/**").authenticated()
        .anyRequest().permitAll()

How to use new PasswordEncoder from Spring Security

I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.

My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $).

To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.

Decoder

@Component
public class LegacyEncoder implements PasswordEncoder {

    private static final String BCRYP_TYPE = "$";
    private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

    return BCRYPT.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

    if (encodedPassword.startsWith(BCRYP_TYPE)) {
        return BCRYPT.matches(rawPassword, encodedPassword);
    }

    return sha1SaltMatch(rawPassword, encodedPassword);
    }

    @SneakyThrows
    private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {

    String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);

    // Legacy code from old system   
    byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
    byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
    byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);

    return Arrays.equals(checkHash, validHash);
    }

}

User Object

public class User implements UserDetails {

    public static final String SPLIT_CHAR = ":";

    @Id
    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(nullable = false, length = 60)
    private String password;

    @Column(nullable = true, length = 32)
    private String salt;

.
.

    @PostLoad
    private void init() {

    username = emailAddress; //To comply with UserDetails
    password = salt == null ? password : salt + SPLIT_CHAR + password;
    }        

You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.

Is it possible to decrypt SHA1

Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.

It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

I encountered the same problem with:

Spring Boot version = 1.5.10
Spring Security version = 4.2.4


The problem occurred on the endpoints, where the ModelAndView viewName was defined with a preceding forward slash. Example:

ModelAndView mav = new ModelAndView("/your-view-here");

If I removed the slash it worked fine. Example:

ModelAndView mav = new ModelAndView("your-view-here");

I also did some tests with RedirectView and it seemed to work with a preceding forward slash.

Remove "Using default security password" on Spring Boot

It is also possible to just turn off logging for that specific class in properties :

logging.level.org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration=WARN

Spring security CORS Filter

  1. You don't need:

    @Configuration
    @ComponentScan("com.company.praktikant")
    

    @EnableWebSecurity already has @Configuration in it, and I cannot imagine why you put @ComponentScan there.

  2. About CORS filter, I would just put this:

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0); 
        return bean;
    }
    

    Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)

  3. According to above, your "MyFilter" class is redundant.

  4. You can also remove those:

    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(CORSConfig.class);
    annotationConfigApplicationContext.refresh();
    

    From Application class.

  5. At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of http://localhost:8080/getKunden you should use HTTP GET method on http://localhost:8080/kunden resource. You can learn about best practices for design RESTful api here: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

To add to Kevin's answer, I find that in practice nearly all of your non-trivial Spring MVC applications will require an application context (as opposed to only the spring MVC dispatcher servlet context). It is in the application context that you should configure all non-web related concerns such as:

  • Security
  • Persistence
  • Scheduled Tasks
  • Others?

To make this a bit more concrete, here's an example of the Spring configuration I've used when setting up a modern (Spring version 4.1.2) Spring MVC application. Personally, I prefer to still use a WEB-INF/web.xml file but that's really the only xml configuration in sight.

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  
  <filter>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
  </filter>
  
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
  </filter>
 
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
      <param-name>contextClass</param-name>
      <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </init-param>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>com.company.config.WebConfig</param-value>
    </init-param>
  </servlet>
  
  <context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.company.config.AppConfig</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <jsp-config>
    <jsp-property-group>
      <url-pattern>*.jsp</url-pattern>
      <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
  </jsp-config>
  
</web-app>

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.company.controller")
public class WebConfig {

  @Bean
  public InternalResourceViewResolver getInternalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
  }
}

AppConfig.java

@Configuration
@ComponentScan(basePackages = "com.company")
@Import(value = {SecurityConfig.class, PersistenceConfig.class, ScheduleConfig.class})
public class AppConfig {
  // application domain @Beans here...
}

Security.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private LdapUserDetailsMapper ldapUserDetailsMapper;

  @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/").permitAll()
      .antMatchers("/**/js/**").permitAll()
      .antMatchers("/**/images/**").permitAll()
      .antMatchers("/**").access("hasRole('ROLE_ADMIN')")
      .and().formLogin();

    http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
    }

  @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth.ldapAuthentication()
      .userSearchBase("OU=App Users")
      .userSearchFilter("sAMAccountName={0}")
      .groupSearchBase("OU=Development")
      .groupSearchFilter("member={0}")
      .userDetailsContextMapper(ldapUserDetailsMapper)
      .contextSource(getLdapContextSource());
    }

  private LdapContextSource getLdapContextSource() {
    LdapContextSource cs = new LdapContextSource();
    cs.setUrl("ldaps://ldapServer:636");
    cs.setBase("DC=COMPANY,DC=COM");
    cs.setUserDn("CN=administrator,CN=Users,DC=COMPANY,DC=COM");
    cs.setPassword("password");
    cs.afterPropertiesSet();
    return cs;
  }
}

PersistenceConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(transactionManagerRef = "getTransactionManager", entityManagerFactoryRef = "getEntityManagerFactory", basePackages = "com.company")
public class PersistenceConfig {

  @Bean
  public LocalContainerEntityManagerFactoryBean getEntityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
    lef.setDataSource(dataSource);
    lef.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
    lef.setPackagesToScan("com.company");
    return lef;
  }

  private HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() {
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    hibernateJpaVendorAdapter.setDatabase(Database.ORACLE);
    hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect");
    hibernateJpaVendorAdapter.setShowSql(false);
    hibernateJpaVendorAdapter.setGenerateDdl(false);
    return hibernateJpaVendorAdapter;
  }

  @Bean
  public JndiObjectFactoryBean getDataSource() {
    JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
    jndiFactoryBean.setJndiName("java:comp/env/jdbc/AppDS");
    return jndiFactoryBean;
  }

  @Bean
  public JpaTransactionManager getTransactionManager(DataSource dataSource) {
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    jpaTransactionManager.setEntityManagerFactory(getEntityManagerFactory(dataSource).getObject());
    jpaTransactionManager.setDataSource(dataSource);
    return jpaTransactionManager;
  }
}

ScheduleConfig.java

@Configuration
@EnableScheduling
public class ScheduleConfig {
  @Autowired
  private EmployeeSynchronizer employeeSynchronizer;

  // cron pattern: sec, min, hr, day-of-month, month, day-of-week, year (optional)
  @Scheduled(cron="0 0 0 * * *")
  public void employeeSync() {
    employeeSynchronizer.syncEmployees();
  }
}

As you can see, the web configuration is only a small part of the overall spring web application configuration. Most web applications I've worked with have many concerns that lie outside of the dispatcher servlet configuration that require a full-blown application context bootstrapped via the org.springframework.web.context.ContextLoaderListener in the web.xml.

How to disable 'X-Frame-Options' response header in Spring Security?

By default X-Frame-Options is set to denied, to prevent clickjacking attacks. To override this, you can add the following into your spring security config

<http>    
    <headers>
        <frame-options policy="SAMEORIGIN"/>
    </headers>
</http>

Here are available options for policy

  • DENY - is a default value. With this the page cannot be displayed in a frame, regardless of the site attempting to do so.
  • SAMEORIGIN - I assume this is what you are looking for, so that the page will be (and can be) displayed in a frame on the same origin as the page itself
  • ALLOW-FROM - Allows you to specify an origin, where the page can be displayed in a frame.

For more information take a look here.

And here to check how you can configure the headers using either XML or Java configs.

Note, that you might need also to specify appropriate strategy, based on needs.

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

Get UserDetails object from Security Context in Spring MVC controller

You can use below code to find out principal (user email who logged in)

  org.opensaml.saml2.core.impl.NameIDImpl principal =  
  (NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

  String email = principal.getValue();

This code is written on top of SAML.

RESTful Authentication via Spring

We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:

Set up the security context like so:

<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
    <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url pattern="/authenticate" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>

<bean id="CustomAuthenticationEntryPoint"
    class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />

<bean id="authenticationTokenProcessingFilter"
    class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
    <constructor-arg ref="authenticationManager" />
</bean>

As you can see, we've created a custom AuthenticationEntryPoint, which basically just returns a 401 Unauthorized if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.

CustomAuthenticationEntryPoint:

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
    }
}

AuthenticationTokenProcessingFilter:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired UserService userService;
    @Autowired TokenUtils tokenUtils;
    AuthenticationManager authManager;

    public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if(parms.containsKey("token")) {
            String token = parms.get("token")[0]; // grab the first "token" parameter

            // validate the token
            if (tokenUtils.validate(token)) {
                // determine the user based on the (already validated) token
                UserDetails userDetails = tokenUtils.getUserFromToken(token);
                // build an Authentication object with the user's info
                UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                // set the authentication into the SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));         
            }
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

Obviously, TokenUtils contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:

public interface TokenUtils {
    String getToken(UserDetails userDetails);
    String getToken(UserDetails userDetails, Long expiration);
    boolean validate(String token);
    UserDetails getUserFromToken(String token);
}

That ought to get you off to a good start. Happy coding. :)

How to use OAuth2RestTemplate?

In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.

...

public ResourceOwnerPasswordResourceDetails() {
    setGrantType("password");
}

...

The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form); was not set.

See the switch in: org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()

Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.

@EnableOAuth2Client
@Configuration
class MyConfig {

@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;

@Value("${security.oauth2.client.client-id}")
private String clientId;

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;

@Value("${security.oauth2.client.password-token}")
private String passwordToken;

@Value("${security.user.name}")
private String username;

@Value("${security.user.password}")
private String password;


@Bean
protected OAuth2ProtectedResourceDetails resource() {

    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

    resource.setAccessTokenUri(tokenUrl);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setClientAuthenticationScheme(AuthenticationScheme.form);
    resource.setUsername(username);
    resource.setPassword(password + passwordToken);

    return resource;
}

@Bean
 public OAuth2RestOperations restTemplate() {
    return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
    }
}


@Service
@SuppressWarnings("unchecked")
class MyService {
    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

disabling spring security in spring boot app

The accepted answer didn't work for me.

If you have a multi configuration, adding the following to your WebSecurityConfig class worked for me (ensure that your Order(1) is lower than all of your other Order annotations in the class):

/* UNCOMMENT TO DISABLE SPRING SECURITY */
    /*@Configuration
    @Order(1)
    public static class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
        }
    }*/

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Add the annotation

@JsonManagedReference

For example:

@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "autorizacoes_usuario", joinColumns = { @JoinColumn(name = "fk_usuario") }, inverseJoinColumns = { @JoinColumn(name = "fk_autorizacoes") })
@JsonManagedReference
public List<AutorizacoesUsuario> getAutorizacoes() {
    return this.autorizacoes;
}

Spring Security redirect to previous page after successful login

In order to redirect to a specific page no matter what the user role is, one can simply use defaultSucessUrl in the configuration file of Spring.

@Override
protected void configure(HttpSecurity http) throws Exception {
    
    
      http.authorizeRequests() 
      .antMatchers("/admin").hasRole("ADMIN") 
      .and()
      .formLogin() .loginPage("/login") 
                    .defaultSuccessUrl("/admin",true)
      .loginProcessingUrl("/authenticateTheUser")
      .permitAll();
     
    

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

You need a spring-security-config.jar on your classpath.

The exception means that the security: xml namescape cannot be handled by spring "parsers". They are implementations of the NamespaceHandler interface, so you need a handler that knows how to process <security: tags. That's the SecurityNamespaceHandler located in spring-security-config

My Application Could not open ServletContext resource

Make sure your maven war plugin block in pom.xml includes all files (especially xml files) while building the war. But you don't need to include the .java files though.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.5</version>

  <configuration>
    <webResources>
      <resources>
        <directory>WebContent</directory>
        <includes>
          <include>**/*.*</include> <!--this line includes the xml files into the war, which will be found when it is exploded in server during deployment -->
        </includes>
        <excludes>
          <exclude>*.java</exclude>
        </excludes>
      </resources>
    </webResources>
    <webXml>WebContent/WEB-INF/web.xml</webXml>
  </configuration>
</plugin> 

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I got this error while deploying to Virgo. The solution was to add this to my bundle imports:

org.springframework.transaction.config;version="[3.1,3.2)",

I noticed in the Spring jars under META-INF there is a spring.schemas and a spring.handlers section, and the class that they point to (in this case org.springframework.transaction.config.TxNamespaceHandler) must be imported.

Serving static web resources in Spring Boot & Spring Security application

  @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/resources/**"); // #3
      }

Ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

It looks like the CSRF (Cross Site Request Forgery) protection in your Spring application is enabled. Actually it is enabled by default.

According to spring.io:

When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.

So to disable it:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}

If you want though to keep CSRF protection enabled then you have to include in your form the csrftoken. You can do it like this:

<form .... >
  ....other fields here....
  <input type="hidden"  name="${_csrf.parameterName}"   value="${_csrf.token}"/>
</form>

You can even include the CSRF token in the form's action:

<form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">

How do I get the Session Object in Spring?

I try with next code and work excellent

    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    /**
     * Created by jaime on 14/01/15.
     */

    @Controller
    public class obteinUserSession {
        @RequestMapping(value = "/loginds", method = RequestMethod.GET)
        public String UserSession(ModelMap modelMap) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName();
            modelMap.addAttribute("username", name);
            return "hellos " + name;
        }

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

@dimas's answer is not logically consistent with your question; ifAllGranted cannot be directly replaced with hasAnyRole.

From the Spring Security 3—>4 migration guide:

Old:

<sec:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>

New (SPeL):

<sec:authorize access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>

Replacing ifAllGranted directly with hasAnyRole will cause spring to evaluate the statement using an OR instead of an AND. That is, hasAnyRole will return true if the authenticated principal contains at least one of the specified roles, whereas Spring's (now deprecated as of Spring Security 4) ifAllGranted method only returned true if the authenticated principal contained all of the specified roles.

TL;DR: To replicate the behavior of ifAllGranted using Spring Security Taglib's new authentication Expression Language, the hasRole('ROLE_1') and hasRole('ROLE_2') pattern needs to be used.

Spring Security with roles and permissions

After reading this post, from Baeldung. I found that the solution is pretty simple.

What I have done, is to add the role and permissions into the GrantedAuthority. I was able to access both methods hasRole() and hasAuthority().

How to check "hasRole" in Java Code with Spring Security?

Better late then never, let me put in my 2 cents worth.

In JSF world, within my managed bean, I did the following:


HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
SecurityContextHolderAwareRequestWrapper sc = new SecurityContextHolderAwareRequestWrapper(req, "");

As mentioned above, my understanding is that it can be done the long winded way as followed:


Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
if (principal instanceof UserDetails) {
    userDetails = (UserDetails) principal;
    Collection  authorities = userDetails.getAuthorities();
}

How to manually set an authenticated user in Spring Security / SpringMVC

I was trying to test an extjs application and after sucessfully setting a testingAuthenticationToken this suddenly stopped working with no obvious cause.

I couldn't get the above answers to work so my solution was to skip out this bit of spring in the test environment. I introduced a seam around spring like this:

public class SpringUserAccessor implements UserAccessor
{
    @Override
    public User getUser()
    {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        return (User) authentication.getPrincipal();
    }
}

User is a custom type here.

I'm then wrapping it in a class which just has an option for the test code to switch spring out.

public class CurrentUserAccessor
{
    private static UserAccessor _accessor;

    public CurrentUserAccessor()
    {
        _accessor = new SpringUserAccessor();
    }

    public User getUser()
    {
        return _accessor.getUser();
    }

    public static void UseTestingAccessor(User user)
    {
        _accessor = new TestUserAccessor(user);
    }
}

The test version just looks like this:

public class TestUserAccessor implements UserAccessor
{
    private static User _user;

    public TestUserAccessor(User user)
    {
        _user = user;
    }

    @Override
    public User getUser()
    {
        return _user;
    }
}

In the calling code I'm still using a proper user loaded from the database:

    User user = (User) _userService.loadUserByUsername(username);
    CurrentUserAccessor.UseTestingAccessor(user);

Obviously this wont be suitable if you actually need to use the security but I'm running with a no-security setup for the testing deployment. I thought someone else might run into a similar situation. This is a pattern I've used for mocking out static dependencies before. The other alternative is you can maintain the staticness of the wrapper class but I prefer this one as the dependencies of the code are more explicit since you have to pass CurrentUserAccessor into classes where it is required.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

Unsupported Media Type in postman

I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.

  • If your request is XML Request use XML(text/xml).

  • If your request is JSON Request use JSON(application/json)

An Authentication object was not found in the SecurityContext - Spring 3.2.2

The security's authorization check part gets the authenticated object from SecurityContext, which will be set when a request gets through the spring security filter. My assumption here is that soon after the login this is not being set. You probably can use a hack as given below to set the value.

try {
    SecurityContext ctx = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(ctx);
    ctx.setAuthentication(event.getAuthentication());

    //Do what ever you want to do

} finally {
    SecurityContextHolder.clearContext();
}

Update:

Also you can have a look at the InteractiveAuthenticationSuccessEvent which will be called once the SecurityContext is set.

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install. This should solve the problem.

How to configure CORS in a Spring Boot + Spring Security application?

After much searching for the error coming from javascript CORS, the only elegant solution I found for this case was configuring the cors of Spring's own class org.springframework.web.cors.CorsConfiguration.CorsConfiguration()

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
    }

How to manage exceptions thrown in filters in Spring?

So this is what I did:

I read the basics about filters here and I figured out that I need to create a custom filter that will be first in the filter chain and will have a try catch to catch all runtime exceptions that might occur there. Then i need to create the json manually and put it in the response.

So here is my custom filter:

public class ExceptionHandlerFilter extends OncePerRequestFilter {

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (RuntimeException e) {

            // custom error response class used across my project
            ErrorResponse errorResponse = new ErrorResponse(e);

            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write(convertObjectToJson(errorResponse));
    }
}

    public String convertObjectToJson(Object object) throws JsonProcessingException {
        if (object == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }
}

And then i added it in the web.xml before the CorsFilter. And it works!

<filter> 
    <filter-name>exceptionHandlerFilter</filter-name> 
    <filter-class>xx.xxxxxx.xxxxx.api.controllers.filters.ExceptionHandlerFilter</filter-class> 
</filter> 


<filter-mapping> 
    <filter-name>exceptionHandlerFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

<filter> 
    <filter-name>CorsFilter</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')

Assigning a function to a variable

The syntax

def x():
    print(20)

is basically the same as x = lambda: print(20) (there are some differences under the hood, but for most pratical purposes, the results the same).

The syntax

def y(t):
   return t**2

is basically the same as y= lambda t: t**2. When you define a function, you're creating a variable that has the function as its value. In the first example, you're setting x to be the function lambda: print(20). So x now refers to that function. x() is not the function, it's the call of the function. In python, functions are simply a type of variable, and can generally be used like any other variable. For example:

def power_function(power):
      return  lambda x : x**power
power_function(3)(2)

This returns 8. power_function is a function that returns a function as output. When it's called on 3, it returns a function that cubes the input, so when that function is called on the input 2, it returns 8. You could do cube = power_function(3), and now cube(2) would return 8.

No Activity found to handle Intent : android.intent.action.VIEW

This exception can raise when you handle Deep linking or URL for a browser, if there is no default installed. In case of Deep linking there may be no application installed that can process a link in format myapp://mylink.

You can use the tangerine solution for API up to 29:

private fun openUrl(url: String) {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    val activityInfo = intent.resolveActivityInfo(packageManager, intent.flags)
    if (activityInfo?.exported == true) {
        startActivity(intent)
    } else {
        Toast.makeText(
            this,
            "No application that can handle this link found",
            Toast.LENGTH_SHORT
        ).show()
    }
}

For API >= 30 see intent.resolveActivity returns null in API 30.

Open a folder using Process.Start

Use an overloaded version of the method that takes a ProcessStartInfo instance and set the ProcessWindowStyle property to a value that works for you.

Kill a postgresql session/connection

There is no need to drop it. Just delete and recreate the public schema. In most cases this have exactly the same effect.

namespace :db do

desc 'Clear the database'
task :clear_db => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == 'schema_migrations'
    ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
  end
end

desc 'Delete all tables (but not the database)'
task :drop_schema => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.execute("DROP SCHEMA public CASCADE")
  ActiveRecord::Base.connection.execute("CREATE SCHEMA public")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO postgres")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO public")
  ActiveRecord::Base.connection.execute("COMMENT ON SCHEMA public IS 'standard public schema'")
end

desc 'Recreate the database and seed'
task :redo_db => :environment do |t,args|
  # Executes the dependencies, but only once
  Rake::Task["db:drop_schema"].invoke
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:migrate:status"].invoke 
  Rake::Task["db:structure:dump"].invoke
  Rake::Task["db:seed"].invoke
end

end

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

Generating Request/Response XML from a WSDL

I use SOAPUI 5.3.0, it has an option for creating requests/responses (also using WSDL), you can even create a mock service which will respond when you send request. Procedure is as follows:

  1. Right click on your project and select New Mock Service option which will create mock service.
  2. Right click on mock service and select New Mock Operation option which will create response which you can use as template.

EDIT #1:

Check out the SoapUI link for the latest version. There is a Pro version as well as the free open source version.

Add A Year To Today's Date

One liner as suggested here

How to determine one year from now in Javascript by JP DeVries

new Date(new Date().setFullYear(new Date().getFullYear() + 1))

Or you can get the number of years from somewhere in a variable:

const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

How to determine if a number is odd in JavaScript

How about this...

    var num = 3 //instead get your value here
    var aa = ["Even", "Odd"];

    alert(aa[num % 2]);

PHP Composer behind http proxy

Try this:

export HTTPS_PROXY_REQUEST_FULLURI=false

solved this issue for me working behind a proxy at a company few weeks ago.

DateTime.Now.ToShortDateString(); replace month and day

Try this:

this.TextBox3.Text = String.Format("{0: MM.dd.yyyy}",DateTime.Now);

Should I use the datetime or timestamp data type in MySQL?

The timestamp data type stores date and time, but in UTC format, not in the current timezone format as datetime does. And when you fetch data, timestamp again converts that into the current timezone time.

So suppose you are in USA and getting data from a server which has a time zone of USA. Then you will get the date and time according to the USA time zone. The timestamp data type column always get updated automatically when its row gets updated. So it can be useful to track when a particular row was updated last time.

For more details you can read the blog post Timestamp Vs Datetime .

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Give full access of .composer to user.

sudo chown -R 'user-name' /home/'user-name'/.composer

or

sudo chmod 777 -R /home/'user-name'/.composer

user-name is your system user-name.

to get user-name type "whoami" in terminal:

enter image description here

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

How to set a text box for inputing password in winforms?

you can use like these "txtpassword.PasswordChar = '•';"

the use location is ...

 namespace Library_Management_System
    {
        public partial class Login : Form
        {
            public Login()
            {
                InitializeComponent();
                txtpassword.PasswordChar = '•';

How to list files in an android directory?

If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:

Android Q (10) ask permission to get access all storage. Scoped storage

I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.

How do I comment on the Windows command line?

Powershell

For powershell, use #:

PS C:\> echo foo # This is a comment
foo

How can I find the link URL by link text with XPath?

//a[text()='programming quesions site']/@href 

which basically identifies an anchor node <a> that has the text you want, and extracts the href attribute.

Android Endless List

At Ognyan Bankov GitHub i found a simple and working solution!

It makes use of the Volley HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.

The given code demonstrates:

  1. ListView which is populated by HTTP paginated requests.
  2. Usage of NetworkImageView.
  3. "Endless" ListView pagination with read-ahead.

For future consistence i forked Bankov's repo.

Java web start - Unable to load resource

If anyone else gets here because they're trying to set up a Jenkins slave, then you need to set the url of the host to the one it's actually using.

On the host, go to Manage Jenkins > Configure System and edit "Jenkins URL"

How to upload a file using Java HttpClient library working with PHP

The correct way will be to use multipart POST method. See here for example code for the client.

For PHP there are many tutorials available. This is the first I've found. I recommend that you test the PHP code first using an html client and then try the java client.

Add Foreign Key relationship between two Databases

If you need rock solid integrity, have both tables in one database, and use an FK constraint. If your parent table is in another database, nothing prevents anyone from restoring that parent database from an old backup, and then you have orphans.

This is why FK between databases is not supported.

Row names & column names in R

Just to expand a little on Dirk's example:

It helps to think of a data frame as a list with equal length vectors. That's probably why names works with a data frame but not a matrix.

The other useful function is dimnames which returns the names for every dimension. You will notice that the rownames function actually just returns the first element from dimnames.

Regarding rownames and row.names: I can't tell the difference, although rownames uses dimnames while row.names was written outside of R. They both also seem to work with higher dimensional arrays:

>a <- array(1:5, 1:4)
> a[1,,,]
> rownames(a) <- "a"
> row.names(a)
[1] "a"
> a
, , 1, 1    
  [,1] [,2]
a    1    2

> dimnames(a)
[[1]]
[1] "a"

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

As stated by user2246674, using success and error as parameter of the ajax function is valid.

To be consistent with precedent answer, reading the doc :

Deprecation Notice:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you are using the callback-manipulation function (using method-chaining for example), use .done(), .fail() and .always() instead of success(), error() and complete().

Open window in JavaScript with HTML inserted

You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open

var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");

jquery get all form elements: input, textarea & select

jQuery keeps a reference to the vanilla JS form element, and this contains a reference to all of the form's child elements. You could simply grab the reference and proceed forward:

var someForm = $('#SomeForm');

$.each(someForm[0].elements, function(index, elem){
    //Do something here.
});

How to get Android GPS location

Worked a day for this project. It maybe useful for u. I compressed and combined both Network and GPS. Plug and play directly in MainActivity.java (There are some DIY function for display result)

 ///////////////////////////////////
////////// LOCATION PACK //////////
// 
//  locationManager: (LocationManager) for getting LOCATION_SERVICE
//  osLocation: (Location) getting location data via standard method
//  dataLocation: class type storage locztion data
//    x,y: (Double) Longtitude, Latitude
//  location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
//  AutoLocation: class help getting provider info
//  tmLocation: (Timer) for running update location over time
//  LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
//  LocationStart(): LocationStart(500)
//  LocationStop(): stop getting location data
//
//  EX:
//    LocationStart(); cycleF(new Runnable() {public void run(){bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();}},500);
//

LocationManager locationManager;
Location osLocation;
public class dataLocation {double x,y;}
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener {
    @Override public void onLocationChanged(Location p1){}
    @Override public void onStatusChanged(String p1, int p2, Bundle p3){}
    @Override public void onProviderEnabled(String p1){}
    @Override public void onProviderDisabled(String p1){}
    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,0,0,this);
            if (locationManager != null) {
                osLocation = locationManager.getLastKnownLocation(provider);
                return osLocation;
            }
        }
        return null;
    }
}
Timer tmLocation=new Timer();
public void LocationStart(int interval){
    locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    final AutoLocation autoLocation = new AutoLocation();
    tmLocation=cycleF(new Runnable() {public void run(){ 
                Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
                if (nwLocation != null) {
                    location.y = nwLocation.getLatitude();
                    location.x = nwLocation.getLongitude();
                } else {
                    //bodym.text("NETWORK_LOCATION is loading...").show();
                }
                Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
                if (gpsLocation != null) {
                    location.y = gpsLocation.getLatitude();
                    location.x = gpsLocation.getLongitude();    
                } else {
                    //bodym.text("GPS_LOCATION is loading...").show();
                }   
            }}, interval);
}
public void LocationStart(){LocationStart(500);};
public void LocationStop(){stopCycleF(tmLocation);}

//////////
///END//// LOCATION PACK //////////
//////////


/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
//  import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
//   Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
// 
// EX:
//   delayF(new Runnable(){public void run(){ sig("Hi"); }},2000);
//   final Runnable rn=delayF(new Runnable(){public void run(){ sig("Hi"); }},3000);
//     delayF(new Runnable(){public void run(){ (new Handler()).post(rn);sig("Hello"); }},1000);
//   final Timer tm=cycleF(new Runnable() {public void run(){ sig("Neverend"); }}, 1000);
//     delayF(new Runnable(){public void run(){ stopCycleF(tm);sig("Ended"); }},7000);
//
public static Runnable delayF(final Runnable r, long delay) {
    final Handler h = new Handler();
    h.postDelayed(r, delay);
    return new Runnable(){
        @Override
        public void run(){h.removeCallbacks(r);}
    };
}
public static Timer cycleF(final Runnable r, long interval) {
    final Timer t=new Timer();
    final Handler h = new Handler();
    t.scheduleAtFixedRate(new TimerTask() {
            public void run() {h.post(r);}
        }, interval, interval);
    return t;
}
public void stopCycleF(Timer t){t.cancel();t.purge();}
public boolean serviceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
//////////
///END//// RUNTIME //////////
//////////

How to upgrade Git on Windows to the latest version?

If you have already installed git , you can update the git with the command git update-git-for-windows

to know the current version use git --version

you can run this commands in cmd prompt

How to get the name of a class without the package?

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How to manage local vs production settings in Django?

My solution to that problem is also somewhat of a mix of some solutions already stated here:

  • I keep a file called local_settings.py that has the content USING_LOCAL = True in dev and USING_LOCAL = False in prod
  • In settings.py I do an import on that file to get the USING_LOCAL setting

I then base all my environment-dependent settings on that one:

DEBUG = USING_LOCAL
if USING_LOCAL:
    # dev database settings
else:
    # prod database settings

I prefer this to having two separate settings.py files that I need to maintain as I can keep my settings structured in a single file easier than having them spread across several files. Like this, when I update a setting I don't forget to do it for both environments.

Of course that every method has its disadvantages and this one is no exception. The problem here is that I can't overwrite the local_settings.py file whenever I push my changes into production, meaning I can't just copy all files blindly, but that's something I can live with.

How do I view / replay a chrome network debugger har file saved with content?

Drag and drop is best solution. I am just showing another way to import by clicking the HAR import icon: enter image description here

How do I count unique values inside a list

I'd use a set myself, but here's yet another way:

uniquewords = []
while True:
    ipta = raw_input("Word: ")
    if ipta == "":
        break
    if not ipta in uniquewords:
        uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"

What is causing the error `string.split is not a function`?

maybe

string = document.location.href;
arrayOfStrings = string.toString().split('/');

assuming you want the current url

Use of "this" keyword in C++

this points to the object in whose member function it is reffered, so it is optional.

Get skin path in Magento?

The way that Magento themes handle actual url's is as such (in view partials - phtml files):

echo $this->getSkinUrl('images/logo.png');

If you need the actual base path on disk to the image directory use:

echo Mage::getBaseDir('skin');

Some more base directory types are available in this great blog post:

http://alanstorm.com/magento_base_directories

How do you copy a record in a SQL table but swap out the unique id of the new row?

Here is how I did it using ASP classic and couldn't quite get it to work with the answers above and I wanted to be able to copy a product in our system to a new product_id and needed it to be able to work even when we add in more columns to the table.

Cn.Execute("CREATE TEMPORARY TABLE temprow AS SELECT * FROM product WHERE product_id = '12345'")
Cn.Execute("UPDATE temprow SET product_id = '34567'")
Cn.Execute("INSERT INTO product SELECT * FROM temprow")
Cn.Execute("DELETE temprow")
Cn.Execute("DROP TABLE temprow")

How to set maximum height for table-cell?

Try something like this:-

 table {
    width: 50%;
    height: 50%;
    border-spacing: 0;
    position:absolute;
}
td {
    border: 1px solid black;
}
#content {
    position:absolute;
    width:100%;
    left:0px;
    top:20px;
    bottom:20px;
    overflow: hidden;
}

illegal use of break statement; javascript

I have a function next() which will maybe inspire you.

function queue(target) {
        var array = Array.prototype;

        var queueing = [];

        target.queue = queue;
        target.queued = queued;

        return target;

        function queued(action) {
            return function () {
                var self = this;
                var args = arguments;

                queue(function (next) {
                    action.apply(self, array.concat.apply(next, args));
                });
            };
        }

        function queue(action) {
            if (!action) {
                return;
            }

            queueing.push(action);

            if (queueing.length === 1) {
                next();
            }
        }

        function next() {
            queueing[0](function (err) {
                if (err) {
                    throw err;
                }

                queueing = queueing.slice(1);

                if (queueing.length) {
                    next();
                }
            });
        }
    }

Remote debugging a Java application

Answer covering Java >= 9:

For Java 9+, the JVM option needs a slight change by prefixing the address with the IP address of the machine hosting the JVM, or just *:

-agentlib:jdwp=transport=dt_socket,server=y,address=*:8000,suspend=n

This is due to a change noted in https://www.oracle.com/technetwork/java/javase/9-notes-3745703.html#JDK-8041435.

For Java < 9, the port number is enough to connect.

How to hide reference counts in VS2013?

Workaround....

In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.

Why do we usually use || over |? What is the difference?

| is the binary or operator

|| is the logic or operator

Getting a list of associative array keys

You can use: Object.keys(obj)

Example:

_x000D_
_x000D_
var dictionary = {
  "cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  "dogs": [4, 5, 6, 3, 2]
};

// Get the keys
var keys = Object.keys(dictionary);

console.log(keys);
_x000D_
_x000D_
_x000D_

See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, and Internet Explorer 9. Object.keys() contains a code snippet that you can add if Object.keys() is not supported in your browser.

how to reset <input type = "file">

Just use:

$('input[type=file]').val('');

How do I set a fixed background image for a PHP file?

Your question doesn't have anything to do with PHP... just CSS.

Your CSS is correct, but your browser won't typically be able to open what you have put in for a URL. At a minimum, you'll need a file: path. It would be best to reference the file by its relative path.

Importing project into Netbeans

Follow these steps:

  1. Open Netbeans
  2. Click File > New Project > JavaFX > JavaFX with existing sources
  3. Click Next
  4. Name the project
  5. Click Next
  6. Under Source Package Folders click Add Folder
  7. Select the nbproject folder under the zip file you wish to upload (Note: you need to unzip the folder)
  8. Click Next
  9. All the files will be included but you can exclude some if you wish
  10. Click Finish and the project should be there

If you don't have the source folder added do the following

  1. Under your projects directory tree right click on Source Packages
  2. Click New
  3. Click Java Package and name it with the name of the package the source files have
  4. Go to the directory location (i.e., using Windows Explorer not Netbeans) of those source files, highlight them all, then drag and drop them under that Java Package you just created
  5. Click Run
  6. Click Clean and Build Project

Now you can have fun and run the application.

Superscript in Python plots

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

ax1.set_ylabel('Rate (min?¹)')

How can I remove jenkins completely from linux

First - stop Jenkins service:

sudo service jenkins stop

Next - delete:

sudo apt-get remove --purge jenkins

If you used separate server for Jenkins, some GCP or AWS - just delete this server. Here is a video how to uninstall Jenkins from GCP Compute Engine https://youtu.be/D2HUFAc_Trw

Facebook login "given URL not allowed by application configuration"

Your settings must be incorrect.

Go to http://www.facebook.com/developers/ and edit the application you're working on.

On the "website" tab, look for "Site URL". This should be set to your website's URL "http://yoursite.com/"

Note that if you're using subdomains, you'll also need to update "Site Domain" to be "yoursite.com"

Get element of JS object with an index

JS objects have no defined order, they are (by definition) an unsorted set of key-value pairs.

If by "first" you mean "first in lexicographical order", you can however use:

var sortedKeys = Object.keys(myobj).sort();

and then use:

var first = myobj[sortedKeys[0]];

Tracking Google Analytics Page Views with AngularJS

Developers creating Single Page Applications can use autotrack, which includes a urlChangeTracker plugin that handles all of the important considerations listed in this guide for you. See the autotrack documentation for usage and installation instructions.

Access to the path denied error in C#

You do not have permissions to access the file. Please be sure whether you can access the file in that drive.

string route= @"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);

You have to provide the file name to create. Please try this, now you can create.

How do I lock the orientation to portrait mode in a iPhone Web Application?

You can specify CSS styles based on viewport orientation: Target the browser with body[orient="landscape"] or body[orient="portrait"]

http://www.evotech.net/blog/2007/07/web-development-for-the-iphone/

However...

Apple's approach to this issue is to allow the developer to change the CSS based on the orientation change but not to prevent re-orientation completely. I found a similar question elsewhere:

http://ask.metafilter.com/99784/How-can-I-lock-iPhone-orientation-in-Mobile-Safari

Determining whether an object is a member of a collection in VBA

I have some edit, best working for collections:

_x000D_
_x000D_
Public Function Contains(col As collection, key As Variant) As Boolean_x000D_
    Dim obj As Object_x000D_
    On Error GoTo err_x000D_
    Contains = True_x000D_
    Set obj = col.Item(key)_x000D_
    Exit Function_x000D_
    _x000D_
err:_x000D_
    Contains = False_x000D_
End Function
_x000D_
_x000D_
_x000D_

Using group by and having clause

1.Get supplier numbers and names for suppliers of parts supplied to at least two different projects.

 SELECT S.SID, S.NAME
 FROM SUPPLIES SP
 JOIN SUPPLIER S
 ON SP.SID = S.SID
 WHERE PID IN
 (SELECT PID FROM SUPPPLIES GROUP BY PID, JID HAVING COUNT(*) >= 2)

I am not slear about your second question

How to set zoom level in google map

What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:

20 : 1128.497220

19 : 2256.994440

18 : 4513.988880

17 : 9027.977761

16 : 18055.955520

15 : 36111.911040

14 : 72223.822090

13 : 144447.644200

12 : 288895.288400

11 : 577790.576700

10 : 1155581.153000

9 : 2311162.307000

8 : 4622324.614000

7 : 9244649.227000

6 : 18489298.450000

5 : 36978596.910000

4 : 73957193.820000

3 : 147914387.600000

2 : 295828775.300000

1 : 591657550.500000

Add 'x' number of hours to date

You can try lib Ouzo goodies, and do this in fluent way:

echo Clock::now()->plusHours($hours)->format("Y-m-d H:m:s");

API's allow multiple operations.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

Inserting values into a SQL Server database using ado.net via C#

Remove the comma

... Gender,Contact, " + ") VALUES ...
                  ^-----------------here

Bootstrap 4 File Input

In case, if you need a no jquery solution

<label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="this.nextElementSibling.innerText = this.files[0].name">
      <span class="custom-file-control"></span>
</label>

How to create helper file full of functions in react native?

I am sure this can help. Create fileA anywhere in the directory and export all the functions.

export const func1=()=>{
    // do stuff
}
export const func2=()=>{
    // do stuff 
}
export const func3=()=>{
    // do stuff 
}
export const func4=()=>{
    // do stuff 
}
export const func5=()=>{
    // do stuff 
}

Here, in your React component class, you can simply write one import statement.

import React from 'react';
import {func1,func2,func3} from 'path_to_fileA';

class HtmlComponents extends React.Component {
    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }
    rippleClickFunction(){
        //do stuff. 
        // foo==bar
        func1(data);
        func2(data)
    }
   render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

I have solved this issue as follows:

removed from chrome extension and install ext again. It will work ISA

Xcode "Device Locked" When iPhone is unlocked

On your device (iPhone/iPad) goto: Settings -> Developer -> Clear Trusted Computers worked for me.

How to call a RESTful web service from Android?

Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/

// The connection URL 
String url = "https://ajax.googleapis.com/ajax/" + 
    "services/search/web?v=1.0&q={query}";

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");

vertical & horizontal lines in matplotlib

If you want to add a bounding box, use a rectangle:

ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)

Rectangle doc

What is the correct value for the disabled attribute?

  • For XHTML, <input type="text" disabled="disabled" /> is the valid markup.
  • For HTML5, <input type="text" disabled /> is valid and used by W3C on their samples.
  • In fact, both ways works on all major browsers.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Heres an example using: getDisplayMedia

document.body.innerHTML = '<video style="width: 100%; height: 100%; border: 1px black solid;"/>';

navigator.mediaDevices.getDisplayMedia()
.then( mediaStream => {
  const video = document.querySelector('video');
  video.srcObject = mediaStream;
  video.onloadedmetadata = e => {
    video.play();
    video.pause();
  };
})
.catch( err => console.log(`${err.name}: ${err.message}`));

Also worth checking out is the Screen Capture API docs.

Access is denied when attaching a database

Copy Database to an other folder and attach or Log in SQLServer with "Windows Authentication"

enter image description here

using nth-child in tables tr td

Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td> that have $ inside. Example: using nth-child in tables tr td

html

<tr>
    <td>&nbsp;</td>
    <td data-rel='$'>$</td>
    <td>&nbsp;</td>
</tr>

css

table tr td[data-rel='$'] {
    background-color: #333;
    color: white;
}

Please try these example.

_x000D_
_x000D_
table tr td[data-content='$'] {_x000D_
    background-color: #333;_x000D_
    color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
    <tr>_x000D_
        <td>A</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>B</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>C</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>D</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Notify ObservableCollection when Item changes

All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems in the NotifyCollectionChangedEventArgs object.

this is the perfect ObservableCollection .

public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
    #region Constructors
    public ObservableCollectionEX() : base()
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(IEnumerable<T> c) : base(c)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(List<T> l) : base(l)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }

    #endregion



    public new void Clear()
    {
        foreach (var item in this)            
            if (item is INotifyPropertyChanged i)                
                i.PropertyChanged -= Element_PropertyChanged;            
        base.Clear();
    }
    private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
            foreach (var item in e.OldItems)                
                if (item != null && item is INotifyPropertyChanged i)                    
                    i.PropertyChanged -= Element_PropertyChanged;


        if (e.NewItems != null)
            foreach (var item in e.NewItems)                
                if (item != null && item is INotifyPropertyChanged i)
                {
                    i.PropertyChanged -= Element_PropertyChanged;
                    i.PropertyChanged += Element_PropertyChanged;
                }
            }
    }
    private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);


    public ListedItemPropertyChangedEventHandler ItemPropertyChanged;

}

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

Simple java8 solution with capturing both outputs and reactive processing using CompletableFuture:

static CompletableFuture<String> readOutStream(InputStream is) {
    return CompletableFuture.supplyAsync(() -> {
        try (
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
        ){
            StringBuilder res = new StringBuilder();
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                res.append(inputLine).append(System.lineSeparator());
            }
            return res.toString();
        } catch (Throwable e) {
            throw new RuntimeException("problem with executing program", e);
        }
    });
}

And the usage:

Process p = Runtime.getRuntime().exec(cmd);
CompletableFuture<String> soutFut = readOutStream(p.getInputStream());
CompletableFuture<String> serrFut = readOutStream(p.getErrorStream());
CompletableFuture<String> resultFut = soutFut.thenCombine(serrFut, (stdout, stderr) -> {
         // print to current stderr the stderr of process and return the stdout
        System.err.println(stderr);
        return stdout;
        });
// get stdout once ready, blocking
String result = resultFut.get();

mkdir -p functionality in Python

I've had success with the following personally, but my function should probably be called something like 'ensure this directory exists':

def mkdirRecursive(dirpath):
    import os
    if os.path.isdir(dirpath): return

    h,t = os.path.split(dirpath) # head/tail
    if not os.path.isdir(h):
        mkdirRecursive(h)

    os.mkdir(join(h,t))
# end mkdirRecursive

System.Security.SecurityException when writing to Event Log

Had a similar issue with all of our 2008 servers. The security log stopped working altogether because of a GPO that took the group Authenticated Users and read permission away from the key HKLM\System\CurrentControlSet\Services\EventLog\security

Putting this back per Microsoft's recommendation corrected the issue. I suspect giving all authenticated users read at a higher level will also correct your problem.

Conversion from List<T> to array T[]

One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:

list.AsParallel().ToArray();

To find first N prime numbers in python

Fastests

import math

n = 10000 #first 10000 primes
tmp_n = 1
p = 3

primes = [2]


while tmp_n < n:

    is_prime = True

    for i in range(3, int(math.sqrt(p) + 1), 2):
        # range with step 2

        if p % i == 0:
            is_prime = False

    if is_prime:
        primes += [p]
        tmp_n += 1

    p += 2

print(primes)

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

List<String> allNames = new ArrayList<String>();

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

OS X Terminal UTF-8 issues

For me, this helped: I checked locale on my local shell in terminal

$ locale
LANG="cs_CZ.UTF-8"
LC_COLLATE="cs_CZ.UTF-8"

Then connected to any remote host I am using via ssh and edited file /etc/profile as root - at the end I added line:

export LANG=cs_CZ.UTF-8

After next connection it works fine in bash, ls and nano.

How to change an element's title attribute using jQuery

In jquery ui modal dialogs you need to use this construct:

$( "#my_dialog" ).dialog( "option", "title", "my new title" );

What does the C++ standard state the size of int, long type to be?

The C++ standard does not specify the size of integral types in bytes, but it specifies minimum ranges they must be able to hold. You can infer minimum size in bits from the required range. You can infer minimum size in bytes from that and the value of the CHAR_BIT macro that defines the number of bits in a byte. In all but the most obscure platforms it's 8, and it can't be less than 8.

One additional constraint for char is that its size is always 1 byte, or CHAR_BIT bits (hence the name). This is stated explicitly in the standard.

The C standard is a normative reference for the C++ standard, so even though it doesn't state these requirements explicitly, C++ requires the minimum ranges required by the C standard (page 22), which are the same as those from Data Type Ranges on MSDN:

  1. signed char: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement and sign-and-magnitude platforms)
  2. unsigned char: 0 to 255
  3. "plain" char: same range as signed char or unsigned char, implementation-defined
  4. signed short: -32767 to 32767
  5. unsigned short: 0 to 65535
  6. signed int: -32767 to 32767
  7. unsigned int: 0 to 65535
  8. signed long: -2147483647 to 2147483647
  9. unsigned long: 0 to 4294967295
  10. signed long long: -9223372036854775807 to 9223372036854775807
  11. unsigned long long: 0 to 18446744073709551615

A C++ (or C) implementation can define the size of a type in bytes sizeof(type) to any value, as long as

  1. the expression sizeof(type) * CHAR_BIT evaluates to a number of bits high enough to contain required ranges, and
  2. the ordering of type is still valid (e.g. sizeof(int) <= sizeof(long)).

Putting this all together, we are guaranteed that:

  • char, signed char, and unsigned char are at least 8 bits
  • signed short, unsigned short, signed int, and unsigned int are at least 16 bits
  • signed long and unsigned long are at least 32 bits
  • signed long long and unsigned long long are at least 64 bits

No guarantee is made about the size of float or double except that double provides at least as much precision as float.

The actual implementation-specific ranges can be found in <limits.h> header in C, or <climits> in C++ (or even better, templated std::numeric_limits in <limits> header).

For example, this is how you will find maximum range for int:

C:

#include <limits.h>
const int min_int = INT_MIN;
const int max_int = INT_MAX;

C++:

#include <limits>
const int min_int = std::numeric_limits<int>::min();
const int max_int = std::numeric_limits<int>::max();

What is the single most influential book every programmer should read?

Fortran IV with Watfor and Watfiv by Cress, Dirkson and Graham.

This book taught me my first programming language that I programmed onto punch cards at the time. After 3 years, the book was all tatters because I had used it so much.

alt text http://g-ecx.images-amazon.com/images/G/01/ciu/4b/83/245d9833e7a03768eaf63110._AA240_.L.jpg

Fortran was a great language! It had a super optimizer and produced very fast code. It is still very popular in Great Britain and FTN95 is now a very full-featured and capable compiler. I sometimes wish I could have continued to use it, but Delphi is a more than adequate replacement.

Compare dates in MySQL

I got the answer.

Here is the code:

SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
    AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Java: Retrieving an element from a HashSet

If you know what element you want to retrieve, then you already have the element. The only question for a Set to answer, given an element, is whether it contains() it or not.

If you want to iterator over the elements, just use a Set.iterator().

It sounds like what you're trying to do is designate a canonical element for an equivalence class of elements. You can use a Map<MyObject,MyObject> to do this. See this SO question or this one for a discussion.

If you are really determined to find an element that .equals() your original element with the constraint that you MUST use the HashSet, I think you're stuck with iterating over it and checking equals() yourself. The API doesn't let you grab something by its hash code. So you could do:

MyObject findIfPresent(MyObject source, HashSet<MyObject> set)
{
   if (set.contains(source)) {
      for (MyObject obj : set) {
        if (obj.equals(source)) 
          return obj;
      } 
   }

  return null;
}

Brute force and O(n) ugly, but if that's what you need to do...

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

Conversion failed when converting date and/or time from character string while inserting datetime

convert(datetime2,((SUBSTRING( ISNULL(S2.FechaReal,e.ETA),7,4)+'-'+ SUBSTRING( ISNULL(S2.FechaReal,e.ETA),4,2)+'-'+ SUBSTRING( ISNULL(S2.FechaReal,e.ETA),1,2) + ' 12:00:00.127')))  as fecha,

A simple explanation of Naive Bayes Classification

Naive Bayes: Naive Bayes comes under supervising machine learning which used to make classifications of data sets. It is used to predict things based on its prior knowledge and independence assumptions.

They call it naive because it’s assumptions (it assumes that all of the features in the dataset are equally important and independent) are really optimistic and rarely true in most real-world applications.

It is classification algorithm which makes the decision for the unknown data set. It is based on Bayes Theorem which describe the probability of an event based on its prior knowledge.

Below diagram shows how naive Bayes works

enter image description here

Formula to predict NB:

enter image description here

How to use Naive Bayes Algorithm ?

Let's take an example of how N.B woks

Step 1: First we find out Likelihood of table which shows the probability of yes or no in below diagram. Step 2: Find the posterior probability of each class.

enter image description here

Problem: Find out the possibility of whether the player plays in Rainy condition?

P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)

P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36

Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.

For more reference refer these blog.

Refer GitHub Repository Naive-Bayes-Examples

What are the differences between git remote prune, git prune, git fetch --prune, etc

Note that one difference between git remote --prune and git fetch --prune is being fixed, with commit 10a6cc8, by Tom Miller (tmiller) (for git 1.9/2.0, Q1 2014):

When we have a remote-tracking branch named "frotz/nitfol" from a previous fetch, and the upstream now has a branch named "**frotz"**, fetch would fail to remove "frotz/nitfol" with a "git fetch --prune" from the upstream.
git would inform the user to use "git remote prune" to fix the problem.

So: when a upstream repo has a branch ("frotz") with the same name as a branch hierarchy ("frotz/xxx", a possible branch naming convention), git remote --prune was succeeding (in cleaning up the remote tracking branch from your repo), but git fetch --prune was failing.

Not anymore:

Change the way "fetch --prune" works by moving the pruning operation before the fetching operation.
This way, instead of warning the user of a conflict, it automatically fixes it.

AngularJS sorting by property

according to http://docs.angularjs.org/api/ng.filter:orderBy , orderBy sorts an array. In your case you're passing an object, so You'll have to implement Your own sorting function.

or pass an array -

$scope.testData = {
    C: {name:"CData", order: 1},
    B: {name:"BData", order: 2},
    A: {name:"AData", order: 3},
}

take a look at http://jsfiddle.net/qaK56/

What's the best way to limit text length of EditText in Android

This works fine...

android:maxLength="10"

this will accept only 10 characters.

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

static String toHex(byte[] digest) {
    String digits = "0123456789abcdef";
    StringBuilder sb = new StringBuilder(digest.length * 2);
    for (byte b : digest) {
        int bi = b & 0xff;
        sb.append(digits.charAt(bi >> 4));
        sb.append(digits.charAt(bi & 0xf));
    }
    return sb.toString();
}

Oracle sqlldr TRAILING NULLCOLS required, but why?

Last column in your input file must have some data in it (be it space or char, but not null). I guess, 1st record contains null after last ',' which sqlldr won't recognize unless specifically asked to recognize nulls using TRAILING NULLCOLS option. Alternatively, if you don't want to use TRAILING NULLCOLS, you will have to take care of those NULLs before you pass the file to sqlldr. Hope this helps

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

Go to the task manager, kill the java processes and turn the server back on. should work fine.

When to use an interface instead of an abstract class and vice versa?

This can be a very difficult call to make...

One pointer I can give: An object can implement many interfaces, whilst an object can only inherit one base class( in a modern OO language like c#, I know C++ has multiple inheritance - but isn't that frowned upon?)

Eclipse plugin for generating a class diagram

Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.

What do the return values of Comparable.compareTo mean in Java?

take example if we want to compare "a" and "b", i.e ("a" == this)

  1. negative int if a < b
  2. if a == b
  3. Positive int if a > b

Can Mockito capture arguments of a method called multiple times?

If you don't want to validate all the calls to doSomething(), only the last one, you can just use ArgumentCaptor.getValue(). According to the Mockito javadoc:

If the method was called multiple times then it returns the latest captured value

So this would work (assumes Foo has a method getName()):

ArgumentCaptor<Foo> fooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar, times(2)).doSomething(fooCaptor.capture());
//getValue() contains value set in second call to doSomething()
assertEquals("2nd one", fooCaptor.getValue().getName());

Fuzzy matching using T-SQL

do it this way

         create table person(
         personid int identity(1,1) primary key,
         firstname varchar(20),
         lastname varchar(20),
         addressindex int,
         sound varchar(10)
         )

and later on create a trigger

         create trigger trigoninsert for dbo.person
         on insert 
         as
         declare @personid int;
         select @personid=personid from inserted;
         update person
         set sound=soundex(firstname) where personid=@personid;

now what i can do is i can create a procedure which looks something like this

         create procedure getfuzzi(@personid int)
          as
         declare @sound varchar(10);
         set @sound=(select sound from person where personid=@personid;
         select personid,firstname,lastname,addressindex from person
         where sound=@sound

this will return you all the names that are nearly in match with the names provided by for a particular personid

vba: get unique values from array

There's no built-in functionality to remove duplicates from arrays. Raj's answer seems elegant, but I prefer to use dictionaries.

Dim d As Object
Set d = CreateObject("Scripting.Dictionary")
'Set d = New Scripting.Dictionary

Dim i As Long
For i = LBound(myArray) To UBound(myArray)
    d(myArray(i)) = 1
Next i

Dim v As Variant
For Each v In d.Keys()
    'd.Keys() is a Variant array of the unique values in myArray.
    'v will iterate through each of them.
Next v

EDIT: I changed the loop to use LBound and UBound as per Tomalak's suggested answer. EDIT: d.Keys() is a Variant array, not a Collection.

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

Why use deflate instead of gzip for text files served by Apache?

There shouldn't be any difference in gzip & deflate for decompression. Gzip is just deflate with a few dozen byte header wrapped around it including a checksum. The checksum is the reason for the slower compression. However when you're precompressing zillions of files you want those checksums as a sanity check in your filesystem. In addition you can utilize commandline tools to get stats on the file. For our site we are precompressing a ton of static data (the entire open directory, 13,000 games, autocomplete for millions of keywords, etc.) and we are ranked 95% faster than all websites by Alexa. Faxo Search. However, we do utilize a home grown proprietary web server. Apache/mod_deflate just didn't cut it. When those files are compressed into the filesystem not only do you take a hit for your file with the minimum filesystem block size but all the unnecessary overhead in managing the file in the filesystem that the webserver could care less about. Your concerns should be total disk footprint and access/decompression time and secondarily speed in being able to get this data precompressed. The footprint is important because even though disk space is cheap you want as much as possible to fit in the cache.

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

Work on a remote project with Eclipse via SSH

This answer currently only applies to using two Linux computers [or maybe works on Mac too?--untested on Mac] (syncing from one to the other) because I wrote this synchronization script in bash. It is simply a wrapper around git, however, so feel free to take it and convert it into a cross-platform Python solution or something if you wish


This doesn't directly answer the OP's question, but it is so close I guarantee it will answer many other peoples' question who land on this page (mine included, actually, as I came here first before writing my own solution), so I'm posting it here anyway.

I want to:

  1. develop code using a powerful IDE like Eclipse on a light-weight Linux computer, then
  2. build that code via ssh on a different, more powerful Linux computer (from the command-line, NOT from inside Eclipse)

Let's call the first computer where I write the code "PC1" (Personal Computer 1), and the 2nd computer where I build the code "PC2". I need a tool to easily synchronize from PC1 to PC2. I tried rsync, but it was insanely slow for large repos and took tons of bandwidth and data.

So, how do I do it? What workflow should I use? If you have this question too, here's the workflow that I decided upon. I wrote a bash script to automate the process by using git to automatically push changes from PC1 to PC2 via a remote repository, such as github. So far it works very well and I'm very pleased with it. It is far far far faster than rsync, more trustworthy in my opinion because each PC maintains a functional git repo, and uses far less bandwidth to do the whole sync, so it's easily doable over a cell phone hot spot without using tons of your data.

Setup:

  1. Install the script on PC1 (this solution assumes ~/bin is in your $PATH):

    git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.git
    cd eRCaGuy_dotfiles/useful_scripts
    mkdir -p ~/bin
    ln -s "${PWD}/sync_git_repo_from_pc1_to_pc2.sh" ~/bin/sync_git_repo_from_pc1_to_pc2
    cd ..
    cp -i .sync_git_repo ~/.sync_git_repo
    
  2. Now edit the "~/.sync_git_repo" file you just copied above, and update its parameters to fit your case. Here are the parameters it contains:

    # The git repo root directory on PC2 where you are syncing your files TO; this dir must *already exist* 
    # and you must have *already `git clone`d* a copy of your git repo into it!
    # - Do NOT use variables such as `$HOME`. Be explicit instead. This is because the variable expansion will 
    #   happen on the local machine when what we need is the variable expansion from the remote machine. Being 
    #   explicit instead just avoids this problem.
    PC2_GIT_REPO_TARGET_DIR="/home/gabriel/dev/eRCaGuy_dotfiles" # explicitly type this out; don't use variables
    
    PC2_SSH_USERNAME="my_username" # explicitly type this out; don't use variables
    PC2_SSH_HOST="my_hostname"     # explicitly type this out; don't use variables
    
  3. Git clone your repo you want to sync on both PC1 and PC2.

  4. Ensure your ssh keys are all set up to be able to push and pull to the remote repo from both PC1 and PC2. Here's some helpful links:
    1. https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh
    2. https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
  5. Ensure your ssh keys are all set up to ssh from PC1 to PC2.
  6. Now cd into any directory within the git repo on PC1, and run:

    sync_git_repo_from_pc1_to_pc2
    
  7. That's it! About 30 seconds later everything will be magically synced from PC1 to PC2, and it will be printing output the whole time to tell you what it's doing and where it's doing it on your disk and on which computer. It's safe too, because it doesn't overwrite or delete anything that is uncommitted. It backs it up first instead! Read more below for how that works.

Here's the process this script uses (ie: what it's actually doing)

  1. From PC1: It checks to see if any uncommitted changes are on PC1. If so, it commits them to a temporary commit on the current branch. It then force pushes them to a remote SYNC branch. Then it uncommits its temporary commit it just did on the local branch, then it puts the local git repo back to exactly how it was by staging any files that were previously staged at the time you called the script. Next, it rsyncs a copy of the script over to PC2, and does an ssh call to tell PC2 to run the script with a special option to just do PC2 stuff.
  2. Here's what PC2 does: it cds into the repo, and checks to see if any local uncommitted changes exist. If so, it creates a new backup branch forked off of the current branch (sample name: my_branch_SYNC_BAK_20200220-0028hrs-15sec <-- notice that's YYYYMMDD-HHMMhrs--SSsec), and commits any uncommitted changes to that branch with a commit message such as DO BACKUP OF ALL UNCOMMITTED CHANGES ON PC2 (TARGET PC/BUILD MACHINE). Now, it checks out the SYNC branch, pulling it from the remote repository if it is not already on the local machine. Then, it fetches the latest changes on the remote repository, and does a hard reset to force the local SYNC repository to match the remote SYNC repository. You might call this a "hard pull". It is safe, however, because we already backed up any uncommitted changes we had locally on PC2, so nothing is lost!
  3. That's it! You now have produced a perfect copy from PC1 to PC2 without even having to ensure clean working directories, as the script handled all of the automatic committing and stuff for you! It is fast and works very well on huge repositories. Now you have an easy mechanism to use any IDE of your choice on one machine while building or testing on another machine, easily, over a wifi hot spot from your cell phone if needed, even if the repository is dozens of gigabytes and you are time and resource-constrained.

Resources:

  1. The whole project: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles
    1. See tons more links and references in the source code itself within this project.
  2. How to do a "hard pull", as I call it: How do I force "git pull" to overwrite local files?

Related:

  1. git repository sync between computers, when moving around?

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

Read JSON data in a shell script

There is jq for parsing json on the command line:

 jq '.Body'

Visit this for jq: https://stedolan.github.io/jq/

Entity Framework select distinct name

use Select().Distinct()

for example

DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();

Pandas split column of lists into multiple columns

This solution preserves the index of the df2 DataFrame, unlike any solution that uses tolist():

df3 = df2.teams.apply(pd.Series)
df3.columns = ['team1', 'team2']

Here's the result:

  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

Command to collapse all sections of code?

if you want to collapse and expand particular loop, if else then install following plugins for visual studio.

enter image description here

Clear the value of bootstrap-datepicker

I was having similar trouble and the following worked for me:

$('#datepicker').val('').datepicker('update');

Both method calls were needed, otherwise it didn't clear.

Does java.util.List.isEmpty() check if the list itself is null?

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

How to delete migration files in Rails 3

You can also run a down migration like so:

rake db:migrate:down VERSION=versionnumber

Refer to the Ruby on Rails guide on migrations for more info.

How do I include a pipe | in my linux find -exec command?

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID

How do I install a plugin for vim?

To expand on Karl's reply, Vim looks in a specific set of directories for its runtime files. You can see that set of directories via :set runtimepath?. In order to tell Vim to also look inside ~/.vim/vim-haml you'll want to add

set runtimepath+=$HOME/.vim/vim-haml

to your ~/.vimrc. You'll likely also want the following in your ~/.vimrc to enable all the functionality provided by vim-haml.

filetype plugin indent on
syntax on

You can refer to the 'runtimepath' and :filetype help topics in Vim for more information.

Do I need <class> elements in persistence.xml?

You can provide for jar-file element path to a folder with compiled classes. For example I added something like that when I prepared persistence.xml to some integration tests:

 <jar-file>file:../target/classes</jar-file>

The simplest way to resize an UIImage?

I've also seen this done as well (which I use on UIButtons for Normal and Selected state since buttons don't resize to fit). Credit goes to whoever the original author was.

First make an empty .h and .m file called UIImageResizing.h and UIImageResizing.m

// Put this in UIImageResizing.h
@interface UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size;
@end

// Put this in UIImageResizing.m
@implementation UIImage (Resize)

- (UIImage*)scaleToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);

CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);

UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return scaledImage;
}

@end

Include that .h file in whatever .m file you're going to use the function in and then call it like this:

UIImage* image = [UIImage imageNamed:@"largeImage.png"];
UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];

Why do we always prefer using parameters in SQL statements?

In addition to other answers need to add that parameters not only helps prevent sql injection but can improve performance of queries. Sql server caching parameterized query plans and reuse them on repeated queries execution. If you not parameterized your query then sql server would compile new plan on each query(with some exclusion) execution if text of query would differ.

More information about query plan caching

Can I update a component's props in React.js?

A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.

For instance, a Dashboard has a speed field in its state, and passes it to a Gauge child thats displays this speed. Its render method is just return <Gauge speed={this.state.speed} />. When the Dashboard calls this.setState({speed: this.state.speed + 1}), the Gauge is re-rendered with the new value for speed.

Just before this happens, Gauge's componentWillReceiveProps is called, so that the Gauge has a chance to compare the new value to the old one.

Getting value from appsettings.json in .net core

  1. Add the required key here like this. In this case its SecureCookies:

Add the required key here like this. In this case its SecureCookies

  1. In startup.cs, add the constructor

     public Startup(IConfiguration configuration)
     {
         Configuration = configuration;
    
     }
     public IConfiguration Configuration { get; }
    
  2. Access the settings using Configuration["SecureCookies"]

CSS horizontal centering of a fixed div?

left: 50%;
margin-left: -400px; /* Half of the width */

Error In PHP5 ..Unable to load dynamic library

Well for Ubuntu 14.04 I was getting that error just for mcrypt:

PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/mcrypt.ini' - /usr/lib/php5/20121212/mcrypt.ini: cannot open shared object file: No such file or directory in Unknown on line 0

If you have a closer look at the error, php is looking for mcrypt.ini and not for mcrypt.so at that location. I just copy mcrypt.so to mcrypt.ini and that's it, the warning is gone and the extension now is properly installed. It might look a bit dirty but it worked!

How to iterate std::set?

Another example for the C++11 standard:

set<int> data;
data.insert(4);
data.insert(5);

for (const int &number : data)
  cout << number;

.htaccess not working apache

First, note that restarting httpd is not necessary for .htaccess files. .htaccess files are specifically for people who don't have root - ie, don't have access to the httpd server config file, and can't restart the server. As you're able to restart the server, you don't need .htaccess files and can use the main server config directly.

Secondly, if .htaccess files are being ignored, you need to check to see that AllowOverride is set correctly. See http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride for details. You need to also ensure that it is set in the correct scope - ie, in the right block in your configuration. Be sure you're NOT editing the one in the block, for example.

Third, if you want to ensure that a .htaccess file is in fact being read, put garbage in it. An invalid line, such as "INVALID LINE HERE", in your .htaccess file, will result in a 500 Server Error when you point your browser at the directory containing that file. If it doesn't, then you don't have AllowOverride configured correctly.

Using global variables between files?

I just came across this post and thought of posting my solution, just in case of anyone being in the same situation as me, where there are quite some files in the developed program, and you don't have the time to think through the whole import sequence of your modules (if you didn't think of that properly right from the start, such as I did).

In such cases, in the script where you initiate your global(s), simply code a class which says like:

class My_Globals:
  def __init__(self):
    self.global1 = "initial_value_1"
    self.global2 = "initial_value_2"
    ...

and then use, instead of the line in the script where you initiated your globals, instead of

global1 = "initial_value_1"

use

globals = My_Globals()

I was then able to retrieve / change the values of any of these globals via

globals.desired_global

in any script, and these changes were automatically also applied to all the other scripts using them. All worked now, by using the exact same import statements which previously failed, due to the problems mentioned in this post / discussion here. I simply thought of global object's properties being changing dynamically without the need of considering / changing any import logic, in comparison to simple importing of global variables, and that definitely was the quickest and easiest (for later access) approach to solve this kind of problem for me.

Sending arrays with Intent.putExtra

This code sends array of integer values

Initialize array List

List<Integer> test = new ArrayList<Integer>();

Add values to array List

test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);

Send the array list values to target activity

intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);

here you get values on targetActivty

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");

Auto submit form on page load

Add the following to Body tag,

<body onload="document.forms['member_signup'].submit()">

and give name attribute to your Form.

<form method="POST" action="" name="member_signup">

How to get the file extension in PHP?

You could try with this for mime type

$image = getimagesize($_FILES['image']['tmp_name']);

$image['mime'] will return the mime type.

This function doesn't require GD library. You can find the documentation here.

This returns the mime type of the image.

Some people use the $_FILES["file"]["type"] but it's not reliable as been given by the browser and not by PHP.

You can use pathinfo() as ThiefMaster suggested to retrieve the image extension.

First make sure that the image is being uploaded successfully while in development before performing any operations with the image.

Submit Button Image

It's very important for accessibility reasons that you always specify value of the submit even if you are hiding this text, or if you use <input type="image" .../> to always specify alt="" attribute for this input field.

Blind people don't know what button will do if it doesn't contain meaningful alt="" or value="".

Java Enum Methods - return opposite direction enum

Create an abstract method, and have each of your enumeration values override it. Since you know the opposite while you're creating it, there's no need to dynamically generate or create it.

It doesn't read nicely though; perhaps a switch would be more manageable?

public enum Direction {
    NORTH(1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.SOUTH;
        }
    },
    SOUTH(-1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.NORTH;
        }
    },
    EAST(-2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.WEST;
        }
    },
    WEST(2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.EAST;
        }
    };

    Direction(int code){
        this.code=code;
    }
    protected int code;

    public int getCode() {
        return this.code;
    }

    public abstract Direction getOppositeDirection();
}

SDK Manager.exe doesn't work

I had the same problem.

when i run \tools\android.bat, i got the exception: Exception in thread main

 java.lang.NoClassDefFoundError: com/android/sdkmanager/Main

My resolved method:

  1. edit \tools\android.bat
  2. find "%jar_path%;%swt_path%\swt.jar"
  3. modify to "%tools_dir%\%jar_path%;%tools_dir%\%swt_path%\swt.jar"
  4. save, and run SDK Manager.exe again

Clear back stack using fragments

I posted something similar here

From Joachim's answer, from Dianne Hackborn:

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

I ended up just using:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    
    fm.popBackStack();
}

But could equally have used something like:

((AppCompatActivity)getContext()).getSupportFragmentManager().popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)

Which will pop all states up to the named one. You can then just replace the fragment with what you want

Show/hide 'div' using JavaScript

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

Recommendation for compressing JPG files with ImageMagick

I use always:

  • quality in 85
  • progressive (comprobed compression)
  • a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably optimizes the size of the jpeg.
  • Strip any comment or EXIF metadata

in imagemagick should be

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg

or in the newer version:

magick source.jpg -strip -interlace Plane -gaussian-blur 0.05 -quality 85% result.jpg

Source.

From @Fordi in the comments (Don't forget to upvote him if you like this): If you dislike blurring, use -sampling-factor 4:2:0 instead. What this does is reduce the chroma channel's resolution to half, without messing with the luminance resolution that your eyes latch onto. If you want better fidelity in the conversion, you can get a slight improvement without an increase in filesize by specifying -define jpeg:dct-method=float - that is, use the more accurate floating point discrete cosine transform, rather than the default fast integer version.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

With C++11 or higher you can use find() and find_first_of()

Example using find to find a single char:

#include <string>
std::string name = "Aaah";
size_t found_index = name.find('a');
if (found_index != std::string::npos) {
    // Found string containing 'a'
}

Example using find to find a full string & starting from position 5:

std::string name = "Aaah";
size_t found_index = name.find('h', 3);
if (found_index != std::string::npos) {
    // Found string containing 'h'
}

Example using the find_first_of() and only the first char, to search at the start only:

std::string name = ".hidden._di.r";
size_t found_index = name.find_first_of('.');
if (found_index == 0) {
    // Found '.' at first position in string
}

Good luck!

What's the difference between a POST and a PUT HTTP REQUEST?

Please see: http://zacharyvoase.com/2009/07/03/http-post-put-diff/

I’ve been getting pretty annoyed lately by a popular misconception by web developers that a POST is used to create a resource, and a PUT is used to update/change one.

If you take a look at page 55 of RFC 2616 (“Hypertext Transfer Protocol – HTTP/1.1”), Section 9.6 (“PUT”), you’ll see what PUT is actually for:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

There’s also a handy paragraph to explain the difference between POST and PUT:

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request – the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.

It doesn’t mention anything about the difference between updating/creating, because that’s not what it’s about. It’s about the difference between this:

obj.set_attribute(value) # A POST request.

And this:

obj.attribute = value # A PUT request.

So please, stop the spread of this popular misconception. Read your RFCs.

load jquery after the page is fully loaded

You can also use:

$(window).bind("load", function() { 
    // Your code here.
});

How to get date in BAT file

You get and format like this

for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
     set dow=%%i
     set month=%%j
     set day=%%k
     set year=%%l
)
set datestr=%month%_%day%_%year%
echo datestr is %datestr%

Note: Above only works on US locale. It assumes the output of echo %date% looks like this: Thu 02/13/21. If you have different Windows locale settings, you will need to modify the script based on your configuration.

FFmpeg: How to split video efficiently?

http://ffmpeg.org/trac/ffmpeg/wiki/Seeking%20with%20FFmpeg may also be useful to you. Also ffmpeg has a segment muxer that might work.

Anyway my guess is that combining them into one command would save time.

Set Page Title using PHP

I know this is an old post but having read this I think this solution is much simpler (though technically it solves the problem with Javascript not PHP).

    <html>
    <head>
    <title>Ultan.me - Unset</title>
    <script type="text/javascript">
        function setTitle( text ) {
            document.title = text;
        }
    </script>
    <!-- other head info -->
    </head>

    <?php 
    // Make the call to the DB to get the title text. See OP post for example
    $title_text = "Ultan.me - DB Title";

    // Use body onload to set the title of the page
    print "<body onload=\"setTitle( '$title_text' )\"   >";

    // Rest of your code here
    print "<p>Either use php to print stuff</p>";
    ?>
    <p>or just drop in and out of php</p>
    <?php

    // close the html page
    print "</body></html>";
    ?>

uncaught syntaxerror unexpected token U JSON

I was getting this error, when I was using the same variable for json string and parsed json:

var json = '{"1":{"url":"somesite1","poster":"1.png","title":"site title"},"2":{"url":"somesite2","poster":"2.jpg","title":"site 2 title"}}'

function usingjson(){
    var json = JSON.parse(json);
}

I changed function to:

function usingjson(){
    var j = JSON.parse(json);
}

Now this error went away.

Find the number of employees in each department - SQL Oracle

select  d.dname
       ,count(e.empno) as count 
from dept d 
left outer join emp e 
  on e.deptno=d.deptno 
group by d.dname;

How to call same method for a list of objects?

Starting in Python 2.6 there is a operator.methodcaller function.

So you can get something more elegant (and fast):

from operator import methodcaller

map(methodcaller('method_name'), list_of_objects)

Coerce multiple columns to factors at once

The more recent tidyverse way is to use the mutate_at function:

library(tidyverse)
library(magrittr)
set.seed(88)

data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
cols <- c("A", "C", "D", "H")

data %<>% mutate_at(cols, funs(factor(.)))
str(data)
 $ A: Factor w/ 4 levels "5","17","18",..: 2 1 4 3   
 $ B: int  36 35 2 26
 $ C: Factor w/ 4 levels "22","31","32",..: 1 2 4 3
 $ D: Factor w/ 4 levels "1","9","16","39": 3 4 1 2
 $ E: int  3 14 30 38
 $ F: int  27 15 28 37
 $ G: int  19 11 6 21
 $ H: Factor w/ 4 levels "7","12","20",..: 1 3 4 2
 $ I: int  23 24 13 8
 $ J: int  10 25 4 33

Best way to get value from Collection by index

You must either wrap your collection in a list (new ArrayList(c)) or use c.toArray() since Collections have no notion of "index" or "order".

React Error: Target Container is not a DOM Element

I figured it out!

After reading this blog post I realized that the placement of this line:

<script src="{% static "build/react.js" %}"></script>

was wrong. That line needs to be the last line in the <body> section, right before the </body> tag. Moving the line down solves the problem.

My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags. Because of this it couldn't find the content id, and thus it wasn't a real DOM element.

How to convert a data frame column to numeric type?

If you don't care about preserving the factors, and want to apply it to any column that can get converted to numeric, I used the script below. if df is your original dataframe, you can use the script below.

df[] <- lapply(df, as.character)
df <- data.frame(lapply(df, function(x) ifelse(!is.na(as.numeric(x)), as.numeric(x),  x)))

I referenced Shane's and Joran's solution btw

MySQL Update Column +1?

How about:

update table
set columnname = columnname + 1
where id = <some id>

How to embed PDF file with responsive width

<html>
<head>
<style type="text/css">
#wrapper{ width:100%; float:left; height:auto; border:1px solid #5694cf;}
</style>
</head>
<div id="wrapper">
<object data="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf" width="100%" height="100%">
<p>Your web browser doesn't have a PDF Plugin. Instead you can <a href="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf"> Click
here to download the PDF</a></p>
</object>
</div>
</html>

SQL Server: combining multiple rows into one row

Using MySQL inbuilt function group_concat() will be a good choice for getting the desired result. The syntax will be -

SELECT group_concat(STRINGVALUE) 
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534
AND ISSUE = 19602

Before you execute the above command make sure you increase the size of group_concat_max_len else the the whole output may not fit in that cell.

To set the value of group_concat_max_len, execute the below command-

SET group_concat_max_len = 50000;

You can change the value 50000 accordingly, you increase it to a higher value as required.

How do I initialize a TypeScript Object with a JSON-Object?

I've been using this guy to do the job: https://github.com/weichx/cerialize

It's very simple yet powerful. It supports:

  • Serialization & deserialization of a whole tree of objects.
  • Persistent & transient properties on the same object.
  • Hooks to customize the (de)serialization logic.
  • It can (de)serialize into an existing instance (great for Angular) or generate new instances.
  • etc.

Example:

class Tree {
  @deserialize public species : string; 
  @deserializeAs(Leaf) public leafs : Array<Leaf>;  //arrays do not need extra specifications, just a type.
  @deserializeAs(Bark, 'barkType') public bark : Bark;  //using custom type and custom key name
  @deserializeIndexable(Leaf) public leafMap : {[idx : string] : Leaf}; //use an object as a map
}

class Leaf {
  @deserialize public color : string;
  @deserialize public blooming : boolean;
  @deserializeAs(Date) public bloomedAt : Date;
}

class Bark {
  @deserialize roughness : number;
}

var json = {
  species: 'Oak',
  barkType: { roughness: 1 },
  leafs: [ {color: 'red', blooming: false, bloomedAt: 'Mon Dec 07 2015 11:48:20 GMT-0500 (EST)' } ],
  leafMap: { type1: { some leaf data }, type2: { some leaf data } }
}
var tree: Tree = Deserialize(json, Tree);

PHP "php://input" vs $_POST

Simple example of how to use it

 <?php  
     if(!isset($_POST) || empty($_POST)) { 
     ?> 
        <form name="form1" method="post" action=""> 
          <input type="text" name="textfield"><br /> 
          <input type="submit" name="Submit" value="submit"> 
        </form> 
   <?php  
        } else { 
        $example = file_get_contents("php://input");
        echo $example;  }  
   ?>

How to read a file into vector in C++?

1. In the loop you are assigning value rather than comparing value so

i=((Main.size())-1) -> i=(-1) since Main.size()

Main[i] will yield "Vector Subscript out of Range" coz i = -1.

2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.

How to change a string into uppercase

to make the string upper case -- just simply type

s.upper()

simple and easy! you can do the same to make it lower too

s.lower()

etc.

WCF named pipe minimal example

Try this.

Here is the service part.

[ServiceContract]
public interface IService
{
    [OperationContract]
    void  HelloWorld();
}

public class Service : IService
{
    public void HelloWorld()
    {
        //Hello World
    }
}

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
{
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
    {

    }
    public void InvokeHelloWorld()
    {
        Channel.HelloWorld();
    }
}

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
    serviceHost.Open();

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
    {
        Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
    }

How to find the port for MS SQL Server 2008?

Try this (requires access to sys.dm_exec_connections):

SELECT DISTINCT 
    local_tcp_port 
FROM sys.dm_exec_connections 
WHERE local_tcp_port IS NOT NULL

How to pass command line argument to gnuplot?

@vagoberto's answer seems the best IMHO if you need positional arguments, and I have a small improvement to add.

vagoberto's suggestion:

#!/usr/local/bin/gnuplot --persist

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD 
print "number of arguments: ", ARGC 

which gets called by:

$ gnuplot -c script.gp one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

for those lazy typers like myself, one could make the script executable (chmod 755 script.gp)

then use the following:

#!/usr/bin/env gnuplot -c

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD
print "number of arguments: ", ARGC

and execute it as:

$ ./imb.plot a b c d
script name        : ./imb.plot
first argument     : a
third argument     : c
number of arguments: 4

Submit form without page reloading

You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.

I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.

Difference between subprocess.Popen and os.system

If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system() with subprocess.Popen():

sts = os.system("mycmd" + " myarg")

...does the same thing as...

sts = Popen("mycmd" + " myarg", shell=True).wait()

The "improved" code looks more complicated, but it's better because once you know subprocess.Popen(), you don't need anything else. subprocess.Popen() replaces several other tools (os.system() is just one of those) that were scattered throughout three other Python modules.

If it helps, think of subprocess.Popen() as a very flexible os.system().

Mounting multiple volumes on a docker container?

Docker now recommends migrating towards using --mount.

Multiple volume mounts are also explained in detail in the current Docker documentation.

From: https://docs.docker.com/storage/bind-mounts/

$ docker run -d \
  -it \
  --name devtest \
  --mount type=bind,source="$(pwd)"/target,target=/app \
  --mount type=bind,source="$(pwd)"/target,target=/app2,readonly,bind-propagation=rslave \
  nginx:latest

Original older answer should still work; just trying to keep the answer aligned to current best known method.

Why can't Python parse this JSON data?

As a python3 user,

The difference between load and loads methods is important especially when you read json data from file.

As stated in the docs:

json.load:

Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads:

json.loads: Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

json.load method can directly read opened json document since it is able to read binary file.

with open('./recipes.json') as data:
  all_recipes = json.load(data)

As a result, your json data available as in a format specified according to this conversion table:

https://docs.python.org/3.7/library/json.html#json-to-py-table

Clear the entire history stack and start a new activity on Android

I found too simple hack just do this add new element in AndroidManifest as:-

<activity android:name=".activityName"
          android:label="@string/app_name"
          android:noHistory="true"/>

the android:noHistory will clear your unwanted activity from Stack.

CXF: No message body writer found for class - automatically mapping non-simple resources

You can try with mentioning "Accept: application/json" in your rest client header as well, if you are expecting your object as JSON in response.

Print the address or pointer for value in C

I believe this would be most correct.

printf("%p", (void *)emp1);
printf("%p", (void *)*emp1);

printf() is a variadic function and must be passed arguments of the right types. The standard says %p takes void *.

Can you find all classes in a package using reflection?

The most robust mechanism for listing all classes in a given package is currently ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author.)

List<String> classNames = new ArrayList<>();
try (ScanResult scanResult = new ClassGraph().acceptPackages("my.package")
        .enableClassInfo().scan()) {
    classNames.addAll(scanResult.getAllClasses().getNames());
}

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
new Date((new Date("07/06/2012 13:30")).toDateString())
_x000D_
_x000D_
_x000D_

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

Here are three different checkmark styles you can use:

_x000D_
_x000D_
ul:first-child  li:before { content:"\2713\0020"; }  /* OR */_x000D_
ul:nth-child(2) li:before { content:"\2714\0020"; }  /* OR */_x000D_
ul:last-child   li:before { content:"\2611\0020"; }_x000D_
ul { list-style-type: none; }
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul><!-- not working on Stack snippet; check fiddle demo -->_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jsFiddle

References:

Removing items from a list

You need to use Iterator and call remove() on iterator instead of using for loop.

What are the most-used vim commands/keypresses?

What most people do is start out with the bare basics, like maybe i, yw, yy, and p. You can continue to use arrow keys to move around, selecting text with the mouse, using the menus, etc. Then when something is slowing you down, you look up the faster way to do it, and gradually add more and more commands. You might learn one new command per day for a while, then it will trickle to one per week. You'll feel fairly productive in a month. After a year you will have a pretty solid repertoire, and after 2-3 years you won't even consciously think what your fingers are typing, and it will look weird if you have to spell it out for someone. I learned vi in 1993 and still pick up 2 or 3 new commands a year.

How to pass a variable to the SelectCommand of a SqlDataSource?

Just add a custom property to the page which will return the variable of your choice. You can then use the built-in "control" parameter type.

In the code behind, add:

Dim MyVariable as Long


ReadOnly Property MyCustomProperty As Long
    Get
        Return MyVariable
    End Get
End Property

In the select parameters section add:

<asp:ControlParameter ControlID="__Page" Name="MyParameter" 
PropertyName="MyCustomProperty" Type="Int32" />

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

Execute a file with arguments in Python shell

This works:

subprocess.call("python abc.py arg1 arg2", shell=True)

How do I add images in laravel view?

If Image folder location is public/assets/img/default.jpg. You can try in view

   <img src="{{ URL::to('/assets/img/default.jpg') }}">

Compare 2 arrays which returns difference

Array operations like this is not jQuery's strongest point. You should consider a library such as Underscorejs, specifically the difference function.

IF EXISTS condition not working with PLSQL

Unfortunately PL/SQL doesn't have IF EXISTS operator like SQL Server. But you can do something like this:

begin
  for x in ( select count(*) cnt
               from dual 
              where exists (
                select 1 from courseoffering co
                  join co_enrolment ce on ce.co_id = co.co_id
                 where ce.s_regno = 403 
                   and ce.coe_completionstatus = 'C' 
                   and co.c_id = 803 ) )
  loop
        if ( x.cnt = 1 ) 
        then
           dbms_output.put_line('exists');
        else 
           dbms_output.put_line('does not exist');
        end if;
  end loop;
end;
/

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

How to escape a single quote inside awk

Another option is to pass the single quote as an awk variable:

awk -v q=\' 'BEGIN {FS=" ";} {printf "%s%s%s ", q, $1, q}'

Simpler example with string concatenation:

# Prints 'test me', *including* the single quotes.
$ awk -v q=\' '{print q $0 q }' <<<'test me'
'test me'

Fastest JavaScript summation

Based on this test (for-vs-forEach-vs-reduce) and this (loops)

I can say that:

1# Fastest: for loop

var total = 0;

for (var i = 0, n = array.length; i < n; ++i)
{
    total += array[i];
}

2# Aggregate

For you case you won't need this, but it adds a lot of flexibility.

Array.prototype.Aggregate = function(fn) {
    var current
        , length = this.length;

    if (length == 0) throw "Reduce of empty array with no initial value";

    current = this[0];

    for (var i = 1; i < length; ++i)
    {
        current = fn(current, this[i]);
    }

    return current;
};

Usage:

var total = array.Aggregate(function(a,b){ return a + b });

Inconclusive methods

Then comes forEach and reduce which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.

How to force Chrome browser to reload .css file while debugging in Visual Studio?

If you are using Sublime Text 3, using a build system to open the file opens the most current version and provides a convenient way to load it via [CTRL + B] To set up a build system that opens the file in chrome:

  1. Go to 'Tools'

  2. Hover your mouse over 'build system'. At the bottom of the list brought up, click 'New Build System...'

  3. In the new build system file type this:

    {"cmd": [ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "$file"]}
    

**provided the path stated above in the first set of quotes is the path to where chrome is located on your computer, if it isn't simply find the location of chrome and replace the path in the first set of quotes with the path to chrome on your computer.

Python functions call by reference

The answer given is

def set_4(x):
   y = []
   for i in x:
       y.append(i)
   y[0] = 4
   return y

and

l = [0]

def set_3(x):
     x[0] = 3

set_3(l)
print(l[0])

which is the best answer so far as it does what it says in the question. However,it does seem a very clumsy way compared to VB or Pascal.Is it the best method we have?

Not only is it clumsy, it involves mutating the original parameter in some way manually eg by changing the original parameter to a list: or copying it to another list rather than just saying: "use this parameter as a value " or "use this one as a reference". Could the simple answer be there is no reserved word for this but these are great work arounds?

Why should I use IHttpActionResult instead of HttpResponseMessage?

We have the following benefits of using IHttpActionResult over HttpResponseMessage:

  1. By using the IHttpActionResult we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.
  2. Unit testing of the implemented controller method will be easier.
  3. Uses async and await by default.

select records from postgres where timestamp is in certain range

SELECT * 
FROM reservations 
WHERE arrival >= '2012-01-01'
AND arrival < '2013-01-01'
   ;

BTW if the distribution of values indicates that an index scan will not be the worth (for example if all the values are in 2012), the optimiser could still choose a full table scan. YMMV. Explain is your friend.

Adding a caption to an equation in LaTeX

As in this forum post by Gonzalo Medina, a third way may be:

\documentclass{article}
\usepackage{caption}

\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}

\begin{document}

Some text

\begin{equ}[!ht]
  \begin{equation}
    a=b+c
  \end{equation}
\caption{Caption of the equation}
\end{equ}

Some other text
 
\end{document}

More details of the commands used from package caption: here.

A screenshot of the output of the above code:

screenshot of output

Network usage top/htop on Linux

jnettop is another candidate.

edit: it only shows the streams, not the owner processes.

How can I store the result of a system command in a Perl variable?

Also for eg. you can use IPC::Run:

use IPC::Run qw(run);

my $pid = 5892;
run [qw(top -H -n 1 -p), $pid],
    '|', sub { print grep { /myprocess/ } <STDIN> },
    '|', [qw(wc -l)],
    '>', \my $out;

print $out;
  • processes are running without bash subprocess
  • can be piped to perl subs
  • very similar to shell

Setting the height of a SELECT in IE

Yes, you can.

I was able to set the height of my SELECT to exactly what I wanted in IE8 and 9. The trick is to set the box-sizing property to content-box. Doing so will set the content area of the SELECT to the height, but keep in mind that margin, border and padding values will not be calculated in the width/height of the SELECT, so adjust those values accordingly.

select {
    display: block;
    padding: 6px 4px;
    -moz-box-sizing: content-box;
    -webkit-box-sizing:content-box;
    box-sizing:content-box;
    height: 15px;
}

Here is a working jsFiddle. Would you mind confirming and marking the appropriate answer?

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

How to refresh a page with jQuery by passing a parameter to URL

You could simply have just done:

var varAppend = "?single";
window.location.href = window.location.href.replace(".com",".com" + varAppend);

Unlike the other answers provided, there is no needless conditional check. If you design your project properly, you'll let the interface make the decision making and calling that statement whenever an event has been triggered.

Since there will only be one ".com" in your url, it will just replace .com with .com?single. I just added varAppend just in case you want to make it easier to modify the code in the future with different kinds of url variables.

One other note: The .replace works by adding to the href since href returns a string containing the full url address information.

Why does ANT tell me that JAVA_HOME is wrong when it is not?

I was also facing the same problem. I am using Windows 7 and I had two versions of java installed. First I have installed latest version java 7 and then version 5.

Contents of my java installation directory:

C:\Program Files\Java>
jdk1.5.0_14
jdk1.7.0_17
jre1.5.0_14
jre7

and my JAVA_HOME was set to the correct value, which was:

C:\>set ja
JAVA_HOME=C:\Program Files\Java\jdk1.5.0_14

But still I was getting the same problem:

XXXXXXX\build.xml:478: The following error occurred while
executing this line:
XXXXXXX\build.xml:477: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\Program Files\Java\jre7"

After trying out all the suggestion in this thread I realized my mistake. I was trying to set the environment variable in "User variables" instead of "System Variables" section. After setting it in "System Variables" it worked fine. I am facing another problem though.

The default version of java it points to is still 7.

C:\>java -version
java version "1.7.0_17"
Java(TM) SE Runtime Environment (build 1.7.0_17-b02)
Java HotSpot(TM) Client VM (build 23.7-b01, mixed mode, sharing)

I am not sure how to make it point to version 5.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

For those using macOS mkfile might be a good alternative to fallocate or dd

mkfile 100m some100mfile.pdf

reference - https://stackoverflow.com/a/33478049/711401

jQuery Set Cursor Position in Text Area

This worked for me on Safari 5 on Mac OSX, jQuery 1.4:

$("Selector")[elementIx].selectionStart = desiredStartPos; 
$("Selector")[elementIx].selectionEnd = desiredEndPos;

How to log out user from web site using BASIC authentication?

function logout() {
  var userAgent = navigator.userAgent.toLowerCase();

  if (userAgent.indexOf("msie") != -1) {
    document.execCommand("ClearAuthenticationCache", false);
  }

  xhr_objectCarte = null;

  if(window.XMLHttpRequest)
    xhr_object = new XMLHttpRequest();
  else if(window.ActiveXObject)
    xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
  else
    alert ("Your browser doesn't support XMLHTTPREQUEST");

  xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
  xhr_object.send ("");
  xhr_object = null;

  document.location = 'http://yourserver.com'; 
  return false;
}

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)