Programs & Examples On #Stereotype

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.

package com.ajinkya.th.controller;

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  @Controller
  public class HomePageController {

      @RequestMapping("/")
      public String homePage() {
        return "home";
      }

  }

Thats it ! Now restart your gradle server. ./gradlew bootRun

Spring CORS No 'Access-Control-Allow-Origin' header is present

We had the same issue and we resolved it using Spring's XML configuration as below:

Add this in your context xml file

<mvc:cors>
    <mvc:mapping path="/**"
        allowed-origins="*"
        allowed-headers="Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Authorization, X-Requested-With, requestId, Correlation-Id"
        allowed-methods="GET, PUT, POST, DELETE"/>
</mvc:cors>

Can't Autowire @Repository annotated interface in Spring Boot

It seems your @ComponentScan annotation is not set properly. Try :

@ComponentScan(basePackages = {"com.pharmacy"})

Actually you do not need the component scan if you have your main class at the top of the structure, for example directly under com.pharmacy package.

Also, you don't need both

@SpringBootApplication
@EnableAutoConfiguration

The @SpringBootApplication annotation includes @EnableAutoConfiguration by default.

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        @ResponseBody
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.

Eg:

ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);

@Autowired - No qualifying bean of type found for dependency at least 1 bean

Missing the 'implements' keyword in the impl classes might also be the issue

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

just add login password to connect to RabbitMq

 CachingConnectionFactory connectionFactory = 
         new CachingConnectionFactory("rabbit_host");

 connectionFactory.setUsername("login");
 connectionFactory.setPassword("password");

How to include js and CSS in JSP with spring MVC

you need declare resources in dispatcher servelet file.below is two declarations

<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**" />

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

In your xyz.DAOImpl.java

Do the following steps:

//Step-1: Set session factory

@Resource(name="sessionFactory")
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf)
{
    this.sessionFactory = sf;
}

//Step-2: Try to get the current session, and catch the HibernateException exception.


//Step-3: If there are any HibernateException exception, then true to get openSession.

try 
{
    //Step-2: Implementation
    session = sessionFactory.getCurrentSession();
} 
catch (HibernateException e) 
{
    //Step-3: Implementation
    session = sessionFactory.openSession();
}

Spring Boot application.properties value not populating

Actually, For me below works fine.

@Component
public class MyBean {

   public static String prop;

   @Value("${some.prop}")
   public void setProp(String prop) {
      this.prop= prop;
   }

   public MyBean() {

   }

   @PostConstruct
   public void init() {
      System.out.println("================== " + prop + "================== ");
   }

}

Now whereever i want, just invoke

MyBean.prop

it will return value.

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.

@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {

    @ApiObjectField(description = "The code which is to be verified.")
    @NotBlank(message = "mandatory")
    private final String code;

    @ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
    private final String maskedMobileNumber;

    public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
        this.code = code;
        this.maskedMobileNumber = maskedMobileNumber;
    }

    public String getcode() {
        return code;
    }

    public String getMaskedMobileNumber() {
        return maskedMobileNumber;
    }
}

The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been

public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
    this.code = code;
    this.maskedMobileNumber = maskedMobileNumber;
}

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I think this is related to the newer version of spring boot plus using spring data JPA just replace @Bean annotation above public LocalContainerEntityManagerFactoryBean entityManagerFactory() to @Bean(name="entityManagerFactory")

Determining the name of bean should solve the issue

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Exception clearly indicates the problem.

CompteDAOHib: No default constructor found

For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib.

Why does my Spring Boot App always shutdown immediately after starting?

With gradle, I replaced this line at build.gradle.kts file inside dependencies block

providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")

with this

compile("org.springframework.boot:spring-boot-starter-web")

and works fine.

How to write JUnit test with Spring Autowire?

A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
        "spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {

    @MockBean
    private PersonRepository repository;

    @Autowired
    private PersonService personService; // uses PersonRepository    

    @Test
    public void testSomething() {
        // using Mockito
        when(repository.findByName(any())).thenReturn(Collection.emptyList());
        Person person = new Person();
        person.setName(null);

        // when
        boolean found = personService.checkSomething(person);

        // then
        assertTrue(found, "Something is wrong");
    }
}

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".

Authorization Type options menu Authorization Inherit auth from parent selected

@Autowired - No qualifying bean of type found for dependency

  • One reason BeanB may not exist in the context
  • Another cause for the exception is the existence of two bean
  • Or definitions in the context bean that isn’t defined is requested by name from the Spring context

see more this url:

http://www.baeldung.com/spring-nosuchbeandefinitionexception

Spring MVC + JSON = 406 Not Acceptable

See the problem is with the extension. Depending upon the extension, spring could figure out the content-type. If your url ends with .com then it sends text/html as the content-type header. If you want to change this behavior of Spring, please use the below code:

@Configuration
@Import(HibernateConfig.class)
@EnableWebMvc
// @EnableAsync()
// @EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.azim.web.service.*",  basePackageClasses = { WebSecurityConfig.class }, excludeFilters = { @ComponentScan.Filter(Configuration.class) })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false)
                .defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
    }

    @Bean(name = "validator")
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }
}

Here, we are setting favorPathExtension to false and Default Content-type to Application/json. Note: HibernateConfig class contains all the beans.

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

This could also happens if you put a @PreAuthorize or @PostAuthorize in a Bean in creation. I would recommend to move such annotations to methods of interest.

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

Autowiring fails: Not an managed Type

You get the same exception when you pass the incorrect Entity object to the CrudRepository in the repository class.

public interface XYZRepository extends CrudRepository<IncorrectEntityClass, Long>

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

By reading your exception , It's sure that you forgot to autowire customerService

You should autowire your customerservice .

make following changes in your controller class

@Controller
public class CustomerController{

    @Autowired
    private Customerservice customerservice;
......other code......

}

Again your service implementation class

write

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDAO customerDAO;
......other code......

.....add transactional methods
}

If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).

you should autowire sessionFactory set method in your DAO mplementation

please find samle application context :

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.sparkle" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" /> -->

     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">         
        <list>
            <value>/WEB-INF/jdbc.properties</value>          

        </list>    
    </property>     
    </bean>




    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />


   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>


</beans>

note that i am using jdbc.properties file for jdbc url and driver specification

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

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

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Injection of autowired dependencies failed;

Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.

What's the difference between @Component, @Repository & @Service annotations in Spring?

The answers presented here are largely technically correct, but even though the response list is long and this will be at the bottom I thought it was worth putting an actually correct response in here too, just in case somebody stumbles upon it and learns something valuable from it. It's not that the rest of the answers are wrong, it's just that they aren't right. And, to stop the hordes of trolls, yes, I know that technically these annotations are effectively the same thing and most interchangeable even unto spring 5. Now, for the right answer:

These three annotations are completely different things and are not interchangeable. You can tell that because there are three of them rather than just one. They are not intended to be interchangeable, they're just implemented that way out of elegance and convenience.

Modern programming is invention, art, technique, and communication, in varying proportions. The communication bit is usually very important because code is usually read much more often than its written. As a programmer you're not only trying to solve the technical problem, you're also trying to communicate your intent to future programmers who read your code. These programmers may not share your native language, nor your social environment, and it is possible that they may be reading your code 50-years in the future (it's not as unlikely as you may think). It's difficult to communicate effectively that far into the future. Therefore, it is vital that we use the clearest, most efficient, correct, and communicative language available to us. That we chose our words carefully to have maximum impact and to be as clear as possible as to our intent.

For example, it is vital that @Repository is used when we're writing a repository, rather than @Component. The latter is a very poor choice of annotation for a repository because it does not indicate that we're looking at a repository. We can assume that a repository is also a spring-bean, but not that a component is a repository. With @Repository we are being clear and specific in our language. We are stating clearly that this is a repository. With @Component we are leaving it to the reader to decide what type of component they are reading, and they will have to read the whole class (and possibly a tree of subclasses and interfaces) to infer meaning. The class could then possibly be misinterpreted by a reader in the distant future as not being a repository, and we would have been partially responsible for this mistake because we, who knew full well that this is a repository, failed to be specific in our language and communicate effectively our intent.

I won't go into the other examples, but will state as clearly as I can: these annotations are completely different things and should be used appropriately, as per their intent. @Repository is for storage repositories and no other annotation is correct. @Service is for services and no other annotation is correct. @Component is for components that are neither repositories nor services, and to use either of these in its place would also be incorrect. It might compile, it might even run and pass your tests, but it would be wrong and I would think less of you (professionally) if you were to do this.

There are examples of this throughout spring (and programming in general). You must not use @Controller when writing a REST API, because @RestController is available. You must not use @RequestMapping when @GetMapping is a valid alternative. Etc. Etc. Etc. You must chose the most specific exact and correct language you can to communicate your intent to your readers, otherwise, you are introducing risks into your system, and risk has a cost.

How to get access to job parameters from ItemReader, in Spring Batch?

Complement with an additional example, you can access all job parameters in JavaConfig class:

@Bean
@StepScope
public ItemStreamReader<GenericMessage> reader(@Value("#{jobParameters}") Map<String,Object> jobParameters){
          ....
}

Infinite Recursion with Jackson JSON and Hibernate JPA issue

The point is to place the @JsonIgnore in the setter method as follow. in my case.

Township.java

@Access(AccessType.PROPERTY)
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="townshipId", nullable=false ,insertable=false, updatable=false)
public List<Village> getVillages() {
    return villages;
}

@JsonIgnore
@Access(AccessType.PROPERTY)
public void setVillages(List<Village> villages) {
    this.villages = villages;
}

Village.java

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "townshipId", insertable=false, updatable=false)
Township township;

@Column(name = "townshipId", nullable=false)
Long townshipId;

Neither BindingResult nor plain target object for bean name available as request attr

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

Find files in a folder using Java

Appache commons IO various

FilenameUtils.wildcardMatch

See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

In my case, there were two different 'AWS_SECRET_ACCESS_KEY' and 'AWS_ACCESS_KEY_ID' values set one through the Windows environment variable and one through the command line.

So, update these two and the default_region using a command line

> aws configure

Press enter and follow the steps to fill the correct AWS_ACESS_KEY_ID AWS_SECRET_ACCESS_KEY and AWS_DEFAULT_REGION

> aws sts get-caller-identity

should return the new set credentials

CSS /JS to prevent dragging of ghost image?

Try it:

img {
  pointer-events: none;
}

and try to avoid

* {
  pointer-events: none;
}

How to listen to the window scroll event in a VueJS component?

I know this is an old question, but I found a better solution with Vue.js 2.0+ Custom Directives: I needed to bind the scroll event too, then I implemented this.

First of, using @vue/cli, add the custom directive to src/main.js (before the Vue.js instance) or wherever you initiate it:

Vue.directive('scroll', {
  inserted: function(el, binding) {
    let f = function(evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f);
      }
    }
    window.addEventListener('scroll', f);
  }
});

Then, add the custom v-scroll directive to the element and/or the component you want to bind on. Of course you have to insert a dedicated method: I used handleScroll in my example.

<my-component v-scroll="handleScroll"></my-component>

Last, add your method to the component.

methods: {
  handleScroll: function() {
    // your logic here
  }
}

You don’t have to care about the Vue.js lifecycle anymore here, because the custom directive itself does.

Given URL is not allowed by the Application configuration Facebook application error

Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.

JavaScript hard refresh of current page

window.location.href = window.location.href

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

As few people shared to tick mark the checkbox for mysqli and mysqlind

but Hostgator (webhosting site) now does not give that option to select extension via the cpanel as that option is removed select PHP and now it gives the option for php manager

You can just select the Php version you want and not the extension.

Solution :- Called the hostgator , first time they said get in touch with your developer, ( i asked my brother and he downloaded the files locally and verified it was working fine on local system) <-- this was not needed though

Again called the hostgator and their backend team installed the missing extension and it was solved.

Below is the code which gives this error when it does not find the extension and you can find this line in load.php via ftp.

if ( ! extension_loaded( 'mysql' ) && ! extension_loaded( 'mysqli' ) && ! extension_loaded( 'mysqlnd' ) && ! file_exists( WP_CONTENT_DIR . '/db.php' ) ) {
    require_once ABSPATH . WPINC . '/functions.php';
    wp_load_translations_early();
    $args = array(
        'exit' => false,
        'code' => 'mysql_not_found',
    );
    wp_die(
        __( 'Your PHP installation appears to be missing the MySQL extension which is required by WordPress.' ),
        __( 'Requirements Not Met' ),
        $args
    );
    exit( 1 );
}

}

Vertically aligning a checkbox

<div>
    <input type="checkbox">
    <img src="/image.png" />
</div>
input[type="checkbox"]
{
    margin-top: -50%;
    vertical-align: middle;
}

Add a new line to the end of a JtextArea

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

This will add text on to the end of your JTextArea.

Another option would be to use getText() to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text) to set the text of the JTextArea to be the new String.

AngularJS Error: $injector:unpr Unknown Provider

When you are using ui-router, you should not use ng-controller anywhere. Your controllers are automatically instantiated for a ui-view when their appropriate states are activated.

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

Update maven version to 3.6.3 and run

mvn -Dhttps.protocols=TLSv1.2 install

it worked on centos 6.9

How can I upload fresh code at github?

It seems like Github has changed their layout since you posted this question. I just created a repository and it used to give you instructions on screen. It appears they have changed that approach.

Here is the information they used to give on repo creation:

Create A Repo · GitHub Help

How to display table data more clearly in oracle sqlplus

You can set the line size as per the width of the window and set wrap off using the following command.

set linesize 160;
set wrap off;

I have used 160 as per my preference you can set it to somewhere between 100 - 200 and setting wrap will not your data and it will display the data properly.

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

This will work:

DECLARE @MS INT = 235216
select cast(dateadd(ms, @MS, '00:00:00') AS TIME(3))

(where ms is just a number of seconds not a timeformat)

Add click event on div tag using javascript

Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.

try if you really want to use class:

 document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};

or you may assign function in html itself:

<div class="drill_cursor" onclick='alert("1");'>
</div>

How to install psycopg2 with "pip" on Python?

I could install it in a windows machine and using Anaconda/Spyder with python 2.7 through the following commands:

 !pip install psycopg2

Then to establish the connection to the database:

 import psycopg2
 conn = psycopg2.connect(dbname='dbname',host='host_name',port='port_number', user='user_name', password='password')

How exactly does the android:onClick XML attribute differ from setOnClickListener?

Specifying android:onClick attribute results in Button instance calling setOnClickListener internally. Hence there is absolutely no difference.

To have clear understanding, let us see how XML onClick attribute is handled by the framework.

When a layout file is inflated, all Views specified in it are instantiated. In this specific case, the Button instance is created using public Button (Context context, AttributeSet attrs, int defStyle) constructor. All of the attributes in the XML tag are read from the resource bundle and passed as AttributeSet to the constructor.

Button class is inherited from View class which results in View constructor being called, which takes care of setting the click call back handler via setOnClickListener.

The onClick attribute defined in attrs.xml, is referred in View.java as R.styleable.View_onClick.

Here is the code of View.java that does most of the work for you by calling setOnClickListener by itself.

 case R.styleable.View_onClick:
            if (context.isRestricted()) {
                throw new IllegalStateException("The android:onClick attribute cannot "
                        + "be used within a restricted context");
            }

            final String handlerName = a.getString(attr);
            if (handlerName != null) {
                setOnClickListener(new OnClickListener() {
                    private Method mHandler;

                    public void onClick(View v) {
                        if (mHandler == null) {
                            try {
                                mHandler = getContext().getClass().getMethod(handlerName,
                                        View.class);
                            } catch (NoSuchMethodException e) {
                                int id = getId();
                                String idText = id == NO_ID ? "" : " with id '"
                                        + getContext().getResources().getResourceEntryName(
                                            id) + "'";
                                throw new IllegalStateException("Could not find a method " +
                                        handlerName + "(View) in the activity "
                                        + getContext().getClass() + " for onClick handler"
                                        + " on view " + View.this.getClass() + idText, e);
                            }
                        }

                        try {
                            mHandler.invoke(getContext(), View.this);
                        } catch (IllegalAccessException e) {
                            throw new IllegalStateException("Could not execute non "
                                    + "public method of the activity", e);
                        } catch (InvocationTargetException e) {
                            throw new IllegalStateException("Could not execute "
                                    + "method of the activity", e);
                        }
                    }
                });
            }
            break;

As you can see, setOnClickListener is called to register the callback, as we do in our code. Only difference is it uses Java Reflection to invoke the callback method defined in our Activity.

Here are the reason for issues mentioned in other answers:

  • Callback method should be public : Since Java Class getMethod is used, only functions with public access specifier are searched for. Otherwise be ready to handle IllegalAccessException exception.
  • While using Button with onClick in Fragment, the callback should be defined in Activity : getContext().getClass().getMethod() call restricts the method search to the current context, which is Activity in case of Fragment. Hence method is searched within Activity class and not Fragment class.
  • Callback method should accept View parameter : Since Java Class getMethod searches for method which accepts View.class as parameter.

How to crop an image using C#?

If you're using AForge.NET:

using(var croppedBitmap = new Crop(new Rectangle(10, 10, 10, 10)).Apply(bitmap))
{
    // ...
}

What is WEB-INF used for in a Java EE web application?

There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.

Correct way to load a Nib for a UIView subclass

MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]

I'm using this to initialise the reusable custom views I have.


Note that you can use "firstObject" at the end there, it's a little cleaner. "firstObject" is a handy method for NSArray and NSMutableArray.

Here's a typical example, of loading a xib to use as a table header. In your file YourClass.m

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;
}

Normally, in the TopArea.xib, you would click on File Owner and set the file owner to YourClass. Then actually in YourClass.h you would have IBOutlet properties. In TopArea.xib, you can drag controls to those outlets.

Don't forget that in TopArea.xib, you may have to click on the View itself and drag that to some outlet, so you have control of it, if necessary. (A very worthwhile tip is that when you are doing this for table cell rows, you absolutely have to do that - you have to connect the view itself to the relevant property in your code.)

Skip rows during csv import pandas

skip[1] will skip second line, not the first one.

Display the binary representation of a number in C?

There is no direct format specifier for this in the C language. Although I wrote this quick python snippet to help you understand the process step by step to roll your own.

#!/usr/bin/python

dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""

while dec >= base:
    solution = str(dec%base) + solution
    dec = dec/base
if dec > 0:
    solution = str(dec) + solution

print solution

Explained:

dec = input("Enter a decimal number to convert: ") - prompt the user for numerical input (there are multiple ways to do this in C via scanf for example)

base = 2 - specify our base is 2 (binary)

solution = "" - create an empty string in which we will concatenate our solution

while dec >= base: - while our number is bigger than the base entered

solution = str(dec%base) + solution - get the modulus of the number to the base, and add it to the beginning of our string (we must add numbers right to left using division and remainder method). the str() function converts the result of the operation to a string. You cannot concatenate integers with strings in python without a type conversion.

dec = dec/base - divide the decimal number by the base in preperation to take the next modulo

if dec > 0: solution = str(dec) + solution - if anything is left over, add it to the beginning (this will be 1, if anything)

print solution - print the final number

Skip certain tables with mysqldump

Dump all databases with all tables but skip certain tables

on github: https://github.com/rubo77/mysql-backup.sh/blob/master/mysql-backup.sh

#!/bin/bash
# mysql-backup.sh

if [ -z "$1" ] ; then
  echo
  echo "ERROR: root password Parameter missing."
  exit
fi
DB_host=localhost
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
#MYSQL_CONN=""

BACKUP_DIR=/backup/mysql/

mkdir $BACKUP_DIR -p

MYSQLPATH=/var/lib/mysql/

IGNORE="database1.table1, database1.table2, database2.table1,"

# strpos $1 $2 [$3]
# strpos haystack needle [optional offset of an input string]
strpos()
{
    local str=${1}
    local offset=${3}
    if [ -n "${offset}" ]; then
        str=`substr "${str}" ${offset}`
    else
        offset=0
    fi
    str=${str/${2}*/}
    if [ "${#str}" -eq "${#1}" ]; then
        return 0
    fi
    echo $((${#str}+${offset}))
}

cd $MYSQLPATH
for i in */; do
    if [ $i != 'performance_schema/' ] ; then 
    DB=`basename "$i"` 
    #echo "backup $DB->$BACKUP_DIR$DB.sql.lzo"
    mysqlcheck "$DB" $MYSQL_CONN --silent --auto-repair >/tmp/tmp_grep_mysql-backup
    grep -E -B1 "note|warning|support|auto_increment|required|locks" /tmp/tmp_grep_mysql-backup>/tmp/tmp_grep_mysql-backup_not
    grep -v "$(cat /tmp/tmp_grep_mysql-backup_not)" /tmp/tmp_grep_mysql-backup

    tbl_count=0
    for t in $(mysql -NBA -h $DB_host $MYSQL_CONN -D $DB -e 'show tables') 
    do
      found=$(strpos "$IGNORE" "$DB"."$t,")
      if [ "$found" == "" ] ; then 
        echo "DUMPING TABLE: $DB.$t"
        mysqldump -h $DB_host $MYSQL_CONN $DB $t --events --skip-lock-tables | lzop -3 -f -o $BACKUP_DIR/$DB.$t.sql.lzo
        tbl_count=$(( tbl_count + 1 ))
      fi
    done
    echo "$tbl_count tables dumped from database '$DB' into dir=$BACKUP_DIR"
    fi
done

With a little help of https://stackoverflow.com/a/17016410/1069083

It uses lzop which is much faster, see:http://pokecraft.first-world.info/wiki/Quick_Benchmark:_Gzip_vs_Bzip2_vs_LZMA_vs_XZ_vs_LZ4_vs_LZO

No Spring WebApplicationInitializer types detected on classpath

xml was not in the WEB-INF folder, thats why i was getting this error, make sure that web.xml and xxx-servlet.xml is inside WEB_INF folder and not in the webapp folder .

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Mostly this is caused with an issue in your React/Client app. Adding this line to your client package.json solves it

"proxy": "http://localhost:5000/"

Note: Replace 5000, with the port number where your server is running

Reference: How to get create-react-app to work with a Node.js back-end API

Android difference between Two Dates

You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.

You can download class from here: DateTimeDifference GitHub Link

  • Simple to use
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago

Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
  • You can compare the example below
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
    Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
    Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}

How to use order by with union all in sql?

SELECT  * 
FROM 
        (
            SELECT * FROM TABLE_A 
            UNION ALL 
            SELECT * FROM TABLE_B
        ) dum
-- ORDER BY .....

but if you want to have all records from Table_A on the top of the result list, the you can add user define value which you can use for ordering,

SELECT  * 
FROM 
        (
            SELECT *, 1 sortby FROM TABLE_A 
            UNION ALL 
            SELECT *, 2 sortby FROM TABLE_B
        ) dum
ORDER   BY sortby 

How to make connection to Postgres via Node.js

Slonik is an alternative to answers proposed by Kuberchaun and Vitaly.

Slonik implements safe connection handling; you create a connection pool and connection opening/handling is handled for you.

import {
  createPool,
  sql
} from 'slonik';

const pool = createPool('postgres://user:password@host:port/database');

return pool.connect((connection) => {
  // You are now connected to the database.
  return connection.query(sql`SELECT foo()`);
})
  .then(() => {
    // You are no longer connected to the database.
  });

postgres://user:password@host:port/database is your connection string (or more canonically a connection URI or DSN).

The benefit of this approach is that your script ensures that you never accidentally leave hanging connections.

Other benefits for using Slonik include:

How to keep :active css style after clicking an element

The :target-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target

It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr

Here is a tab example with :target-pseudo selector.

How to set date format in HTML date input tag?

You don't.

Firstly, your question is ambiguous - do you mean the format in which it is displayed to the user, or the format in which it is transmitted to the web server?

If you mean the format in which it is displayed to the user, then this is down to the end-user interface, not anything you specify in the HTML. Usually, I would expect it to be based on the date format that it is set in the operating system locale settings. It makes no sense to try to override it with your own preferred format, as the format it displays in is (generally speaking) the correct one for the user's locale and the format that the user is used to writing/understanding dates in.

If you mean the format in which it's transmitted to the server, you're trying to fix the wrong problem. What you need to do is program the server-side code to accept dates in yyyy-mm-dd format.

How to count certain elements in array?

Modern JavaScript:

Note that you should always use triple equals === when doing comparison in JavaScript (JS). The triple equals makes sure, that JS comparison behaves like double equals == in other languages. The following solution shows how to solve this the functional way, which will never have out of bounds error:

// Let has local scope
let array = [1, 2, 3, 5, 2, 8, 9, 2]

// Functional filter with an Arrow function
array.filter(x => x === 2).length  // -> 3

The following anonymous Arrow function (lambda function) in JavaScript:

(x) => {
   const k = 2
   return k * x
}

may be simplified to this concise form for a single input:

x => 2 * x

where the return is implied.

jQuery - Detect value change on hidden input field

This example returns the draft field value every time the hidden draft field changes its value (chrome browser):

var h = document.querySelectorAll('input[type="hidden"][name="draft"]')[0];
//or jquery.....
//var h = $('input[type="hidden"][name="draft"]')[0];

observeDOM(h, 'n', function(draftValue){ 
  console.log('dom changed draftValue:'+draftValue);
});


var observeDOM = (function(){
var MutationObserver = window.MutationObserver || 
window.WebKitMutationObserver;

  return function(obj, thistime, callback){
    if(typeof obj === 'undefined'){
      console.log('obj is undefined');
      return;
    }

    if( MutationObserver ){

        // define a new observer
        var obs = new MutationObserver(function(mutations, observer){

            if( mutations[0].addedNodes.length || mutations[0].removedNodes.length ){

               callback('pass other observations back...');

            }else if(mutations[0].attributeName == "value" ){

               // use callback to pass back value of hidden form field                            
               callback( obj.value );

            }

        });

        // have the observer observe obj for changes in children
        // note 'attributes:true' else we can't read the input attribute value
        obs.observe( obj, { childList:true, subtree:true, attributes:true  });

       }
  };
})();

How to navigate a few folders up?

This is what worked best for me:

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));

Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end. Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.

How to enter in a Docker container already running with a new TTY

You should use Jérôme Petazzoni's tool called 'nsenter' to enter a container without using SSH. See: https://github.com/jpetazzo/nsenter

Install with simply running: docker run -v /usr/local/bin:/target jpetazzo/nsenter

Then use the command docker-enter <container-id> to enter the container.

Can you use a trailing comma in a JSON object?

Since a for-loop is used to iterate over an array, or similar iterable data structure, we can use the length of the array as shown,

awk -v header="FirstName,LastName,DOB" '
  BEGIN {
    FS = ",";
    print("[");
    columns = split(header, column_names, ",");
  }
  { print("  {");
    for (i = 1; i < columns; i++) {
      printf("    \"%s\":\"%s\",\n", column_names[i], $(i));
    }
    printf("    \"%s\":\"%s\"\n", column_names[i], $(i));
    print("  }");
  }
  END { print("]"); } ' datafile.txt

With datafile.txt containing,

 Angela,Baker,2010-05-23
 Betty,Crockett,1990-12-07
 David,Done,2003-10-31

Save array in mysql database

<?php
$myArray = new array('1', '2');
$seralizedArray = serialize($myArray);
?>

How to split a comma separated string and process in a loop using JavaScript

Please run below code may it helps you :)

_x000D_
_x000D_
var str = "this,is,an,example";_x000D_
var strArr = str.split(',');_x000D_
var data = "";_x000D_
for(var i=0; i<strArr.length; i++){_x000D_
  data += "Index : "+i+" value : "+strArr[i]+"<br/>";_x000D_
}_x000D_
document.getElementById('print').innerHTML = data;
_x000D_
<div id="print">_x000D_
</div>
_x000D_
_x000D_
_x000D_

UIAlertController custom font, size, color

Swift 5 and 5.1. Create a separate file and put UIAlertController Customization code there

import Foundation
import  UIKit

extension UIAlertController {

  //Set background color of UIAlertController
  func setBackgroudColor(color: UIColor) {
    if let bgView = self.view.subviews.first,
      let groupView = bgView.subviews.first,
      let contentView = groupView.subviews.first {
      contentView.backgroundColor = color
    }
  }

  //Set title font and title color
  func setTitle(font: UIFont?, color: UIColor?) {
    guard let title = self.title else { return }
    let attributeString = NSMutableAttributedString(string: title)//1
    if let titleFont = font {
      attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
        range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
        range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributeString, forKey: "attributedTitle")//4
  }

  //Set message font and message color
  func setMessage(font: UIFont?, color: UIColor?) {
    guard let title = self.message else {
      return
    }
    let attributedString = NSMutableAttributedString(string: title)
    if let titleFont = font {
      attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributedString, forKey: "attributedMessage")//4
  }

  //Set tint color of UIAlertController
  func setTint(color: UIColor) {
    self.view.tintColor = color
  }
}

Now On any action Show Alert

  func tapShowAlert(sender: UIButton) {
    let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
    // Change font and color of title
    alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
    // Change font and color of message
    alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
    // Change background color of UIAlertController
    alertController.setBackgroudColor(color: UIColor.black)
    let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
    let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(actnOk)
    alertController.addAction(actnCancel)
    self.present(alertController, animated: true, completion: nil)
  }

Result

enter image description here

How can one tell the version of React running at runtime in the browser?

From the command line:

npm view react version
npm view react-native version

Permanently Set Postgresql Schema Path

(And if you have no admin access to the server)

ALTER ROLE <your_login_role> SET search_path TO a,b,c;

Two important things to know about:

  1. When a schema name is not simple, it needs to be wrapped in double quotes.
  2. The order in which you set default schemas a, b, c matters, as it is also the order in which the schemas will be looked up for tables. So if you have the same table name in more than one schema among the defaults, there will be no ambiguity, the server will always use the table from the first schema you specified for your search_path.

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

If you install it directly with the community installer on windows 2008 server, it will reside on c:\ProgamData\MySql\MysqlServerVersion\my.ini

CentOS 64 bit bad ELF interpreter

Try

$ yum provides ld-linux.so.2
$ yum update
$ yum install glibc.i686 libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6

Hope this clears out.

CSS: fixed to bottom and centered

I ran into a problem where the typical position: fixed and bottom: 0 didn't work. Discovered a neat functionality with position: sticky. Note it's "relatively" new so it won't with IE/Edge 15 and earlier.

Here's an example for w3schools.

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
<style>
div.sticky {
  position: sticky;
  bottom: 0;
  background-color: yellow;
  padding: 30px;
  font-size: 20px;
}
</style>
</head>
<body>

<p>Lorem ipsum dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est,  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dlerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dlerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dlerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dlerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas  dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas </p>

<div class="sticky">I will stick to the screen when you reach my scroll position</div>

</body>
</html>
_x000D_
_x000D_
_x000D_

Good MapReduce examples

One of the best examples of Hadoop-like MapReduce implementation.

Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).

Read contents of a local file into a variable in Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

In your table dbo.Sup_Item_Cat, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.

If you have SQL Server Management Studio, open it up and sp_help 'dbo.Sup_Item_Cat'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.

Let me know if you need anything explained better!

Where do I call the BatchNormalization function in Keras?

Just to answer this question in a little more detail, and as Pavel said, Batch Normalization is just another layer, so you can use it as such to create your desired network architecture.

The general use case is to use BN between the linear and non-linear layers in your network, because it normalizes the input to your activation function, so that you're centered in the linear section of the activation function (such as Sigmoid). There's a small discussion of it here

In your case above, this might look like:


# import BatchNormalization
from keras.layers.normalization import BatchNormalization

# instantiate model
model = Sequential()

# we can think of this chunk as the input layer
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))

# we can think of this chunk as the hidden layer    
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))

# we can think of this chunk as the output layer
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('softmax'))

# setting up the optimization of our weights 
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)

# running the fitting
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose = 2)

Hope this clarifies things a bit more.

How to run a function when the page is loaded?

window.onload = codeAddress; should work - here's a demo, and the full code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <title>Test</title>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript">_x000D_
        function codeAddress() {_x000D_
            alert('ok');_x000D_
        }_x000D_
        window.onload = codeAddress;_x000D_
        </script>_x000D_
    </head>_x000D_
    <body>_x000D_
    _x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <title>Test</title>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript">_x000D_
        function codeAddress() {_x000D_
            alert('ok');_x000D_
        }_x000D_
        _x000D_
        </script>_x000D_
    </head>_x000D_
    <body onload="codeAddress();">_x000D_
    _x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

If you use windows authentication, and you don't know a password to login as a user via username and password, you can do this: on the login-screen on SSMS click options at the bottom right, then go to the connection properties tab. Then you can type in manually the name of another database you have access to, over where it says , which will let you connect. Then follow the other advice for changing your default database

https://gyazo.com/c3d04c600311c08cb685bb668b569a67

Unexpected end of file error

You did forget to include stdafx.h in your source (as I cannot see it your code). If you didn't, then make sure #include "stdafx.h" is the first line in your .cpp file, otherwise you will see the same error even if you've included "stdafx.h" in your source file (but not in the very beginning of the file).

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This is documented behavior. From ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME).

How do I combine 2 javascript variables into a string

warning! this does not work with links.

var variable = 'variable', another = 'another';

['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

How to JSON decode array elements in JavaScript?

JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.

You will then have a JavaScript datastructure that you can traverse for the data you need.

Set IDENTITY_INSERT ON is not working

Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.

to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx

Email and phone Number Validation in android

Try this

public class Validation {

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
        return false;
        } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    } 

    public static final boolean isValidPhoneNumber(CharSequence target) {
        if (target.length()!=10) {
            return false;
        } else {
            return android.util.Patterns.PHONE.matcher(target).matches();
        }
    }

}

Calling Oracle stored procedure from C#?

I have now got the steps needed to call procedure from C#

   //GIVE PROCEDURE NAME
   cmd = new OracleCommand("PROCEDURE_NAME", con);
   cmd.CommandType = CommandType.StoredProcedure;

   //ASSIGN PARAMETERS TO BE PASSED
   cmd.Parameters.Add("PARAM1",OracleDbType.Varchar2).Value = VAL1;
   cmd.Parameters.Add("PARAM2",OracleDbType.Varchar2).Value = VAL2;

   //THIS PARAMETER MAY BE USED TO RETURN RESULT OF PROCEDURE CALL
   cmd.Parameters.Add("vSUCCESS", OracleDbType.Varchar2, 1);
   cmd.Parameters["vSUCCESS"].Direction = ParameterDirection.Output;

   //USE THIS PARAMETER CASE CURSOR IS RETURNED FROM PROCEDURE
   cmd.Parameters.Add("vCHASSIS_RESULT",OracleDbType.RefCursor,ParameterDirection.InputOutput); 

   //CALL PROCEDURE
   con.Open();
   OracleDataAdapter da = new OracleDataAdapter(cmd);
   cmd.ExecuteNonQuery();

   //RETURN VALUE
   if (cmd.Parameters["vSUCCESS"].Value.ToString().Equals("T"))
   {
      //YOUR CODE
   }
   //OR
   //IN CASE CURSOR IS TO BE USED, STORE IT IN DATATABLE
   con.Open();
   OracleDataAdapter da = new OracleDataAdapter(cmd);
   da.Fill(dt);

Hope this helps

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I was finding the same error complaining about mixing google play services version when switching from 8.3 to 8.4. Bizarrely I saw reference to the app-measurement lib which I wasn't using.

I thought maybe one of my app's dependencies was referencing the older version so I ran ./gradlew app:dependencies to find the offending library (non were).

But at the top of task output I found a error message saying that the google plugin could not be found and defaulting to google play services 8.3. I used the sample project @TheYann linked to compare. My setup was identical except I applied the apply plugin: 'com.google.gms.google-services' at the top my app's build.gradle file. I moved to bottom of the file and that fixed the gradle compile error.

Find Nth occurrence of a character in a string

Here is a recursive implementation - as an extension method, mimicing the format of the framework method(s):

public static int IndexOfNth(
    this string input, string value, int startIndex, int nth)
{
    if (nth < 1)
        throw new NotSupportedException("Param 'nth' must be greater than 0!");
    if (nth == 1)
        return input.IndexOf(value, startIndex);

    return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
}

Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):

[Test]
public void TestIndexOfNthWorksForNth1()
{
    const string input = "foo<br />bar<br />baz<br />";
    Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1));
}

[Test]
public void TestIndexOfNthWorksForNth2()
{
    const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
    Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2));
}

[Test]
public void TestIndexOfNthWorksForNth3()
{
    const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
    Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3));
}

ALTER TABLE, set null in not null column, PostgreSQL 9.1

First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

Eloquent: find() and where() usage laravel

To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.

public $keyType = 'string'

Eloquent understands any of the types defined in the castAttribute() function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.

This will ensure that your primary key is correctly cast into the equivalent PHP data type.

JavaScript: how to change form action attribute value based on selection?

Simple and easy in javascipt

<script>

  document.getElementById("selectsearch").addEventListener("change", function(){

  var get_form =   document.getElementById("search-form") // get form 
  get_form.action =  '/search/' +  this.value; // assign value 

});

</script>

Displaying a message in iOS which has the same functionality as Toast in Android

For the ones that using Xamarin.IOS you can do like this:

new UIAlertView(null, message, null, "OK", null).Show();

using UIKit; is required.

How to remove the first and the last character of a string

use .replace(/.*\/(\S+)\//img,"$1")

"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

How to center a navigation bar with CSS or HTML?

#nav ul {
    display: inline-block;
    list-style-type: none;
}

It should work, I tested it in your site.

enter image description here

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

Python Socket Multiple Clients

#!/usr/bin/python
import sys
import os
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         
port = 50000

try:
    s.bind((socket.gethostname() , port))
except socket.error as msg:
    print(str(msg))
s.listen(10)
conn, addr = s.accept()  
print 'Got connection from'+addr[0]+':'+str(addr[1]))
while 1:
        msg = s.recv(1024)
        print +addr[0]+, ' >> ', msg
        msg = raw_input('SERVER >>'),host
        s.send(msg)
s.close()

How to free memory from char array in C

You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.

(It's the same as when you say int n = 10;: There are no dynamic resources involved that you have to manage manually.)

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

gitx How do I get my 'Detached HEAD' commits back into master

If your detached HEAD is a fast forward of master and you just want the commits upstream, you can

git push origin HEAD:master

to push directly, or

git checkout master && git merge [ref of HEAD]

will merge it back into your local master.

Resolving a Git conflict with binary files

I've come across two strategies for managing diff/merge of binary files with Git on windows.

  1. Tortoise git lets you configure diff/merge tools for different file types based on their file extensions. See 2.35.4.3. Diff/Merge Advanced Settings http://tortoisegit.org/docs/tortoisegit/tgit-dug-settings.html. This strategy of course relys on suitable diff/merge tools being available.

  2. Using git attributes you can specify a tool/command to convert your binary file to text and then let your default diff/merge tool do it's thing. See http://git-scm.com/book/it/v2/Customizing-Git-Git-Attributes. The article even gives an example of using meta data to diff images.

I got both strategies to work with binary files of software models, but we went with tortoise git as the configuration was easy.

$(form).ajaxSubmit is not a function

$(form).ajaxSubmit(); 

triggers another validation resulting to a recursion. try changing it to

form.ajaxSubmit(); 

Throw HttpResponseException or return Request.CreateErrorResponse?

Do not throw an HttpResponseException or return an HttpResponesMessage for errors - except if the intent is to end the request with that exact result.

HttpResponseException's are not handled the same as other exceptions. They are not caught in Exception Filters. They are not caught in the Exception Handler. They are a sly way to slip in an HttpResponseMessage while terminating the current code's execution flow.

Unless the code is infrastructure code relying on this special un-handling, avoid using the HttpResponseException type!

HttpResponseMessage's are not exceptions. They do not terminate the current code's execution flow. They can not be filtered as exceptions. They can not be logged as exceptions. They represent a valid result - even a 500 response is "a valid non-exception response"!


Make life simpler:

When there is an exceptional/error case, go ahead and throw a normal .NET exception - or a customized application exception type (not deriving from HttpResponseException) with desired 'http error/response' properties such as a status code - as per normal exception handling.

Use Exception Filters / Exception Handlers / Exception Loggers to do something appropriate with these exceptional cases: change/add status codes? add tracking identifiers? include stack traces? log?

By avoiding HttpResponseException the 'exceptional case' handling is made uniform and can be handled as part of the exposed pipeline! For example one can turn a 'NotFound' into a 404 and an 'ArgumentException' into a 400 and a 'NullReference' into a 500 easily and uniformly with application-level exceptions - while allowing extensibility to provide "basics" such as error logging.

.attr("disabled", "disabled") issue

To add disabled attribute

$('#id').attr("disabled", "true");

To remove Disabled Attribute

$('#id').removeAttr('disabled');

Editor does not contain a main type

File >> Import >> Existing Projects into Workspace >> Select Archive Filed >> Browse and locate file >> Finish. If its already imported some other way delete it and try it that way. I was having the same problem until i tried that.

Permanently hide Navigation Bar in an activity

Change the theme in your manifest.

If you want to hide nav bar for one activity you can use this:

<activity
        android:name="Activity Name"
        android:theme="@android:style/Theme.Black.NoTitleBar"
        android:label="@string/app_name" >

If you want to hide nav bar for entire application you can use this:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar" >

day of the week to day number (Monday = 1, Tuesday = 2)

$day_of_week = date('N', strtotime('Monday'));

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

look at the my.cnf file, if there contain [client] section, and the port is other than real listen port (default 3306), you must connect the server with explicit parameter -P 3306, e.g.

mysql -u root -h 127.0.0.1 -p -P 3306

LinearLayout not expanding inside a ScrollView

The solution is to use

android:fillViewport="true"

on Scroll view and moreover try to use

"wrap_content" instead of "fill_parent" as "fill_parent"

is deprecated now.

Center form submit buttons HTML / CSS

<style>
form div {
    width: 400px;   
    border: 1px solid black;
} 

form input[type='submit']  {
    display: inline-block;
    width: 70px;
}

div.submitWrapper  {
   text-align: center;    
}    
</style>
<form>

<div class='submitWrapper'>    
<input type='submit' name='submit' value='Submit'> 
 </div>

Also Check this jsfiddle

Create web service proxy in Visual Studio from a WSDL file

Try the WSDL To Proxy class tool shipped with the .NET Framework SDK. I've never used it before, but it certainly looks like what you need.

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

Put byte array to JSON and vice versa

In line with @Qwertie's suggestion, but going further on the lazy side, you could just pretend that each byte is a ISO-8859-1 character. For the uninitiated, ISO-8859-1 is a single-byte encoding that matches the first 256 code points of Unicode.

So @Ash's answer is actually redeemable with a charset:

byte[] args2 = getByteArry();
String byteStr = new String(args2, Charset.forName("ISO-8859-1"));

This encoding has the same readability as BAIS, with the advantage that it is processed faster than either BAIS or base64 as less branching is required. It might look like the JSON parser is doing a bit more, but it's fine because dealing with non-ASCII by escaping or by UTF-8 is part of a JSON parser's job anyways. It could map better to some formats like MessagePack with a profile.

Space-wise however, it is usually a loss, as nobody would be using UTF-16 for JSON. With UTF-8 each non-ASCII byte would occupy 2 bytes, while BAIS uses (2+4n + r?(r+1):0) bytes for every run of 3n+r such bytes (r is the remainder).

Difference between return 1, return 0, return -1 and exit?

As explained here, in the context of main both return and exit do the same thing

Q: Why do we need to return or exit?

A: To indicate execution status.

In your example even if you didnt have return or exit statements the code would run fine (Assuming everything else is syntactically,etc-ally correct. Also, if (and it should be) main returns int you need that return 0 at the end).

But, after execution you don't have a way to find out if your code worked as expected. You can use the return code of the program (In *nix environments , using $?) which gives you the code (as set by exit or return) . Since you set these codes yourself you understand at which point the code reached before terminating.

You can write return 123 where 123 indicates success in the post execution checks.

Usually, in *nix environments 0 is taken as success and non-zero codes as failures.

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

Had suddenly the same Problem, from one day to another eclipse said

Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`.

after trying to run java on the console

Error: could not open `C:\WINDOWS\jre\lib\amd64\jvm.cfg' 

now i just deleted the whole directory

C:\WINDOWS\jre

and everything worked again... i don't know there this jre came from, i hope it was not a virus

Simple way to sort strings in the (case sensitive) alphabetical order

I recently answered a similar question here. Applying the same approach to your problem would yield following solution:

list.sort(
  p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
    public P2<String, String> f(String s) {
      return p(s.toLowerCase(), s);
    }
  })
);

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

using BETWEEN in WHERE condition

$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');

this is my solution

DataGrid get selected rows' column values

If you are using an SQL query to populate your DataGrid you can do this :

Datagrid fill

Private Sub UserControl_Loaded(sender As Object, e As RoutedEventArgs)
        Dim cmd As SqlCommand
        Dim da As SqlDataAdapter
        Dim dt As DataTable

        cmd = New SqlCommand With {
            .CommandText = "SELECT * FROM temp_rech_dossier_route",
            .Connection = connSQLServer
        }
        da = New SqlDataAdapter(cmd)
        dt = New DataTable("RECH")
        da.Fill(dt)
        DataGridRech.ItemsSource = dt.DefaultView
End Sub

Value diplay

    Private Sub DataGridRech_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles DataGridRech.SelectionChanged
        Dim val As DataRowView
        val = CType(DataGridRech.SelectedItem, DataRowView)
        Console.WriteLine(val.Row.Item("num_dos"))
    End Sub

I know it's in VB.Net but it can be translated into C#. I put this solution here, it might be useful for someone.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Adding this to project's gradle.properties fixed it for us:

android.enableJetifier=true
android.useAndroidX=true

How to increase request timeout in IIS?

To Increase request time out add this to web.config

<system.web>
    <httpRuntime executionTimeout="180" />
</system.web>

and for a specific page add this

<location path="somefile.aspx">
    <system.web>
        <httpRuntime executionTimeout="180"/>
    </system.web>
</location>

The default is 90 seconds for .NET 1.x.

The default 110 seconds for .NET 2.0 and later.

Combining two sorted lists in Python

This is my solution in linear time without editing l1 and l2:

def merge(l1, l2):
  m, m2 = len(l1), len(l2)
  newList = []
  l, r = 0, 0
  while l < m and r < m2:
    if l1[l] < l2[r]:
      newList.append(l1[l])
      l += 1
    else:
      newList.append(l2[r])
      r += 1
  return newList + l1[l:] + l2[r:]

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

Adjust icon size of Floating action button (fab)

You can play with the following settings of FloatingActionButton : android:scaleType and app:maxImageSize. As for me, I've got a desirable result if android:scaleType="centerInside" and app:maxImageSize="56dp".

android: how to align image in the horizontal center of an imageview?

Try this code :

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/imgBusiness"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/back_detail" />
</LinearLayout>

How to use jQuery to show/hide divs based on radio button selection?

An interesting solution is to make this declarative: you just give every div that should be shown an attribute automaticallyVisibleIfIdChecked with the id of the checkbox or radio button on which it depends. That is, your form looks like this:

<form name="form1" id="my_form" method="post" action="">
    <div><label><input type="radio" name="group1" id="rdio1" value="opt1">opt1</label></div>  
    <div><label><input type="radio" name="group1" id="rdio2" value="opt2">opt2</label></div>  
</form>
....
<div id="opt1" automaticallyVisibleIfIdChecked="rdio1">lorem ipsum dolor</div>
<div id="opt2" automaticallyVisibleIfIdChecked="rdio2">consectetur adipisicing</div>

and have some page independent JavaScript that nicely uses functional programming:

function executeAutomaticVisibility(name) {
    $("[name="+name+"]:checked").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").show();
    });
    $("[name="+name+"]:not(:checked)").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").hide();
    });
}

$(document).ready( function() {
    triggers = $("[automaticallyVisibleIfIdChecked]")
        .map(function(){ return $("#" + $(this).attr("automaticallyVisibleIfIdChecked")).get() })
    $.unique(triggers);
    triggers.each( function() {
        executeAutomaticVisibility(this.name);
        $(this).change( function(){ executeAutomaticVisibility(this.name); } );
    });
});

Similarily you could automatically enable / disable form fields with an attribute automaticallyEnabledIfChecked.

I think this method is nice since it avoids having to create specific JavaScript for your page - you just insert some attributes that say what should be done.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

The cause isn't contrary to syntax rather than inappropriate usage of objects. Life Cycle of objects in ViewData, ViewBag, & View Life Cycle is shorter than in the session. Data defined in the formers will be lost after a request-response(if try to access after a request-response, you will get exceptions). So the formers are appropriate for passing data between View & Controller while the latter for storing temporary data. The temporary data should store in the session so that can be accessed many times.

How to add an image to an svg container using D3.js

 var svg = d3.select("body")
        .append("svg")
        .style("width", 200)
        .style("height", 100)

Can't specify the 'async' modifier on the 'Main' method of a console app

class Program
{
     public static EventHandler AsyncHandler;
     static void Main(string[] args)
     {
        AsyncHandler+= async (sender, eventArgs) => { await AsyncMain(); };
        AsyncHandler?.Invoke(null, null);
     }

     private async Task AsyncMain()
     {
        //Your Async Code
     }
}

IntelliJ: Never use wildcard imports

This applies to "IntelliJ IDEA-2019.2.4" on Mac.

  1. Navigate to "IntelliJ IDEA->Preferences->Editor->Code Style->Kotlin".
  2. The "Packages to use Import with '' section on the screen will list "import java.util."

Before

  1. Click anywhere in that box and clear that entry.
  2. Hit Apply and OK.

After

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).

What is the difference between static_cast<> and C style casting?

C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime.

Also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts.

Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.

When writing C++ I'd pretty much always use the C++ ones over the the C style.

How to create virtual column using MySQL SELECT?

Your syntax would create an alias for a as b, but it wouldn't have scope beyond the results of the statement. It sounds like you may want to create a VIEW

Converting Pandas dataframe into Spark dataframe error

Type related errors can be avoided by imposing a schema as follows:

note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").

import pyspark
from pyspark.sql import SparkSession
import pandas as pd

spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()

pdDF = pd.read_csv("test.csv")

contents of the pandas data frame:

       col1     col2    col3    col4    col5    col6    col7    col8   ... 
0      10000001 1       0       1       12:35   OK      10002   1      ...
1      10000001 2       0       1       12:36   OK      10002   1      ...
2      10000002 1       0       4       12:19   PA      10003   1      ...

Next, create the schema:

from pyspark.sql.types import *

mySchema = StructType([ StructField("col1", LongType(), True)\
                       ,StructField("col2", IntegerType(), True)\
                       ,StructField("col3", IntegerType(), True)\
                       ,StructField("col4", IntegerType(), True)\
                       ,StructField("col5", StringType(), True)\
                       ,StructField("col6", StringType(), True)\
                       ,StructField("col7", IntegerType(), True)\
                       ,StructField("col8", IntegerType(), True)\
                       ,StructField("col9", IntegerType(), True)\
                       ,StructField("col10", IntegerType(), True)\
                       ,StructField("col11", StringType(), True)\
                       ,StructField("col12", StringType(), True)\
                       ,StructField("col13", IntegerType(), True)\
                       ,StructField("col14", IntegerType(), True)\
                       ,StructField("col15", IntegerType(), True)\
                       ,StructField("col16", IntegerType(), True)\
                       ,StructField("col17", IntegerType(), True)\
                       ,StructField("col18", IntegerType(), True)\
                       ,StructField("col19", IntegerType(), True)\
                       ,StructField("col20", IntegerType(), True)\
                       ,StructField("col21", IntegerType(), True)\
                       ,StructField("col22", IntegerType(), True)\
                       ,StructField("col23", IntegerType(), True)\
                       ,StructField("col24", IntegerType(), True)\
                       ,StructField("col25", IntegerType(), True)])

Note: True (implies nullable allowed)

create the pyspark dataframe:

df = spark.createDataFrame(pdDF,schema=mySchema)

confirm the pandas data frame is now a pyspark data frame:

type(df)

output:

pyspark.sql.dataframe.DataFrame

Aside:

To address Kate's comment below - to impose a general (String) schema you can do the following:

df=spark.createDataFrame(pdDF.astype(str)) 

Configuring angularjs with eclipse IDE

Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.

Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development

How to convert a PIL Image into a numpy array?

You're not saying how exactly putdata() is not behaving. I'm assuming you're doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).

Why is AJAX returning HTTP status code 0?

Status code 0 means the requested url is not reachable. By changing http://something/something to https://something/something worked for me. IE throwns an error saying "permission denied" when the status code is 0, other browsers dont.

what is the multicast doing on 224.0.0.251?

Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.

The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.

mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.

If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.

Field 'id' doesn't have a default value?

This is caused by MySQL having a strict mode set which won’t allow INSERT or UPDATE commands with empty fields where the schema doesn’t have a default value set.

There are a couple of fixes for this.

First ‘fix’ is to assign a default value to your schema. This can be done with a simple ALTER command:

ALTER TABLE `details` CHANGE COLUMN `delivery_address_id` `delivery_address_id` INT(11) NOT NULL DEFAULT 0 ;

However, this may need doing for many tables in your database schema which will become tedious very quickly. The second fix is to remove sql_mode STRICT_TRANS_TABLES on the mysql server.

If you are using a brew installed MySQL you should edit the my.cnf file in the MySQL directory. Change the sql_mode at the bottom:

#sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
sql_mode=NO_ENGINE_SUBSTITUTION

Save the file and restart Mysql.

Source: https://www.euperia.com/development/mysql-fix-field-doesnt-default-value/1509

Get filename from input [type='file'] using jQuery

Getting the file name is fairly easy. As matsko points out, you cannot get the full file path on the user's computer for security reasons.

var file = $('#image_file')[0].files[0]
if (file){
  console.log(file.name);
}

Is there a "goto" statement in bash?

A simple searchable goto for the use of commenting out code blocks when debugging.

GOTO=false
if ${GOTO}; then
    echo "GOTO failed"
    ...
fi # End of GOTO
echo "GOTO done"

Result is-> GOTO done

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

What is the size limit of a post request?

You can post large amount of data by setting php.ini variable: max_input_vars Default size of this variable is 1000 but if you want to sent large amount of data you have to increase the size accordingly. If you can't set the size from ini_set you have to do it through htaccess or by doing changes into php.ini file directly.

max_input_vars  2500
memory_limit    256M

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

Well, I'm not sure that merge would be the way to go. Personally I would build a new data frame by creating an index of the dates and then constructing the columns using list comprehensions. Possibly not the most pythonic way, but it seems to work for me!

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )

# Create an index list from the set of dates in both data frames
Index = list(set(list(df1.index) + list(df2.index)))
Index.sort()

df3 = pd.DataFrame({'df1': [df1.loc[Date, 'c'] if Date in df1.index else np.nan for Date in Index],\
                'df2': [df2.loc[Date, 'c'] if Date in df2.index else np.nan for Date in Index],},\
                index = Index)

df3

What is the difference between "screen" and "only screen" in media queries?

The answer by @hybrid is quite informative, except it doesn't explain the purpose as mentioned by @ashitaka "What if you use the Mobile First approach? So, we have the mobile CSS first and then use min-width to target larger sites. We shouldn't use the only keyword in that context, right? "

Want to add in here that the purpose is simply to prevent non supporting browsers to use that Other device style as if it starts from "screen" without it will take it for a screen whereas if it starts from "only" style will be ignored.

Answering to ashitaka consider this example

<link rel="stylesheet" type="text/css" 
  href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css" 
  href="desktop.css" media="screen and (min-width: 481px)" />

If we don't use "only" it will still work as desktop-style will also be used striking android styles but with unnecessary overhead. In this case, IF a browser is non-supporting it will fallback to the second Style-sheet ignoring the first.

What is the difference between AF_INET and PF_INET in socket programming?

AF_INET = Address Format, Internet = IP Addresses

PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP

AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part sticking with AF_INET for socket programming over a network is the safest option.

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.

PF_INET refers to anything in the protocol, usually sockets/ports.

Difference between readFile() and readFileSync()

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

     <asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
                                                                    FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
                                                                    <ItemTemplate>
                                                                        <asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
                                                                            Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
                                                                    </ItemTemplate>
                                                                    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                                                                    <ItemStyle HorizontalAlign="Center" Width="50px" />
                                                                    <FooterTemplate>
                                                                        <asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
                                                                    </FooterTemplate>
                                                                </asp:TemplateField>


 private void TotalExEmpOFMonth()
    {
        Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
        /*Sum of the  Total Amount Of month*/
        foreach (GridViewRow gvr in GrdPFRecord.Rows)
        {
            TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
            lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
            lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));



        }
    }

Unable to compile class for JSP

Try adding this to your web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/your-servlet-name.xml
    </param-value>

How to search for file names in Visual Studio?

CTRL + P this searches for the file name your direct answer.

How/When does Execute Shell mark a build as failure in Jenkins?

Plain and simple:

If Jenkins sees the build step (which is a script too) exits with non-zero code, the build is marked with a red ball (= failed).

Why exactly that happens depends on your build script.

I wrote something similar from another point-of-view but maybe it will help to read it anyway: Why does Jenkins think my build succeeded?

Submitting HTML form using Jquery AJAX

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

Overlay a background-image with an rgba background-color

I've gotten the following to work:

html {
  background:
      linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
      url('bgimage.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

The above will produce a nice opaque blue overlay.

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

How can I present a file for download from an MVC controller?

You can do the same in Razor or in the Controller, like so..

@{
    //do this on the top most of your View, immediately after `using` statement
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}

Or in the Controller..

public ActionResult Receipt() {
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");

    return View();
}

I tried this in Chrome and IE9, both is downloading the pdf file.

I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF

How to convert seconds to time format?

Use modulo:

$hours = $time_in_seconds / 3600;
$minutes = ($time_in_seconds / 60) % 60;

Magento - How to add/remove links on my account navigation?

My solution was to completely remove the block in local.xml and create it with the blocks I needed, so, for example

<customer_account>
        <reference name="left">
            <action method="unsetChild">
                <name>customer_account_navigation</name>
            </action>
            <block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
                <action method="addLink" translate="label" module="customer">
                    <name>account</name>
                    <path>customer/account/</path>
                    <label>Account Dashboard</label>
                </action>
                <action method="addLink" translate="label" module="customer">
                    <name>account_edit</name>
                    <path>customer/account/edit/</path>
                    <label>Account Information</label>
                </action>
        </block>
    </reference>
</customer_account>

Show "loading" animation on button click

try

$("#btnId").click(function(e){
 e.preventDefault();
 //show loading gif

 $.ajax({
  ...
  success:function(data){
   //remove gif
  },
  error:function(){//remove gif}

 });
});

EDIT: after reading the comments

in case you decide against ajax

$("#btnId").click(function(e){
     e.preventDefault();
     //show loading gif
     $(this).closest('form').submit();
});

How to list all the files in android phone by using adb shell?

This command will show also if the file is hidden adb shell ls -laR | grep filename

Make child visible outside an overflow:hidden parent

Neither of the posted answers worked for me. Setting position: absolute for the child element did work however.

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

Maven Out of Memory Build Failure

What type of OS are you running on?

In order to assign more than 2GB of ram it needs to be at least a 64bit OS.

Then there is another problem. Even if your OS has Unlimited RAM, but that is fragmented in a way that not a single free block of 2GB is available, you'll get out of memory exceptions too. And keep in mind that the normal Heap memory is only part of the memory the VM process is using. So on a 32bit machine you will probably never be able to set Xmx to 2048MB.

I would also suggest to set min an max memory to the same value, because in this case as soon as the VM runs out of memory the frist time 1GB is allocated from the start, the VM then allocates a new block (assuming it increases with 500MB blocks) of 1,5GB after that is allocated, it would copy all the stuff from block one to the new one and free Memory after that. If it runs out of Memory again the 2GB are allocated and the 1,5 GB are then copied, temporarily allocating 3,5GB of memory.

Unzip files (7-zip) via cmd command

make sure that your path is pointing to .exe file in C:\Program Files\7-Zip (may in bin directory)

Simplest SOAP example

This is the simplest JavaScript SOAP Client I can create.

<html>
<head>
    <title>SOAP JavaScript Client Test</title>
    <script type="text/javascript">
        function soap() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', 'https://somesoapurl.com/', true);

            // build SOAP request
            var sr =
                '<?xml version="1.0" encoding="utf-8"?>' +
                '<soapenv:Envelope ' + 
                    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
                    'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
                    'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
                    'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
                    '<soapenv:Body>' +
                        '<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
                            '<username xsi:type="xsd:string">login_username</username>' +
                            '<password xsi:type="xsd:string">password</password>' +
                        '</api:some_api_call>' +
                    '</soapenv:Body>' +
                '</soapenv:Envelope>';

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        alert(xmlhttp.responseText);
                        // alert('done. use firebug/console to see network response');
                    }
                }
            }
            // Send the POST request
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            xmlhttp.send(sr);
            // send request
            // ...
        }
    </script>
</head>
<body>
    <form name="Demo" action="" method="post">
        <div>
            <input type="button" value="Soap" onclick="soap();" />
        </div>
    </form>
</body>
</html> <!-- typo -->

Get user's non-truncated Active Directory groups from command line

Based on answer by P.Brian.Mackey-- I tried using gpresult /user <UserName> /r command, but it only seemed to work for my user account; for other users accounts I got this result: The user "userNameHere" does not have RSOP data.

So I read through this blog-- https://blog.thesysadmins.co.uk/group-policy-gpresult-examples.html-- and came upon a solution. You have to know the users computer name:

gpresult /s <UserComputer> /r /user:<UserName>

After running the command, you have to ENTER a few times for the program to complete because it will pause in the middle of the ouput. Also, the results gave a bunch of data including a section for "COMPUTER SETTINGS> Applied Group Policy Objects" and then "COMPUTER SETTINGS> Security groups" and finally "USER SETTINGS> security groups" (this is what we are looking for with the AD groups listed with non-truncated descriptions!).

Interesting to note that GPRESULT had some extra members not seen in NET USER command. Also, the sort order does not match and is not alphabetical. Any body who can add more insights in the comments that would be great.

RESULTS: gpresult (with ComputerName, UserName)

For security reasons, I have included only a subset of the membership results. (36 TOTAL, 12 SAMPLE)

The user is a part of the following security groups
---------------------------------------------------
..
 Internet Email 
 GEVStandardPSMViewers  
 GcoFieldServicesEditors    
 AnimalWelfare_Readers  
 Business Objects   
 Zscaler_Standard_Access    
..
 GCM    
..
 GcmSharesEditors   
 GHVStandardPSMViewers  
 IntranetReportsViewers 
 JetDWUsers     -- (NOTE: this one was deleted today, the other "Jet" one was added)
..
 Time and Attendance Users  
..

RESULTS: net user /DOMAIN (with UserName)

For security reasons, I have included only a subset of the membership results. (23 TOTAL, 12 SAMPLE)

Local Group Memberships  
Global Group memberships    ...
                             *Internet Email       *GEVStandardPSMViewers
                             *GcoFieldServicesEdito*AnimalWelfare_Readers
                             *Business Objects     *Zscaler_Standard_Acce
                             ...
                             *Time and Attendance U*GCM
                             ...
                             *GcmSharesEditors     *GHVStandardPSMViewers
                             *IntranetReportsViewer*JetPowerUsers
The command completed successfully.

Rotating and spacing axis labels in ggplot2

I'd like to provide an alternate solution, a robust solution similar to what I am about to propose was required in the latest version of ggtern, since introducing the canvas rotation feature.

Basically, you need to determine the relative positions using trigonometry, by building a function which returns an element_text object, given angle (ie degrees) and positioning (ie one of x,y,top or right) information.

#Load Required Libraries
library(ggplot2)
library(gridExtra)

#Build Function to Return Element Text Object
rotatedAxisElementText = function(angle,position='x'){
  angle     = angle[1]; 
  position  = position[1]
  positions = list(x=0,y=90,top=180,right=270)
  if(!position %in% names(positions))
    stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")),call.=FALSE)
  if(!is.numeric(angle))
    stop("'angle' must be numeric",call.=FALSE)
  rads  = (angle - positions[[ position ]])*pi/180
  hjust = 0.5*(1 - sin(rads))
  vjust = 0.5*(1 + cos(rads))
  element_text(angle=angle,vjust=vjust,hjust=hjust)
}

Frankly, in my opinion, I think that an 'auto' option should be made available in ggplot2 for the hjust and vjust arguments, when specifying the angle, anyway, lets demonstrate how the above works.

#Demonstrate Usage for a Variety of Rotations
df    = data.frame(x=0.5,y=0.5)
plots = lapply(seq(0,90,length.out=4),function(a){
  ggplot(df,aes(x,y)) + 
    geom_point() + 
    theme(axis.text.x = rotatedAxisElementText(a,'x'),
          axis.text.y = rotatedAxisElementText(a,'y')) +
    labs(title = sprintf("Rotated %s",a))
})
grid.arrange(grobs=plots)

Which produces the following:

Example

How to position two elements side by side using CSS

you can simple use some div to make a container and the display: flex; to make the content appear side-by-side like this:

CSS

.splitscreen {
    display:flex;
}
.splitscreen .left {
    flex: 1;
}
.splitscreen .right {
    flex: 1;
}

HTML

<div class="splitscreen">
    <div class="left">
        <!-- content -->
    </div>

    <div class="right">
        <!-- content -->
    </div>
</div>

using flex you say who will use more space on the screen.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Format bytes to kilobytes, megabytes, gigabytes

Simple function

function formatBytes($size, $precision = 0){
    $unit = ['Byte','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];

    for($i = 0; $size >= 1024 && $i < count($unit)-1; $i++){
        $size /= 1024;
    }

    return round($size, $precision).' '.$unit[$i];
}

echo formatBytes('1876144', 2);
//returns 1.79 MiB

How to save username and password in Git?

Just put your credentials in the Url like this:

https://Username:Password@github.com/myRepoDir/myRepo.git

You may store it like this:

git remote add myrepo https://Userna...

...example to use it:

git push myrepo master


Now that is to List the url aliases:

git remote -v

...and that the command to delete one of them:

git remote rm myrepo

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Experienced this issue on new Windows 10 machine on VS2015 with an existing project. Package Manager 3.4.4. Restore packages enabled.

The restore doesn't seem to work completely. Had to run the following on the Package Manager Command line

Update-Package -ProjectName "YourProjectName" -Id Microsoft.Web.Infrastructure -Reinstall

This made the following changes to my solution file which the restore did NOT do.

<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
  <Private>True</Private>
</Reference>

Just adding the above elements to the ItemGroup section in you solution file will ALSO solve the issue provided that ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll exist.

Easier to just do the -Reinstall but good to understand what it does differently to the package restore.

Initialising mock objects - MockIto

MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:

XXX mockedXxx = mock(XXX.class);

I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

If the keystore is for tomcat then, after creating the keystore with the above answers, you must add a final step to create the "tomcat" alias for the key:

keytool -changealias -alias "1" -destalias "tomcat" -keystore keystore-file.jks

You can check the result with:

keytool -list -keystore keystore-file.jks -v

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

Array(100).fill().map((_,i)=> console.log(i) );

This version satisifies the OP's requirement for immutability. Also consider using reduce instead of map depending on your use case.

This is also an option if you don't mind a little mutation in your prototype.

Number.prototype.times = function(f) {
   return Array(this.valueOf()).fill().map((_,i)=>f(i));
};

Now we can do this

((3).times(i=>console.log(i)));

+1 to arcseldon for the .fill suggestion.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

The code below resolved the issue

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3

What's the use of "enum" in Java?

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Here is some code that shows you how to use the Day enum defined above:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;

            case FRIDAY:
                System.out.println("Fridays are better.");
                break;

            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;

            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}

The output is:

Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
}

In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

If you run Planet.class from the command line with an argument of 175, you get this output:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

Source: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Catch checked change event of a checkbox

For JQuery 1.7+ use:

$('input[type=checkbox]').on('change', function() {
  ...
});

regular expression for Indian mobile numbers

"^((0091)|(\+91)|0?)[789]{1}\d{9}$";

Is also a valid expression. You can precede it with either 0091,+91 or 0 and is optional.

For more details with code sample, refer to my blog.

How to get the text of the selected value of a dropdown list?

Hi if you are having dropdownlist like this

<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">

after giving id to dropdownlist you just need to add jquery code like this

function getHTML()
{
      var display=$('#testID option:selected').html();
      alert(display);
}

Can I remove the URL from my print css, so the web address doesn't print?

Remove the url from header and footer using below method

 @page { size: letter;  margin-top: 4mm;margin-bottom: 4mm }

How to insert a large block of HTML in JavaScript?

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

How to check for the type of a template parameter?

In C++17, we can use variants.

To use std::variant, you need to include the header:

#include <variant>

After that, you may add std::variant in your code like this:

using Type = std::variant<Animal, Person>;

template <class T>
void foo(Type type) {
    if (std::is_same_v<type, Animal>) {
        // Do stuff...
    } else {
        // Do stuff...
    }
}

Convert integer to hex and hex to integer

It is possible using the function FORMAT available on SQL Server 2012 and above

select FORMAT(10,'x2')

Results in:

0a

How to make Java honor the DNS Caching Timeout?

To summarize the other answers, in <jre-path>/lib/security/java.security you can set the value of the property networkaddress.cache.ttl to adjust how DNS lookups are cached. Note that this is not a system property but a security property. I was able to set this using:

java.security.Security.setProperty("networkaddress.cache.ttl", "<value>");

This can also be set by the system property -Dsun.net.inetaddr.ttl though this will not override a security property if it is set elsewhere.

I would also like to add that if you are seeing this issue with web services in WebSphere, as I was, setting networkaddress.cache.ttl will not be enough. You need to set the system property disableWSAddressCaching to true. Unlike the time-to-live property, this can be set as a JVM argument or via System.setProperty).

IBM has a pretty detailed post on how WebSphere handles DNS caching here. The relevant piece to the above is:

To disable address caching for Web services, you need to set an additional JVM custom property disableWSAddressCaching to true. Use this property to disable address caching for Web services. If your system typically runs with lots of client threads, and you encounter lock contention on the wsAddrCache cache, you can set this custom property to true, to prevent caching of the Web services data.

Google Script to see if text contains a value

Google Apps Script is javascript, you can use all the string methods...

var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }

You can find doc on many sites, this one for example.

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

Deploying just HTML, CSS webpage to Tomcat

Here's my step in Ubuntu 16.04 and Tomcat 8.

  1. Copy folder /var/lib/tomcat8/webapps/ROOT to your folder.

    cp -r /var/lib/tomcat8/webapps/ROOT /var/lib/tomcat8/webapps/{yourfolder}

  2. Add your html, css, js, to your folder.

  3. Open "http://localhost:8080/{yourfolder}" in browser

Notes:

  1. If you using chrome web browser and did wrong folder before, then clean web browser's cache(or change another name) otherwise (sometimes) it always 404.

  2. The folder META-INF with context.xml is needed.

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

Make Sure you have included this part in your layout (top below xmlns:android line)

xmlns:ads="http://schemas.android.com/apk/res/com.google.example" 
...........blah blah..

Also Check whether you have included attrs.xml in the res/values/

Check here for more details. http://code.google.com/mobile/ads/docs/android/banner_xml.html

What is the difference between Java RMI and RPC?

RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.

Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.

Upgrade Node.js to the latest version on Mac OS

You can directly use curl to upgrade node to the latest version. Run the following command:

curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg</a>.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/"

Reference: https://nodejs.org/en/download/package-manager/#macos

round up to 2 decimal places in java?

public static float roundFloat(float in) {
    return ((int)((in*100f)+0.5f))/100f;
}

Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.

What are 'get' and 'set' in Swift?

The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.

Consider a variable members of a class family. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.

So you would probably go ahead by defining the members variable like this:

class family {
   var members:Int
}

This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.

This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.

Returning to our family class, let's make sure nobody can set the members value to anything less than 2:

class family {
  var _members:Int = 2
  var members:Int {
   get {
     return _members
   }
   set (newVal) {
     if newVal >= 2 {
       _members = newVal
     } else {
       println('error: cannot have family with less than 2 members')
     }
   }
  }
}

Now we can access the members variable as before, by typing instanceOfFamily.members, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.

Note the introduction of the _members variable, which is the actual variable to store the value that we set through the members setter function. The original members has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void);

That is the correct way to say "no parameters" in C, and it also works in C++.

But:

void foo();

Means different things in C and C++! In C it means "could take any number of parameters of unknown types", and in C++ it means the same as foo(void).

Variable argument list functions are inherently un-typesafe and should be avoided where possible.

INNER JOIN ON vs WHERE clause

If you are often programming dynamic stored procedures, you will fall in love with your second example (using where). If you have various input parameters and lots of morph mess, then that is the only way. Otherwise, they both will run the same query plan so there is definitely no obvious difference in classic queries.

Rails: How to list database tables/objects using the Rails console?

I hope my late answer can be of some help.
This will go to rails database console.

rails db

pretty print your query output

.headers on
.mode columns
(turn headers on and show database data in column mode )

Show the tables

.table

'.help' to see help.
Or use SQL statements like 'Select * from cars'

Setting Column width in Apache POI

I answered my problem with a default width for all columns and cells, like below:

int width = 15; // Where width is number of caracters 
sheet.setDefaultColumnWidth(width);

How to restart a rails server on Heroku?

Just type the following commands from console.

cd /your_project
heroku restart

.includes() not working in Internet Explorer

Or just put this in a Javascript file and have a good day :)

String.prototype.includes = function (str) {
  var returnValue = false;

  if (this.indexOf(str) !== -1) {
    returnValue = true;
  }

  return returnValue;
}

Convert canvas to PDF

So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.

  // Download button
  $("#download-image").on('click', function () {
    let width = __CANVAS.width; 
    let height = __CANVAS.height;

    //set the orientation
    if(width > height){
      pdf = new jsPDF('l', 'px', [width, height]);
    }
    else{
      pdf = new jsPDF('p', 'px', [height, width]);
    }
    //then we get the dimensions from the 'pdf' file itself
    width = pdf.internal.pageSize.getWidth();
    height = pdf.internal.pageSize.getHeight();
    pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
    pdf.save("download.pdf");
  });

Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476

C#: Printing all properties of an object

Any other solution/library is in the end going to use reflection to introspect the type...

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

**

bundle install --no-deployment

**

$ jekyll help

jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

Java Equivalent of C# async/await?

No, there isn't any equivalent of async/await in Java - or even in C# before v5.

It's a fairly complex language feature to build a state machine behind the scenes.

There's relatively little language support for asynchrony/concurrency in Java, but the java.util.concurrent package contains a lot of useful classes around this. (Not quite equivalent to the Task Parallel Library, but the closest approximation to it.)

Maven Unable to locate the Javac Compiler in:

I am able to resolved by doing following steps :

Right click on project select Build path -> Configure build path -> select Libraries Tab -> then select JRE System Library[version you have for me its JavaSE-1.7] - > click Edit button -> In JRE System Library window select Execution environment - In drop down you can select the JDK listed for me its JavaSE-1.7 -> next to this click to Environments button -> In Execution Environments window you have to again select your java SE for me its JavaSE-1.7 -> just select it, you will have options in Compatible JREs tab, so select JDK that you want to have in my case its jdk1.7.0_25.


Click ok and finish the rest windows by doing appropriate action Ok/Finish.

Lastly do Maven Clean and Maven Install.

Javascript isnull

I prefer the style

(results || [, 0]) [1]

Python - use list as function parameters

This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.

def some_func(a_char, a_float, a_something):
    print a_char

params = ['a', 3.4, None]
some_func(*params)

>> a

How to set xampp open localhost:8080 instead of just localhost

you can get loccalhost page by writing localhost/xampp or by writing http://127.0.0.1 you will get the local host page. After starting the apache serve that can be from wamp, xamp or lamp.

How do I extract Month and Year in a MySQL date and compare them?

in Mysql Doku: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract

SELECT EXTRACT( YEAR_MONTH FROM `date` ) 
FROM `Table` WHERE Condition = 'Condition';

@Media min-width & max-width

I've found the best method is to write your default CSS for the older browsers, as older browsers including i.e. 5.5, 6, 7 and 8. Can't read @media. When I use @media I use it like this:

<style type="text/css">
    /* default styles here for older browsers. 
       I tend to go for a 600px - 960px width max but using percentages
    */
    @media only screen and (min-width: 960px) {
        /* styles for browsers larger than 960px; */
    }
    @media only screen and (min-width: 1440px) {
        /* styles for browsers larger than 1440px; */
    }
    @media only screen and (min-width: 2000px) {
        /* for sumo sized (mac) screens */
    }
    @media only screen and (max-device-width: 480px) {
       /* styles for mobile browsers smaller than 480px; (iPhone) */
    }
    @media only screen and (device-width: 768px) {
       /* default iPad screens */
    }
    /* different techniques for iPad screening */
    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
      /* For portrait layouts only */
    }

    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
      /* For landscape layouts only */
    }
</style>

But you can do whatever you like with your @media, This is just an example of what I've found best for me when building styles for all browsers.

iPad CSS specifications.

Also! If you're looking for printability you can use @media print{}

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How to convert a string to lower case in Bash?

If using v4, this is baked-in. If not, here is a simple, widely applicable solution. Other answers (and comments) on this thread were quite helpful in creating the code below.

# Like echo, but converts to lowercase
echolcase () {
    tr [:upper:] [:lower:] <<< "${*}"
}

# Takes one arg by reference (var name) and makes it lowercase
lcase () { 
    eval "${1}"=\'$(echo ${!1//\'/"'\''"} | tr [:upper:] [:lower:] )\'
}

Notes:

  • Doing: a="Hi All" and then: lcase a will do the same thing as: a=$( echolcase "Hi All" )
  • In the lcase function, using ${!1//\'/"'\''"} instead of ${!1} allows this to work even when the string has quotes.

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4, see this answer.

For Rails 3.x, configure a logger in config/environments/test.rb:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR

This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.

Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile, then set up two appenders in config/environments/test.rb:

logger = Logging.logger['test']
logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

Actually you can do it.

Although, someone should note that repeating the CASE statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE twice so that you won't get any performance hit because of that.

Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)

INSERT INTO dbo.T1
(
    Col1,
    Col2,
    Col3
)
SELECT
    1,
    SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
    SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
    dbo.T1 t
LEFT OUTER JOIN
(
    SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1

This will insert the values (1, 2, 3) for each record in the table T1. This uses a delimiter '%' to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar fields etc.). But the main logic is that you should join the CASE statement and select from the result set of the join with using a split logic.

What is the best way to manage a user's session in React?

This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.

jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
    res.json({
      token
  });

user object in here is the user data which you want to keep in the session

localStorage.setItem('session',JSON.stringify(token));

Python Finding Prime Factors

Isn't largest prime factor of 27 is 3 ?? The above code might be fastest,but it fails on 27 right ? 27 = 3*3*3 The above code returns 1 As far as I know.....1 is neither prime nor composite

I think, this is the better code

def prime_factors(n):
    factors=[]
    d=2
    while(d*d<=n):
        while(n>1):            
            while n%d==0:
                factors.append(d)
                n=n/d
            d+=1
    return factors[-1]

Undo scaffolding in Rails

When we generate scaffold, following files will be created:

Command: rails generate scaffold Game

Files created:

>       invoke  active_record
>       create    db/migrate/20160905064128_create_games.rb
>       create    app/models/game.rb
>       invoke    test_unit
>       create      test/models/game_test.rb
>       create      test/fixtures/games.yml
>       invoke  resource_route
>        route    resources :games
>       invoke  inherited_resources_controller
>       create    app/controllers/games_controller.rb
>       invoke    erb
>       create      app/views/games
>       create      app/views/games/index.html.erb
>       create      app/views/games/edit.html.erb
>       create      app/views/games/show.html.erb
>       create      app/views/games/new.html.erb
>       create      app/views/games/_form.html.erb
>       invoke    test_unit
>       create      test/controllers/games_controller_test.rb
>       invoke    helper
>       create      app/helpers/games_helper.rb
>       invoke      test_unit
>       create        test/helpers/games_helper_test.rb
>       invoke    jbuilder
>       create      app/views/games/index.json.jbuilder
>       create      app/views/games/show.json.jbuilder
>       invoke  assets
>       invoke    coffee
>       create      app/assets/javascripts/games.js.coffee
>       invoke    scss
>       create      app/assets/stylesheets/games.css.scss
>       invoke  scss
>       create    app/assets/stylesheets/scaffolds.css.scss

If we have run the migration after this then we have to rollback the migration first as the deletion of scaffold will remove the migration file too and we will not able to revert that migration.

Incase we have run the migration:

rake db:rollback

and after this we can safely remove the scaffold by this commad.

rails d scaffold Game

This command will remove all the files created by the scaffold in your project.

PHP header(Location: ...): Force URL change in address bar

why all of this location url?

http://localhost:8080/meet2eat/index.php

you can just use

index.php

if the php files are in the same folder and this is better because if you want to host the files or change the port you will have no problem reaching this URL.

Converting Columns into rows with their respective data in sql server

i solved the query this way

SELECT
    ca.ID, ca.[Name]
FROM [Emp2]
CROSS APPLY (
      Values
         ('ID' , cast(ID as varchar)),
         ('[Name]' , Name)

  ) as CA (ID, Name)

output look like

  ID     Name
------ --------------------------------------------------
ID     1
[Name] Joy
ID     2
[Name] jean
ID     4
[Name] paul

Initializing data.frames()

> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300

How to download fetch response in react as file

I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was

onClick = () => {
  // do something to compute or go fetch
  // the url we need from the server
  const url = goComputeOrFetchURL();

  // window.location forces the browser to prompt the user if they want to download it
  window.location = url
}

render() {
  return (
    <Button onClick={ this.onClick } />
  );
}

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.