specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"
http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().
<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" />
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.
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.
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;
}
}
}
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.
There should be three pages here:
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).
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.
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 theWebSecurityConfigurationAdapter
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 whichWebSecurityConfigurerAdapter
should be considered first.3 The
http.antMatcher
states that thisHttpSecurity
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 afterApiWebSecurityConfigurationAdapter
since it has an@Order
value after1
(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()
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.
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.
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.
It is also possible to just turn off logging for that specific class in properties :
logging.level.org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration=WARN
You don't need:
@Configuration
@ComponentScan("com.company.praktikant")
@EnableWebSecurity
already has @Configuration
in it, and I cannot imagine why you put @ComponentScan
there.
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 :)
According to above, your "MyFilter" class is redundant.
You can also remove those:
final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(CORSConfig.class);
annotationConfigApplicationContext.refresh();
From Application class.
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
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:
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.
<?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>
@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;
}
}
@Configuration
@ComponentScan(basePackages = "com.company")
@Import(value = {SecurityConfig.class, PersistenceConfig.class, ScheduleConfig.class})
public class AppConfig {
// application domain @Beans here...
}
@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;
}
}
@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;
}
}
@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
.
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
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.
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();
}
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/
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.
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. :)
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();
}
}
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();
}
}*/
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;
}
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();
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
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>
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.
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.
@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.
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:
ChannelProcessingFilter, because it might need to redirect to a different protocol
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)
ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal
Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token
The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container
The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken
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
AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there
ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched
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 customJwtAuthenticationFilter
.
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.
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">
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;
}
@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.
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().
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();
}
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.
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
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)
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.
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.
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());
}
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>
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')
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.
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.
Use an overloaded version of the method that takes a ProcessStartInfo instance and set the ProcessWindowStyle property to a value that works for you.
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
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:
input.files
FileListvideo.src
propertyLean back and watch :)
http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
(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_
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:
EDIT #1:
Check out the SoapUI link for the latest version. There is a Pro version as well as the free open source version.
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))
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 about this...
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
Try this:
export HTTPS_PROXY_REQUEST_FULLURI=false
solved this issue for me working behind a proxy at a company few weeks ago.
Try this:
this.TextBox3.Text = String.Format("{0: MM.dd.yyyy}",DateTime.Now);
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 .
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:
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>']`
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 = '•';
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.
For powershell, use #
:
PS C:\> echo foo # This is a comment
foo
//a[text()='programming quesions site']/@href
which basically identifies an anchor node <a>
that has the text you want, and extracts the href
attribute.
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:
For future consistence i forked Bankov's repo.
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"
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.
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.
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
import re
htmlString = '</dd><dt> Fine, thank you. </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.
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()
.
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 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.
});
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 //////////
//////////
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
Here is a link to an example using PDFSharp and ConcatenateDocuments
If using a StackTraceElement, use:
String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
System.out.println(simpleClassName);
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.
My solution to that problem is also somewhat of a mix of some solutions already stated here:
local_settings.py
that has the content USING_LOCAL = True
in dev and USING_LOCAL = False
in prodsettings.py
I do an import on that file to get the USING_LOCAL
settingI 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.
Drag and drop is best solution. I am just showing another way to import by clicking the HAR import icon:
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!"
maybe
string = document.location.href;
arrayOfStrings = string.toString().split('/');
assuming you want the current url
this
points to the object in whose member function it is reffered, so it is optional.
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:
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")
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;
}
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();
}
});
}
}
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.
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.
| is the binary or operator
|| is the logic or operator
You can use: Object.keys(obj)
Example:
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_
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.
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.
Follow these steps:
If you don't have the source folder added do the following
Now you can have fun and run the application.
Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:
ax1.set_ylabel('Rate (min?¹)')
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
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"
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]];
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.
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.
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
Here is a heavy tutorial that has good stuff in it to pick out:
http://mobile.tutsplus.com/tutorials/mobile-web-apps/jquery_android/
I have some edit, best working for collections:
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_
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
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
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.
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.
Remove the comma
... Gender,Contact, " + ") VALUES ...
^-----------------here
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>
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;
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.
I have solved this issue as follows:
removed from chrome extension and install ext again. It will work ISA
On your device (iPhone/iPad) goto: Settings -> Developer -> Clear Trusted Computers worked for me.
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");
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)
<input type="text" disabled="disabled" />
is the valid markup.<input type="text" disabled />
is valid and used by W3C on their samples.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.
Copy Database to an other folder and attach or Log in SQLServer with "Windows Authentication"
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> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
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_
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;
}
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();
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
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.
One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:
list.AsParallel().ToArray();
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)
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.
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).
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.
In jquery ui modal dialogs you need to use this construct:
$( "#my_dialog" ).dialog( "option", "title", "my new title" );
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:
signed char
: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement and sign-and-magnitude platforms)unsigned char
: 0 to 255char
: same range as signed char
or unsigned char
, implementation-definedsigned short
: -32767 to 32767unsigned short
: 0 to 65535signed int
: -32767 to 32767unsigned int
: 0 to 65535signed long
: -2147483647 to 2147483647unsigned long
: 0 to 4294967295signed long long
: -9223372036854775807 to 9223372036854775807unsigned long long
: 0 to 18446744073709551615A C++ (or C) implementation can define the size of a type in bytes sizeof(type)
to any value, as long as
sizeof(type) * CHAR_BIT
evaluates to a number of bits high enough to contain required ranges, andsizeof(int) <= sizeof(long)
).Putting this all together, we are guaranteed that:
char
, signed char
, and unsigned char
are at least 8 bitssigned short
, unsigned short
, signed int
, and unsigned int
are at least 16 bitssigned long
and unsigned long
are at least 32 bitssigned long long
and unsigned long long
are at least 64 bitsNo 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();
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.
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')
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...
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.
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,
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
Formula to predict NB:
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.
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
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.
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/
This works fine...
android:maxLength="10"
this will accept only 10
characters.
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();
}
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
Go to the task manager, kill the java processes and turn the server back on. should work fine.
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?)
Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.
take example if we want to compare "a" and "b", i.e ("a" == this)
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());
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
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.
Yes there is retainAll
check out this
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
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.
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
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 conflictaccept working
specifies to keep your working files-R
stands for recursiveHope 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)svn switch
commandSwitch working copy to new branch/tag
option at branch creationThis 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.
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.
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
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
Git clone your repo you want to sync on both PC1 and PC2.
Now cd
into any directory within the git repo on PC1, and run:
sync_git_repo_from_pc1_to_pc2
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.
rsync
s 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.cd
s 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! 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`
There is jq
for parsing json on the command line:
jq '.Body'
Visit this for jq: https://stedolan.github.io/jq/
use Select().Distinct()
for example
DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();
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
if you want to collapse and expand particular loop, if else then install following plugins for visual studio.
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.
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)) {
// ...
}
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
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.
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID
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.
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>
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)];
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.
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.
In startup.cs, add the constructor
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
Access the settings using Configuration["SecureCookies"]
left: 50%;
margin-left: -400px; /* Half of the width */
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!
Another example for the C++11 standard:
set<int> data;
data.insert(4);
data.insert(5);
for (const int &number : data)
cout << number;
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.
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.
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");
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">
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.
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=""
.
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();
}
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:
\tools\android.bat
"%jar_path%;%swt_path%\swt.jar"
"%tools_dir%\%jar_path%;%tools_dir%\%swt_path%\swt.jar"
SDK Manager.exe
againI 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
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
}
I use always:
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
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.
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!
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.
You can also use:
$(window).bind("load", function() {
// Your code here.
});
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.
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.
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>";
?>
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.
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;
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)
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
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".
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.
You can use the str.isspace()
method.
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)))
How about:
update table
set columnname = columnname + 1
where id = <some id>
<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>
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.
I've been using this guy to do the job: https://github.com/weichx/cerialize
It's very simple yet powerful. It supports:
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);
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; }
?>
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.
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.
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);
}
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
@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
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.
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()
.
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.
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
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.
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.
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 *
.
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());
}
new Date((new Date("07/06/2012 13:30")).toDateString())
_x000D_
Here are three different checkmark styles you can use:
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_
References:
You need to use Iterator
and call remove()
on iterator
instead of using for
loop.
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.
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" />
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;
This works:
subprocess.call("python abc.py arg1 arg2", shell=True)
If Image folder location is public/assets/img/default.jpg.
You can try in view
<img src="{{ URL::to('/assets/img/default.jpg') }}">
Array operations like this is not jQuery's strongest point. You should consider a library such as Underscorejs, specifically the difference function.
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;
/
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.
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'
Based on this test (for-vs-forEach-vs-reduce) and this (loops)
I can say that:
var total = 0;
for (var i = 0, n = array.length; i < n; ++i)
{
total += array[i];
}
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 });
Then comes forEach
and reduce
which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.
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:
Go to 'Tools'
Hover your mouse over 'build system'. At the bottom of the list brought up, click 'New Build System...'
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.
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?
We have the following benefits of using IHttpActionResult
over HttpResponseMessage
:
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.async
and await
by default.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.
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:
jnettop is another candidate.
edit: it only shows the streams, not the owner processes.
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;
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?
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.
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.
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.
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
This worked for me on Safari 5 on Mac OSX, jQuery 1.4:
$("Selector")[elementIx].selectionStart = desiredStartPos;
$("Selector")[elementIx].selectionEnd = desiredEndPos;
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;
}
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.)