Q:

Configuration of eclipselink + Spring MVC + MySql using Java Configuration (No XML configuration)

I am trying to integrate eclipselink JPA into my Spring Web application.
Is there any good guide oh how to configure eclipseLink for MySql database in Spring MVC using Java based configuration only?. No dispatcher-servlet.xml.
I am familiar with Java based Spring configuration. (Using @Configuration, @EnableWebMvc, @ComponentScan, @EnableTransactionManagement etc). But not familiar with eclipseLink java based configuration in Spring MVC.
Following is the pom.xml
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>roster3</groupId>
    <artifactId>roster3</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>roster3 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.0.2.RELEASE</spring.version>
        <hibernate.version>4.3.4.Final</hibernate.version>
        <hibernate.validator.version>5.1.0.Final</hibernate.validator.version>
        <mysql.connector.version>5.1.29</mysql.connector.version>
        <eclipselink.version>2.5.0</eclipselink.version>
        <aspectj.version>1.5.4</aspectj.version>
    </properties>
    <repositories>
        <repository>
            <id>oss.sonatype.org</id>
            <name>OSS Sonatype Staging</name>
            <url>https://oss.sonatype.org/content/groups/staging</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency> -->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Servlet & jstl -->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Hibernate Validation & DB Validation -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator.version}</version>
        </dependency>

        <!-- eclipselink -->
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>${eclipselink.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>commonj.sdo</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.4</version>
        </dependency>

    </dependencies>
    <build>

        <!-- To define the plugin version in your parent POM -->
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.3-SNAPSHOT</version>
                <configuration>
                    <url>http://127.0.0.1:8080/roster3</url>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                    <argLine>-javaagent:eclipselink.jar</argLine>
                </configuration>
            </plugin>
            <!-- This plugin ensures the EclipseLink static weaving -->
            <plugin>
                <artifactId>eclipselink-staticweave-maven-plugin</artifactId>
                <groupId>au.com.alderaan</groupId>
                <version>1.0.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>weave</goal>
                        </goals>
                        <phase>process-classes</phase>
                        <configuration>
                            <logLevel>ALL</logLevel>
                            <!-- <includeProjectClasspath>true</includeProjectClasspath> -->
                        </configuration>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.eclipse.persistence</groupId>
                        <artifactId>eclipselink</artifactId>
                        <version>${eclipselink.version}</version>
                    </dependency>
                </dependencies>
            </plugin>

        </plugins>
        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings
                    only. It has no influence on the Maven build itself. -->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            au.com.alderaan
                                        </groupId>
                                        <artifactId>
                                            eclipselink-staticweave-maven-plugin
                                        </artifactId>
                                        <versionRange>
                                            [1.0.4,)
                                        </versionRange>
                                        <goals>
                                            <goal>weave</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute>
                                            <runOnIncremental>true</runOnIncremental>
                                        </execute>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>roster3</finalName>
    </build>
</project>

Following is what I tried as of now.
Configuration class Config.java
package com.ecw.roster.config;

import java.util.Properties;

import org.eclipse.persistence.platform.database.DatabasePlatform;
import org.eclipse.persistence.platform.database.MySQLPlatform;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration //Marks this class as configuration
@EnableWebMvc
//Specifies which package to scan
@ComponentScan("com.ecw.roster")
@PropertySource(value = "classpath:application.properties")
//Enable Spring's annotations
@EnableTransactionManagement
public class Config extends WebMvcConfigurerAdapter{

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

    private static final String PROPERTY_NAME_DATABASEPLATFORM = "databasePlatform";
    private static final String PROPERTY_NAME_GENERATE_DDL = "generateDdl";
    private static final String PROPERTY_NAME_SHOW_SQL = "showSql";

    @Value("${jdbc.driverClassName}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

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

    @Value("${hibernate.dialect}")
    private String hibernate_dialect;

    @Value("${hibernate.show_sql}")
    private String hibernate_show_sql;

    @Value("${entitymanager.packages.to.scan}")
    private String entity_package_to_scan;

    @Bean
    public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        System.out.println("Roster 3 : Initializing UrlBasedViewResolver........");
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    @Bean
    public PlatformTransactionManager transactionManager(){
        System.out.println("Roster 3 : LocalContainerEntityManagerFactoryBean *************");
       JpaTransactionManager transactionManager = new JpaTransactionManager();
       transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
       return transactionManager;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setPackagesToScan(new String[] { "com.ecw.roster.beans" });
        em.setPersistenceUnitName("roster3");
        DatabasePlatform dp = new MySQLPlatform();
        em.setJpaVendorAdapter(getEclipseLinkJpaVendorAdapter());
        return em;
    }

    private EclipseLinkJpaVendorAdapter getEclipseLinkJpaVendorAdapter(){
        System.out.println("Roster 3 : EclipseLinkJpaVendorAdapter initialization ***************");

        EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
        vendorAdapter.setDatabasePlatform("org.eclipse.persistence.platform.database.MySQLPlatform");
        vendorAdapter.setGenerateDdl(false);
        vendorAdapter.setShowSql(true);
        return vendorAdapter;
    }

    private Properties eclipseLinkProperty(){
        Properties properties = new Properties();
        properties.put("eclipselink.deploy-on-startup", "true");
        properties.put("eclipselink.ddl-generation", "create-or-extend-tables");
        properties.put("eclipselink.ddl-generation.output-mode", "database");
        properties.put("eclipselink.weaving", "static");
        properties.put("eclipselink.weaving.lazy", "true");
        properties.put("eclipselink.weaving.internal", "true");
        properties.put("eclipselink.logging.level", "SEVERE");
        properties.put("eclipselink.query-results-cache.type", "WEAK");
        properties.put("eclipselink.jdbc.batch-writing", "JDBC");
        properties.put("eclipselink.jdbc.batch-writing.size", "1000");
        return properties;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("In Resouce Handler");
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/defaultTheme/");
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages/messages/");
        return messageSource;
    }

}

persistence.xml file for eclipselink:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="roster3" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.ecw.roster.beans.Roster</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/roster" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="mysqladmin" />
        </properties>
    </persistence-unit>
</persistence>

I am able to build & deploy the project but I am getting connection leaks & then my context is stopped by tomcat container.
Please advice me what I am doing wrong with it.
Thanks

A:

The following configuration will enable Spring to use two application contexts (the root context and the web application context) and will configure most of the things you need.
@Configuration
@EnableTransactionManagement
@EnableMBeanExport
@EnableJpaRepositories("your.jpa.repositories.package")
@ComponentScan(basePackages = "gr.xe.payments", excludeFilters = {@ComponentScan.Filter(value = Controller.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE ,value = MvcConfig.class)})
public class ApplicationConfig {

}

@EnableWebMvc
@ComponentScan(basePackages = "your.controller.package", includeFilters = @ComponentScan.Filter(value = Controller.class))
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public TilesConfigurer tilesViewResolver() {
        TilesConfigurer tilesViewResolver = new TilesConfigurer();
        tilesViewResolver.setDefinitions(new String[]{"/WEB-INF/tiles.xml"});
        return tilesViewResolver;
    }

    @Bean
    public UrlBasedViewResolver urlBasedViewResolver() {
        UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
        urlBasedViewResolver.setViewClass(TilesView.class);
        return urlBasedViewResolver;
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource() {
        ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
        reloadableResourceBundleMessageSource.setBasename("WEB-INF/i18n/messages");
        reloadableResourceBundleMessageSource.setFallbackToSystemLocale(false);
        reloadableResourceBundleMessageSource.setDefaultEncoding("UTF-8");
        return reloadableResourceBundleMessageSource;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

@Configuration
public class DatabaseConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(false);

        LocalContainerEntityManagerFactoryBean factory =
                new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("your.domain.package");
        factory.setDataSource(dataSource());
        factory.setJpaProperties(jpaProperties());
        return factory;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Bean
    public DataSource dataSource() {
        //This uses JNDI, you could create the data source in any way you want
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            return (DataSource) envCtx.lookup("jdbc/yourDS");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Unable to lookup datasource", e);
        }
    }

    private Properties jpaProperties() {
        Properties properties = new Properties();
        //use whatever EclipseLink properties you like
        return properties;
    }
}

EDIT:
The relevant dependencies are
<properties>
    <spring.version>3.2.8.RELEASE</spring.version>
    <spring-security.version>3.1.3.RELEASE</spring-security.version>
</properties>

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
        <exclusions>
            <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
         <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.2.0.RELEASE</version>
        <exclusions>
            <exclusion>
                <artifactId>slf4j-api</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
            <exclusion>
                <artifactId>jcl-over-slf4j</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.1</version>
    </dependency>


Q:

Tomcat specific webapp slowdown

Today in the company where I work we received a report about one of our webapps not working.
The first thing we did was look at the hardware utilization:

Processor: 5%;
Memory: 68%;
Disk IO capacity: 4%;
Network: 1Mbps/1Gbps;

After some tests we saw that, indeed, the webapp pages weren't loading, some time after the webapp timeouts.
Other webapps in the exactly same tomcat instance were working fine and fast as ever, no problem with them. We tried to restart/reload the webapp but it still didn't get it working. Finally we restarted tomcat which corrected the issue for now.
There were no restarts or redeploys since yesterday when it was working fine. We believe this may be a periodic bug of some sort so we want to correct it soon.
Does anyone know of any steps we may take to investigate what it might have been?

A:

It seems related to lock on IO.
If you are using linux, the first thing is do is to check open files by using the command lsof . If you see a lot of opened files by your app, you have to check in the code that every InputStream/OutputStream are closed (even in exception handling code).
An other common source of issues is related to thread starvation, see http://tomcat.apache.org/tomcat-9.0-doc/config/valve.html#Stuck_Thread_Detection_Valve


Q:

What does "toggle" mean in the context of Lexplore?

The description of Lexplore says that it "toggles" a directory window on the left side, but I don't see the difference between that and Vexplore, which seems to do exactly the same thing. If I do :Lex twice in row, then a second netrw window is created, so it does not appear to turn the window off (q) as a toggle would normally mean. What does the help mean by "toggle" in this context if it does not mean to close the window? The help itself is unclear because it does not explain what the command does (any different than Vex).

A:

With :Vexplore, the current window is split in two and a netrw buffer is displayed in the new window.
Repeating that command again and again will keep splitting the current window until the left half of the workspace is filled with very narrow netrw windows.
:Lexplore is a toggle, this means that it switches between two states:

The netrw window created with :Lexplore is not present.
A new window is created.
The netrw window created with :Lexplore is present.
That window is closed.


Q:

Forcing Object Data Source To Reinstantiate

I am using the XPages Mobile Controls with an Object data source (Java Class which is NOT a managed bean) tied to View scope on a second app page. I have resetContent on the second page set to true. So I would have assumed the Object Data Source would be destroyed and recreated every time I transitioned to the second page.
When I transition to the second page the first time, the createObject() method is invoked as expected. If I transition to the second page using a button AND set forceFullRefresh to true the createObject() method is invoked. If, however I have a Rounded List Item with a moveTo specified for the second page the createObject() method does not get invoked. Instead the object remains set to the last value it was using when that application page was last accessed.
Is there a way to force the createObject() method to be invoked every time I transition to the page?

A:

The solution turned out to be to move the object data source from view scope to request scope.  This is possible because I do not have the need for any partial refreshes on that page until the details are ready to be submitted.


Q:

Drupal7: Change node permission programmatically

I'm creating a custom Drupal 7 module and within my module I'm creating a node programmatically. In summary, it's something like this:
$node = new stdClass();
$node->type = 'donation';
node_object_prepare($node);
$node->title = 'Donation made on ' . date('r');
node_save($node);

How can I modify/set the permission for this dynamically created node so it's only accessible to admins?

A:

I used Content Access module and it solved my problem.


Q:

In C#, how can I access an object's objects when bracket notation doesn't work?

I have an object of objects, and I'm not sure how to access the values. Here's a picture from the VS debugger:

the object in question is bounds. I'd like to get the value 7, 14, 157 and 174 like so:
bounds[0]  //Should equal 7
bounds[3]  //Should equal 174

Obviously this won't work  because it's not an array but an object of objects. Could you explain the correct way to access the numeric values nested inside the bounds object?
Thank you!

A:

You need to cast bounds from object to object[], get the value from the array, then cast it to double.
object[] array = (object[])bounds;
object value = array[0];
double number = (double)value;

or one line
double value = (double)((object[])bounds)[0];

If you put your numbers in an array of double in the first place, then you can avoid all the casting.
double[] bounds = new double[x];
... populate array
double value = bounds[0];

Also, "bracket notation" is know as indexers.


Q:

Printing text from 2-D list python

I am making a GUI using pyqt4. In this application i am storing my result from database in a 2-d list and now i want to print this list in my GUI, but when i do so, every result is being printed on a new line, so how do i print 1 row in a line?
for row in to_d_col:
      clm = ''
      for col in row:
          q=q+1
          item = QtGui.QListWidgetItem("%i)  %s"% (q,col))

I have tried to store the result in a string and then print it, it works fine by that way but the spaces between the words create a problem.
for row in to_d_col:
      clm = ''
      for col in row:
          clm = clm +str(col)+"\t"
      q=q+1
      item = QtGui.QListWidgetItem("%i)  %s"% (q,clm))
      self.listWidget_2.addItem(item)
          self.listWidget_2.addItem(item)

A:

You should probably use a QtGui.QTableWidget instead of a listwidget, and fill it like so:
widget = QtGui.QTableWidget(parent) # or get the widget some other way
for i, row in enumerate(to_d_col):
  for j, value in enumerate(row):
    ci = QtGui.QTableWidgetItem(value)
    widget.setItem(i, j, ci)


Q:

how can I make sense of the trigonometric outputs of radian values that are not represented as multiples of π?

E.g., $\cos 2, \cos3$ are negative. Is there a conversion formula?

A:

Note that $$\dfrac{\pi}2 \; \leq 2\;\leq 3\leq \;\pi$$ (Think second quadrant.) So yes, in radians, $\cos 2$, and $\cos 3$ are negative.
(Radians are the default measure of angles, and in most cases, barring the designation of angle x in degrees, like $(x^\circ)$, they are assumed to be measured in radians.)
In degrees, we have $2 \times \frac{180^\circ}{\pi} $ degrees.
Similarly for converting $3$ radians to degrees.


Q:

App appearing on Android Market (Google Play) as twice its size?

I have an apk which is 13.5MB. When I upload it to Google Play it shows as 27MB. When you start the download, however, you'll see the progress bar going from 0 to 13.5MB (as it should) rather than 0 to 27MB (as advertised on Google Play). Quite strange. Anyone else experienced this or know why it's happening?
If you want to see for yourself, this is the app:
htps://play.google.com/store/apps/details?id=com.projectzebra.bunkerbuster

A:

It's because the Copy Protection feature in Publishing Options was enabled. Disabling this feature, re-uploading my apk and saving changes (in the Edit Application page of Android Developer Console) got it down to its proper size.


Q:

Android touch event propagation

It's my understanding that Android event propagation goes from parent to child, that is to say, it starts with the outermost element and inwards from there. My question is, why is it that when I try to scroll vertically a listview that is inside a viewpager that is wrapped on a scrollview, the listview moves, and not the viewpager.
Okay, let me rephrase that:
I'm trying to create a menu that appears when the user pulls down the view pager, let me make that even clearer:
Scrollview
   My custom Menu
   ViewPager (with three fragments, all of them have a lisview)
      ListView
I understand that what I'm trying to do is a bit odd, but bear with me just for this time. :)
What can I do to "disable" momentarily the list views scrolling.
Thanks

A:

It seems you have to override the scrolling event. A good webpage is Disable scrolling in Android ListView .
Mainly look at dispatchTouchEvent. Snippet of it:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK;
    if (actionMasked == MotionEvent.ACTION_MOVE) {
        // Ignore move events
        return true;
    }

Personally I wish it is simpler than this like disabling scroll method.


Q:

Redirecting Loggers`messages to sys.stdout and sys.stderr

I´m just starting to learn Python and have encountered a Problem that I´m not able to solve.
I want to redirect every level above CRITICAL to sys.stderr and everything above WARNING to sys.stdout.
I came up with this script...

import logging
import sys

print("imported module {}".format(__name__))

class PyLogger(logging.Logger):
    """Wrapper for logging.Logger to redirect its message to
    sys.stdout or sys.stderr accordingly """

    def __init__(self, *args):
        super(PyLogger, self).__init__(self, *args)

        # get Logger
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

        # build Formatter
        formatter = logging.Formatter(fmt="%(asctime)s:%(name)s   %(message)s")

        # build StreamHandler for sys.stderr
        error = logging.StreamHandler(stream=sys.stderr)
        error.setLevel(logging.CRITICAL)
        error.setFormatter(formatter)
        logger.addHandler(error)

        # build StreamHandler for sys.stdin
        out = logging.StreamHandler(stream=sys.stdout)
        out.setFormatter(formatter)
        out.setLevel(logging.WARNING)
        logger.addHandler(out)

def main():
    logger = PyLogger()
    # help(logger)
    logger.info("INFO")

if __name__ == "__main__":
    main()

When running this scrip directly I get the following error:
No handlers could be found for logger "<__main__.PyLogger object at 0x105f23c50>"

I´ve googled around and many people said that a logging.basicConfig() would do the job but that didn´t worked for me.
Maybe someone of you guys could help me out.
Thanks!

A:

Your class subclasses logging.Logger, so you should not call getLogger or manipulate a logger as an attribute. Rather, the logger is self inside the class, and should be adjusted directly:
import logging
import sys

print("imported module {}".format(__name__))

class PyLogger(logging.Logger):
    """Wrapper for logging.Logger to redirect its message to
    sys.stdout or sys.stderr accordingly """

    def __init__(self, *args):
        super(PyLogger, self).__init__(self, *args)

        #####
        # self *is* the logger!
        self.setLevel(logging.DEBUG)

        # build Formatter
        formatter = logging.Formatter(fmt="%(asctime)s:%(name)s   %(message)s")

        # build StreamHandler for sys.stderr
        error = logging.StreamHandler(stream=sys.stderr)
        error.setLevel(logging.CRITICAL)
        error.setFormatter(formatter)

        #####
        # Assign the handler to self
        self.addHandler(error)

        # build StreamHandler for sys.stdin
        out = logging.StreamHandler(stream=sys.stdout)
        out.setFormatter(formatter)
        out.setLevel(logging.WARNING)

        #####
        # Assign the handler to self
        self.addHandler(out)

def main():
    logger = PyLogger()
    # help(logger)
    logger.info("INFO")
    logger.warning("WARN")
    logger.critical("CRIT")

if __name__ == "__main__":
    main()

This displays the following, as expected:
ely@eschaton:~/programming$ python test_logger.py
imported module __main__
2018-03-01 11:59:41,896:<__main__.PyLogger object at 0x7fa236aa4a50>   WARN
2018-03-01 11:59:41,896:<__main__.PyLogger object at 0x7fa236aa4a50>   CRIT
2018-03-01 11:59:41,896:<__main__.PyLogger object at 0x7fa236aa4a50>   CRIT

Notice how the critical message trips two different output handlers, so it appears twice (once because it satisfied warning level, once for critical level).
In your original code, notice that you are creating a variable called logger inside of __init__, but this not assigned to self or anything. This variable gets destroyed when it goes out of scope of the __init__ function, and so the assignment of any handlers is meaningless. Plus, because handlers weren't assigned to self, but the object that self is referencing is the logger that will be called later on, that is why you see the error about no handlers.


Q:

Substitute for chicken broth in tomato soup

In this recipe, how can I substitute chicken broth?

A:

Just use vegetable broth. It's sold in plenty of stores, though you can certainly make your own too, lots of recipes out there. The most canonical ingredients are onion, carrot, and celery, with some assortment of herbs and seasonings, but you'll also sometimes find things like mushrooms, peppers, tomatoes (surprise!), and even root vegetables! It's hard to recommend anything in particular, though; everyone has their preferences, and stronger flavored broths may not work as well in certain recipes.
Or of course you can go find a tomato soup recipe that doesn't use chicken broth.


Q:

Intersection between contour and rectangle OPENcv c++

I have drawn a rectangle using cv.rectangle and have a contours shape (from FindContours) which the rectangle is drawn over .
The rectangle intersects the the complete contour at two points. How can I find these points of intersection between the rectangle and the contour outline.
I could add the two images together and look for maxima but I do know how the rectangle vertices are stored , as I would need a line type vector filled with a set of points
Thanks

A:

If you are sure that your rectangle cross the shape at only 2 points, you can iterate through your contour point, and check if these points are in your rectangle border.
std::vector<cv::Point> shape; // computed with FindContours
cv::Rect myRect; //whatever

const int NUMPOINTS = 2;
int found = 0;
for(std::vector<cv::Point>::iterator it = shape.begin(); it != shapes.end() && found < NUMPOINTS; ++it) {
  if (it->y == myRect.y && it->x >= myRect.x && it->x < myRect.x + width)
    // that point cross the top line of the rectangle
    found++; // you might want to store the point
  else if (// ... add the other checks here)

}


Q:

How do you join two tables using Django without using raw sql?

Is is possible to programatically join two tables using Django's ORM? I have two models: Topics and Votes. On my template I have a list of topics that users can up/down vote like Reddit. Everything works as it should except for sorting the results. I cannot figure out how to sort an objects list based off the score which is a sum of each object's vote count. I can retrieve the desired data from postgres without any issue:
select i.id, i.title, i.date_created, s.object_id, s.vote, Sum(vote)
from topic_topic i, votes s
where i.id = s.object_id
group by 1, 2, 3, 4, 5
order by sum DESC;

It returns the desired results:
id | title  |         date_created          | object_id | vote | sum

11 | sdfg   | 2012-06-04 23:30:17.805671-07 |        11 |    1 |   2

 1 | test   | 2012-05-13 17:03:24.206092-07 |         1 |    1 |   2

 3 | asdf   | 2012-05-13 19:23:15.059135-07 |         3 |    1 |   2

 2 | adsf   | 2012-05-13 19:21:34.180905-07 |         2 |    1 |   2

12 | 11     | 2012-06-04 23:30:54.759158-07 |        12 |    1 |   2

 9 | asfd   | 2012-05-24 00:26:26.705843-07 |         9 |   -1 |  -1

 4 | asdf   | 2012-05-14 19:59:52.450693-07 |         4 |   -1 |  -2

The problem is, I am not sure how to retrieve this as a queryset. At the moment I am using the following to display objects:
topic_list = Topic.objects.all()

Everything displays as I would like it to, except for the sort order. I would like the highest score to display first.
Resources I have already looked at:
https://docs.djangoproject.com/en/dev/topics/db/managers/#adding-extra-manager-methods
How to query as GROUP BY in django?
And many more, but as a new user, anti-spam prevents me from adding them.
Thing's I've tried:
Chain:
listed_links = list(chain(topic, score))

Unfortunately, if I tried to add a sorted value this broke.
Combining object lists:
topic = Topic.objects.all().values_list('user','id', 'title','slug', 'date_created', 'date_updated',)

score = Vote.objects.values('object_id').annotate(total=Sum('vote')).order_by('-total')

results = []

for topic in topic:
results.append(topic)

for score in score:
results.append(topic)

This resulted in all the objects I wanted in one list, but I could not figure out how to link topic.id to score.object_id.
I've also tried inserting raw SQL, but I don't feel like I am doing it correctly, and could lead to SQL injection by a third party.
I would love to share the results of this back to the django-voting project. Like I said, everything works as it should, except I cannot figure out how to sort by score desc.
=============Voting========================
from django.contrib.contenttypes import generic

from django.contrib.contenttypes.models import ContentType

from django.contrib.auth.models import User

from django.db import models

from voting.managers import VoteManager

from voting.VotedObjectsManager import VotedObjectsManager

    SCORES = (
    (+1, u'+1'),
    (-1, u'-1'),
)

class Vote(models.Model):

    """
    A vote on an object by a User.
    """

    user         = models.ForeignKey(User)

    content_type = models.ForeignKey(ContentType)

    object_id    = models.PositiveIntegerField()

    object       = generic.GenericForeignKey('content_type', 'object_id')

    vote         = models.SmallIntegerField(choices=SCORES)

    objects      = VoteManager()

    class Meta:
        db_table = 'votes'
        # One vote per user per object
        unique_together = (('user', 'content_type', 'object_id'),)

    def __unicode__(self):
        return u'%s: %s on %s' % (self.user, self.vote, self.object)

    def is_upvote(self):
        return self.vote == 1

    def is_downvote(self):
        return self.vote == -1

=============Topic Model========================
from django.db import models

from datetime import datetime

from tinymce import models as tinymce_models

from django.forms import ModelForm

from django.template.defaultfilters import slugify

from tagging.fields import TagField

from tagging.models import Tag

from django.contrib.auth.models import User

from django.utils.translation import ugettext_lazy as _

from django.contrib.contenttypes.models import ContentType

from django.contrib.contenttypes import generic

from django.core import urlresolvers

    class Topic(models.Model):

    title           = models.CharField(max_length=50)

    slug            = models.SlugField(max_length=50, editable=False)

    topic         = tinymce_models.HTMLField()

    date_created    = models.DateTimeField(editable=False)

    date_updated    = models.DateTimeField(editable=False)

    tags            = TagField()

    def set_tags(self, tags):
        Tag.objects.update_tags(self, tags)

    def __unicode__(self):
        return self.tags

    def __unicode__(self):
        return self.id

    def __unicode__(self):
        return self.title

A:

I was able to figure out the solution using a patch as described here:
http://code.google.com/p/django-voting/issues/detail?id=10
The difference was that I extracted the following lines:
    def select_score(self):
    """ Add vote scores for objects in resoultset """
    from django.contrib.contenttypes.models import ContentType
    model_type = ContentType.objects.get_for_model(self.model)
    table_name = self.model._meta.db_table
    print type(model_type)
    print model_type.id
    return self.extra(select={'score': 'SELECT SUM(vote) FROM votes WHERE content_type_id=%i AND object_id=%s.id' % (int(model_type.id), table_name)})

And added them to the voting/managers.py file as so:
class VoteManager(models.Manager):
def get_score(self, obj):
    """
    Get a dictionary containing the total score for ``obj`` and
    the number of votes it's received.
    """
    ctype = ContentType.objects.get_for_model(obj)
    result = self.filter(object_id=obj._get_pk_val(),
                         content_type=ctype).extra(
        select={
            'score': 'COALESCE(SUM(vote), 0)',
            'num_votes': 'COALESCE(COUNT(vote), 0)',
    }).values_list('score', 'num_votes')[0]

    return {
        'score': int(result[0]),
        'num_votes': int(result[1]),
    }

Then In my topic.views.py I added the following:
from voting.managers import VoteManager
def index(request):
queryset = Topic.objects.select_score().order_by('-score')
paginator = Paginator(queryset, 3) # Show 25 contacts per page

page = request.GET.get('page')
try:
    topic_list = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    topic_list = paginator.page(1)
except EmptyPage:
    #If page is out of range (e.g. 9999), deliver last page of results.
    topic_list = paginator.page(paginator.num_pages)

c = Context({
'topic_list': topic_list,
'request': request
})
return render_to_response('idea/index.html', c, context_instance=RequestContext(request))

Lastly, in my index.html I added the following lines slightly deviating from the original example provided for users:
{% load voting_tags %}
{% votes_by_user user on topic_list as vote_dict %}
{% scores_for_objects topic_list as score_dict %}

  {% for link in topic_list %}

{% dict_entry_for_item link from vote_dict as vote %}
{% dict_entry_for_item link from score_dict as score %}

 <form class="linkvote" id="linkup{{ link.id }}"{% if vote and vote.is_upvote %} action="{% url link_vote object_id=link.id, direction="clear" %}"{% else %} action="{% url link_vote object_id=link.id, direction="up" %}"{% endif %} method="POST">
    <input type="image" id="linkuparrow{{ link.id }}" src="{{ STATIC_URL }}images/aup{% if vote and vote.is_upvote %}mod{% else %}grey{% endif %}.png">
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ request.get_full_path }}"/>
    {% else %}

  </form>

{{ score.score|default:0 }}

  <form class="linkvote" id="linkdown{{ link.id }}" {% if vote and vote.is_downvote %} action="{% url link_vote object_id=link.id, direction="clear" %}"{% else %} action="{% url link_vote object_id=link.id, direction="down" %}"{% endif %} method="POST">
  {% csrf_token %}
    <input type="image" id="linkdownarrow{{ link.id }}" src="{{ STATIC_URL }}images/adown{% if vote and vote.is_downvote %}mod{% else %}grey{% endif %}.png">
     <input type="hidden" name="next" value="{{ request.get_full_path }}"/>

  {{ link.title|escape }}

    posted {{ link.date_created|timesince }} ago by
    {{ link.owner|escape }}
{% get_comment_count for link as comment_count %}
     {{ comment_count }} comment{{ comment_count|pluralize }}

{% endfor %}

        {% if topic_list.has_previous %}
            previous
    {% endif %}
    {% if topic_list.has_next %}
        next
    {% endif %}

EDIT
I almost forgot! If you would like the list to sort in an order like 2,1,0,-1,-2 make sure to set the vote object value upon submitting whatever object you are creating. The example below is from my topic.views.py.
def submit_topic(request):

if request.method == 'POST':
    post_topic = PosttopicForm(request.POST)
    owner = request.user
    if post_topic.is_valid():
        topic = post_topic.save(commit=False)
        topic.owner = request.user
        topic.save()
        vote = Vote(vote='0', user = request.user, content_type_id=10, object_id=topic.pk)
        vote.save()
        url = reverse('topic', args=[topic.pk, topic.slug])
        return HttpResponseRedirect(url)
else:
    post_topic = PosttopicForm()

c = Context({
    'form': post_topic,
    'user': request.user,
    'request': request,

})
return render_to_response('topic/submit.html', c, context_instance=RequestContext(request))

I really hopes this helps someone else. Sorry for not posting the solution sooner. Hopefully someone can improve this by getting rid of the SQL all together from the VoteManager, but I need to move forward.


Q:

How to write unit tests for emails being sent via Apex?

If I send an email via Apex
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(someContactId);
mail.setTemplateId(someTemplateId);
mail.setSaveAsActivity(true);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

How can I create a unit test and test whether it was sent? Checking e.g. Limits.getEmailInvocations() doesn't actually work, because the emails are not sent out for real during tests. Or should I simpy assume that it works for the given contact and emailtemplate?

A:

Testing emails involves many things

To test that the properties of an email are properly set and that your code actually tries to send an email, see this Stackexchange answer that exploits ApexMocks.
To test that an email template is properly rendered before sending it, the savepoint - rollback hack is no longer required. You can use built-in Apex methods that render an email template. These are described in this stackexchange answer

The latter use case will mean you should create a wrapper method around your rendering of the template so you can unit test that method in a testmethod by passing in different arguments and verifying the proper application of merge fields to the template
For example
public Messaging.SingleEmailMessage render(ID templateId, ID whoId, ID whatId) {
 return Messaging.renderStoredEmailTemplate(templateId, whoId, whatId);
}

and the testmethod
// Given Sobjects corresponding to the whoId and whatId. Mock or fetch an email template and note the Id

Account a = new Account(...);
insert a;
Contact c = new Contact(...);
insert c;
EmailTemplate et;

System.runAs([select Id from User where Id = :Userinfo.getUserId() limit 1][0]) {       // creating setup objects requires diff context
  Folder[] folders = [select Id from Folder
                        where AccessType IN: new list<String>{'Shared','Public'}
                          AND Type = 'Email'];
  System.assert(!folders.isEmpty(),'test can\'t run wo Email Template folders. Folders can\'t be mocked in Apex');

  //    Given an EmailTemplate with merge fields
  et = new EmailTemplate(   Name = 'TestEmailTemplate ApexTestMethod',
                            Body = someBodyWithMergeFields,
                            DeveloperName = 'TestEmailTemplate_ApexTestMethod',
                            FolderId = folders[0].Id,
                            HtmlValue =someBodyWithMergeFields,
                            IsActive = true,
                            TemplateType = 'custom');
  insert et;
}

// When rendering...
Messaging.SingleEmailMessage res = new myClass().render(et.Id, c.id, a.Id);

// Then verify rendered template

System.assertEquals(someExpectedRenderedTemplate,res.getHtmlBody());

Note that you can't use mocked SObjects in memory here to test the above because the code under test actually queries the database given the Ids passed.


Q:

SELECT multiple data from MySQL node.js with promises

The concept of promises is very new for me (so far, I was working with async.each and async.waterfall)
I want to use promises but i'm stuck right now.
I want to get "tags" from my db.
I have two tables for this : One called 'tags' with every tag in it (with an ID) and another one 'user_tags' with every username saved and the ID of the tag that the user (username) created and saved into 'tags'.
I can put information in my DB but now I want to pull this out and log it out (I will display it later)
So far this is my idea :
var getUserprofile = function getUserprofile(username, callback){
  pool.getConnection(function (err, connection) {
    var dataUser = [];

    // Error check
    if (err) {
      console.log(err);
    }

    connection.query('SELECT * FROM users_tags FULL JOIN tags ON (tags.id = users_tags.t_id) WHERE users_tags.user_id=666;', username , function (err, rows, fields) {
      if (err) {
        connection.release();
        cb(err);
      } else if (rows.length < 1) {
        connection.release();
        cb("We don't have any informations about this user yet");

      } else {
        console.log("we pull the information right now");
        connection.release();
        callback(null, rows[0]);
      }
    });
  });
}

Is this a good idea ? What should I do if I want to use promises for this kind of function ?
Thanks in advance for any help !!!

A:

I would use Bluebird. You can "promisify" existing APIs with Promise.promisify or Promise.promisifyAll.
I would do something like
var Promise = require('bluebird'),
     ... //other deps;

var pool = Promise.promisifyAll(pool);
function getUserprofile(username){
    var connection = null;
    return pool.getConnectionAsync()
        .then(function (conn) {
             connection = Promise.promisifyAll(conn);
             return connection.queryAsync('...');
        })
        .then(function (results) {
             if (results.length < 1) {
                 return "We don't have any informations about this user yet";
             } else {
                 console.log("we pull the information right now");
                 return results[0];
             }
        })
        .catch(function (err) {
             console.log(err);
             throw err;
        })
        .finally(function () {
             if (connection) {
                 connection.release();
             }
        });
}


Q:

DFT in Python taking significantly longer than C

I'm currently working on translating some C code To Python. This code is being used to help identify errors arising from the CLEAN algorithm used in Radio Astronomy. In order to do this analysis the value of the Fourier Transforms of Intensity Maps, Q Stokes Map and U Stokes Map must be found at specific pixel values (given by ANT_pix). These Maps are just 257*257 arrays.
The below code takes a few seconds to run with C but takes hours to run with Python. I'm pretty sure that it is terribly optimized as my knowledge of Python is quite poor.
Thanks for any help you can give.
Update My question is if there is a better way to implement the loops in Python which will speed things up. I've read quite a few answer here for other questions on Python which recommend avoiding nested for loops in Python if possible and I'm just wondering if anyone knows a good way of implementing something like the Python code below without the loops or with better optimised loops. I realise this may be a tall order though!
I've been using the FFT up till now but my supervisor wants to see what sort of difference the DFT will make. This is because the Antenna position will not, in general, occur at exact pixels values. Using FFT requires round to the closest pixel value.
I'm using Python as CASA, the computer program used to reduce Radio Astronomy datasets is written in python and implementing Python scripts in it is far far easier than C.
Original Code
def DFT_Vis(ANT_Pix="",IMap="",QMap="",UMap="", NMap="", Nvis=""):

UV=numpy.zeros([Nvis,6])
Offset=(NMap+1)/2
ANT=ANT_Pix+Offset;

i=0
l=0
k=0
SumI=0
SumRL=0
SumLR=0

z=0

RL=QMap+1j*UMap
LR=QMap-1j*UMap

Factor=[math.e**(-2j*math.pi*z/NMap) for z in range(NMap)]

for i in range(Nvis):
    X=ANT[i,0]
    Y=ANT[i,1]

    for l in range(NMap):

        for k in range(NMap):

            Temp=Factor[int((X*l)%NMap)]*Factor[int((Y*k)%NMap)];

            SumI+=IMap[l,k]*Temp
            SumRL+=RL[l,k]*Temp
            SumLR+=IMap[l,k]*Temp

        k=1

    UV[i,0]=SumI.real
    UV[i,1]=SumI.imag
    UV[i,2]=SumRL.real
    UV[i,3]=SumRL.imag
    UV[i,4]=SumLR.real
    UV[i,5]=SumLR.imag
    l=1
    k=1
    SumI=0
    SumRL=0
    SumLR=0

return(UV)

A:

You should probably use numpy's fourier transform code, rather than writing your own: http://docs.scipy.org/doc/numpy/reference/routines.fft.html


Q:

Microservices architecture: Divide micro services by user roles alone

I have encountered the following design requirement in an app marketplace like project from a client in which users can rate games/apps they download (only in a special way more helpful than traditional marketplaces).
My question is regarding microservices architecture,
If I have a game user, app owner, market place moderator and market place admin roles and they have common API's they are using but also different ones where in some cases, for example, user can review an app but only moderator and admin can edit that review, so basically I can approach the design by having a microservice that is responsible for app reviews and have a single method SaveOrUpdateAppReview and then based on authentication and authorization both user, moderator and admin could call this method but update will only work for moderator and admin or I can perhaps split it into microservices based on roles, so ill have AppReview microservice having only createReview method and AppReviewModeration microservice in which will have both createReview (as moderator can also create a review) and editReview).
This example repeats itself in many workflows and use-cases, e.g 2, the app owner cannot change app price under certain conditions but admin can, so perhaps the method that enables it to do it should only be under App Admin microservice?
To sum it up, if different roles have different APIs they require, should I handle it in the design level, splitting/dividing it into different microservices or is it part of an internal authorization claim based logic and each method should check if its create or update and enable/disable accordingly.
Regards,
James

A:

Don't couple architecture to authorization policy. It's normal and expected to have code blocks branching on the user's permissions. Depending on how complex it is, you can keep it out of the way of other business logic by putting it in decorators / middleware.
If you have several frontends (e.g. game user and app owner are different apps), it can make sense to have a dedicated microservice sitting behind each one. This would then turn around and consume a common set of platform services. This can save you from having frontend-specific concerns in e.g. the review store layer. But it adds a lot of complexity, and as with all microservices architectures, you don't want to do this until your team is so big that you have to.


Q:

When writing carriage return to a pycharm console the whole line is deleted?

I have a program in Python that makes extensive use of the line feed character to produce the effect of an updating console line (specifically a progress bar).
When trying to debug the code in PyCharm I saw that the progress bar doesn't get printed until it's done.
Upon further inspection it turned out that when a carriage return (\r) is printed, the whole line is deleted.
Because the library itself writes strings of the form ({line}\r), I always get an empty line.
Is there any way to solve this using PyCharm? Currently what I'll be doing is replacing stdout with a version that records the current line and reprints it after a carriage return is received. However I'd much rather have a simple way to do it.
Sample code:
import sys
sys.stdout.write('xxx')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\rZZ')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('yyy\r')
sys.stdout.flush()

time.sleep(1)

print ('===')

My run looks like this:
1. 'xxx' is printed
[After 1 second]
2. 'ZZ' is printed
[After 1 second]
3. The line is deleted
[After 1 second]
4. '===' is printed and the program terminates
This happens both in the debug and the run console when running this script.

A:

I recently ran into the same problem, and found a solution.
The answer is actually in your post. As you said, the carriage return deletes the whole line. To avoid the issue, print the carriage return only when you print the new line, like so:
Print each line with the carriage return at the start, and without the default end='\n'. Didn't need the flush, though I didn't do much testing.
print('\rxxx', end='')
# sys.stdout.flush()
time.sleep(1)

Continue like this...
print('\rZZ', end='')
time.sleep(1)

print('\ryyy', end='')
time.sleep(1)

To keep the last printout, keep the default end.
print('\r===')

Hope this works for you.
Frank


Q:

Jersey: saving data in-memory

I am building a simple REST web service using Java and Jersey. I want to store some data in-memory that can be accessed during the time that the server is online. For example:
http://localhost:8080/register/<someusername>
would add  to an ArrayList/HashMap/etc that can be accessed by
http://localhost:8080/list
which would list the registered users.
How can I accomplish this?
I'm aware that this is not a great way to go about storing data, but for the purposes of my project I'd like it to only be saved while the server is online, and have everything fully reset when it's restarted/stopped/whatever.

A:

If you want this data be all same of all clients, then you can use
@Context
ServletContext servletContext;
Then, put the attribute there and fetch from this attribute on each invocation.

If you have some framework, like spring, then you can get/set value with its facilities.


Q:

Silverlight 4.0: HyperlinkButton

How to redirect your navigateuri of hyperlinkbutton to your isolatedstorage?
or
Is there a workaround to display data from isolatedstorage to new browser?

A:

You dont.
IsolatedStoratge is usable only by the API. You can no redirect the navigateurl to it.


Q:

Remove tr if it has not children - ng-repeat - angular

I'm trying to build tr inside a table using ng-repeat and I'm building it based on certain logic using row as value. This is introducing empty tr's how can I remove it ?
This code is adding 2 empty tr's at the end of tbody.
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

$scope.data = [
{
    "name" : "John",
    "row" : 1
},
 {
    "name" : "Mike",
    "row" : 2
},
 {
    "name" : "Bill",
    "row" : 1
},
{
    "name" : "Alice",
    "row" : 3
},
{
    "name" : "David",
    "row" : 2
}
 ]
 });

app.directive('specrow', ['$compile', function($compile) {
return {
  restrict: 'A',
    scope : {
      'specobj' : '=',
      'specitemindex' : '='
    },
    link: function (scope, elem, attrs){
      var template = "{{specobj.name}}	";
        var linkFn = $compile(template);
        var content = linkFn(scope);
        var trEl = angular.element(elem[0].parentElement.children).eq(scope.specobj.row-1);
        if(trEl.length === 0) {
          elem.append(content);
        }else{
          angular.element(elem[0].parentElement.children).eq(scope.specobj.row-1).append(content);
        }
    }
  }
}]);

Plnkr : http://plnkr.co/edit/I3kl9U41n3VzQvqFfG4G?p=preview

A:

So there is answer :)

var app = angular.module('app', ['angular.filter']);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.data = [
    {
        "name" : "John",
        "row" : 1
    },
     {
        "name" : "Mike",
        "row" : 2
    },
     {
        "name" : "Bill",
        "row" : 1
    },
    {
        "name" : "Alice",
        "row" : 3
    },
    {
        "name" : "David",
        "row" : 2
    }
  ]
});
table, th, td {
   border: 1px solid black;
}

          {{person.row}}.{{person.name}}


Q:

Explain Keyed Tuple output from SQLAlchemy ORM Query using Aliased

Please help me improve/understand queries using an aliased class. Consider an example with movement between two locations described as follows.
class Location(Base):
  __tablename__ = 'location'
  id = Column(Integer, primary_key = True)

class Movement(Base):
  __tablename__ = 'movement'
  id = Column(Integer, primary_key = True)
  from_id = Column(None, ForeignKey('location.id')
  to_id = Column(None, ForeignKey('location.id')

  from_location = relationship('Location', foreign_keys = from_id)
  to_location = relationship('Location', foreign_keys = to_id)

To join three tables in a query, I'm using the aliased() function from sqlalchemy.orm:
FromLocation = aliased(Location)
ToLocation = aliased(Location)

r = session.query(Movement, FromLocation, ToLocation).\
    join(FromLocation, Movement.from_id == FromLocation.id).\
    join(ToLocation, Movement.to_id == ToLocation.id).first()

First question is "What's the intelligent way to work with r?" The query returns a keyed tuple, but the only key is 'Movement', there's no 'FromLocation' as I would expect. I can get it with r[1], but that's easily broken.
Second question is "Did I put in the relationship right?" I didn't think I would have to specify the join target so explicitly. But without the targets specified, I get an error:
r = session.query(Movement, FromLocation, ToLocation).\
    join(FromLocation).\
    join(ToLocation)

InvalidRequestError: Could not find a FROM clause to join from.  Tried joining to <AliasedClass at 0x10cfa16d8; Location>, but got: Can't determine join between 'movement' and '%(4512717680 location)s'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

Yes, I see the two foreign keys, but how to map them correctly?

A:

Option-1: To have names in the KeyedTuple, just add names to the aliases:
FromLocation = aliased(Location, name="From")
ToLocation = aliased(Location, name="To")

# ...
print(r.keys)
# >>>> ['Movement', 'From', 'To']

Option-2: Create a query to return only Movement instance(s), but preload both locations. Please note also alternative join syntax by specifying relationship instead of key pairs.
r = (session.query(Movement)
        .join(FromLocation, Movement.from_location)
        .join(ToLocation, Movement.to_location)
        .options(contains_eager(Movement.from_location, alias=FromLocation))
        .options(contains_eager(Movement.to_location, alias=ToLocation))
    ).first()
print(r)
print(r.from_location)
print(r.to_location)


Q:

Change value of textarea when hovering link

I would like to change the value of a textarea when hovering over a link. I am not very proficient at javascript and do not quite understand the intricacies of 'this.' and 'document.' etc..
Currently I have a textarea 'info' that on page load is unpopulated and two links that should change its value. I can not seem to get it to work..
<textarea name="info"></textarea>
Foo.com
Bar.com
I'm sure there is a way to accomplish what I need to do but I can't find it.
Thanks in advance.

A:

Create a function, that accepts the string you want, and sets the textarea:
   // Select the textarea by its ID (that you need to give it)
var textarea = document.getElementById('info');

   // Define the function that sets the value passed
function changeTextarea( str ) {
    textarea.value = str;
}

Assign an ID to the textarea, and call the function in the onmouseover, passing the string you want to set:
<textarea name="info" id='info'></textarea>

Foo.com
Bar.com

Example: http://jsfiddle.net/nmZb9/


Q:

Joomla login page, if user is already logged redirect to home page

I think I'm missing something in the Joomla login behaviour.
I read a lot of post but can't find the answer of what I looking for.
Let's say you have login page (ie: yoursite.com/login), if you login, Joomla correctly brings you to the target page you choose.
The problem is :
if you then go back to the login page yoursite.com/login, the redirect doesn't work no more. In fact if you refresh the page the login fields vanish and all it remains is the logout button.
I tried
$user = JFactory::getUser();

if($user->id == 1)
{
// redirect here
}

I tried in Joomla 2.5 and 3.x, the behaviour is the same. Am I missing something?

A:

Because it's not the same layout.
If the user is guest, you are looking at the "default_login.php" layout, which - I gather - is the one you already modified.
But if the user is logged, you are looking at the "default_logout.php" layout, which you need to override as well.


Q:

Mutate a nummrec variable dependent of it´s quantity

I have this column in my data frame.
str(a)
 $ : int [1:2] 2 2
 $ : int [1:2] 0 3
 $ : int [1:2] 0 0
 $ : int [1:2] 0 0
 $ : int [1:2] 10 9

dput (a)
list(c(2L, 2L), c(0L, 3L), c(0L, 0L), c(0L, 0L), 10:9)

As you can see, every row consists two numbers. I want to create a new variable out of these in a new column.
The conditions are as follows:

If the first of the two numbers is greater than the second one -> -1
If the second number is greater than the first one -> +1
If both numbers are equal -> 0

So the result should look as follows:
      a (old variable) b (new variable)
1.    2 2              0
2.    0 3              1
3.    0 0              0
4.    0 0              0
5.   10 9             -1

I tried the following code but I got an error.
a %>% mutate(b = ifelese(sapply(a,'[[',1) == sapply(a,'[[',2), 0, ifelese(sapply(a,'[[',1) > sapply(a,'[[',2), -1, felese(sapply(a,'[[',1) < sapply(a,'[[',2), 1, NA))))

    Error in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "list"

Much appreciated!

A:

How about this:
sapply(a, function(x) sign(diff(x)))
#[1]  0  1  0  0 -1


Q:

missing ; before identifier while compiling VC6 code in VC9

The following code compiles fine in VC6 but when I compile the same project in VS2008 it gives the following error
error C2146: syntax error : missing ';' before identifier 'm_pItr'
template <class pKey, class Data, class pCompare,
          class hKey = int, class hCompare = less<hKey>,
          class sKey = int, class sCompare = less<sKey>,
          class tKey = int, class tCompare = less<tKey>,
          class cKey = int, class cCompare = less<cKey>>

class  GCache
{
    private:

        typedef map<pKey, Data, pCompare> PRIMARY_MAP;
        PRIMARY_MAP pMap;

        PRIMARY_MAP::iterator m_pItr; //error here

//Code truncated
}

Any ideas of what is wrong here? Someone with experience in migrating C++ code from VC6 to VC2005/2008 might be able to help.

A:

You may need to insert 'typename', to tell the compiler PRIMARY_MAP::iterator is, in all cases, a type.
e.g.
class  GCache
{
    private:

        typedef map<pKey, Data, pCompare> PRIMARY_MAP;
        PRIMARY_MAP pMap;

        typename PRIMARY_MAP::iterator m_pItr;

//Code truncated
}

A:

It should be typename PRIMARY_MAP::iterator m_pItr; . Otherwise compiler thinks that PRIMARY_MAP::iterator is a static object and will not be able to recognize it as a type. So you have to give an hint to the compiler indicating that it is a type and not a static object.


Q:

Can I set the VS Code default EOL based on file type?

Working with .sh files on Windows causes issues when running them in Linux Docker containers if they have EOL of CRLF. Can I make VS Code always work with LF for specific file type such as .sh while still using CRLF for all others?
I only find "files.eol": "\r\n" in settings, but this is global.
I understand you can change this in the bottom toolbar on a per-file basis, but I would like this to be the default for all .sh files.

A:

EDIT : I was a bit "premature" with this answer.  But it now works as of v1.40. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_40.md#fileseol-per-language

You can do this in vscode without an extension.  You can make a language-specific setting:
In the command palette, search for "Configure language specific", select it and choose "shellscript" from the language options:
This will create the following in your settings:
"[shellscript]": {

},

Now add in whatever you want to apply to shellscript files only like (not all settings will work in there but most do):
"[shellscript]": {
    "files.eol": "\n"
},

VERY, VERY IMPORTANT:

The end-of-line sequence is used for new files. For existing files,
  the existing end-of-line sequence is always preserved. To change the
  end-of-line sequence for an existing file, use the Change End Of Line
  Sequence command.

from https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_40.md#fileseol-per-language

A:

You can use EditorConfig.
Install the editorconfig extension, and then add a .editorconfig file at the root of your project with this:
[*]
end_of_line = crlf

[*.{sh}]
end_of_line = lf

But as @axiac said, I would recommend to always use lf...


Q:

Trying to pass Image from UICollectionView loaded from Firebase, to another VC

The problem i'm having is setting the image from my MainDetailVC to the image in the cell selected in my Main View controller. I keep getting a nil value for desVC.detailImage.image . If anyone has any tips, that would be awesome.
Still pretty new to swift so please excuse any ignorance on my end. lol
Thank you!
import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ImageCellDelegate {

@IBOutlet weak var popImageCollection: UICollectionView!
@IBOutlet weak var imageCollection: UICollectionView!

var customImageFlowLayout = CustomImageFlowLayout()
var popImageFlowLayout = PopImagesFlowLayout()
var images = [BlogInsta]()
var popImageArray = [UIImage]()
var homePageTextArray = [NewsTextModel]()

var dbRef: DatabaseReference!
var dbPopularRef: DatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()
    dbRef = Database.database().reference().child("images")
    dbPopularRef = Database.database().reference().child("popular")
    loadDB()
    loadImages()
    loadText()
    customImageFlowLayout = CustomImageFlowLayout()
    popImageFlowLayout = PopImagesFlowLayout()

    imageCollection.backgroundColor = .clear
    popImageCollection.backgroundColor = .white

    // Do any additional setup after loading the view, typically from a nib.
}
func loadText() {
    dbRef.queryOrdered(byChild: "order").observe(DataEventType.value, with: { (snapshot) in
        if snapshot.childrenCount > 0 {
            self.homePageTextArray.removeAll()
            for homeText in snapshot.children.allObjects as! [DataSnapshot] {
                let homeTextObject = homeText.value as? [String: AnyObject]
                let titleHome = homeTextObject?["title"]
                let categoryButtonText = homeTextObject?["category"]
                self.imageCollection.reloadData()
                let homeLabels = NewsTextModel(title: titleHome as! String?, buttonText: categoryButtonText as! String?)
                self.homePageTextArray.append(homeLabels)
            }
        }
    })
}
func loadImages() {
    popImageArray.append(UIImage(named: "2")!)
    popImageArray.append(UIImage(named: "3")!)
    popImageArray.append(UIImage(named: "4")!)

    self.popImageCollection.reloadData()
}
func loadDB() {
    dbRef.queryOrdered(byChild: "order").observe(DataEventType.value, with: { (snapshot) in
        var newImages = [BlogInsta]()
        for BlogInstaSnapshot in snapshot.children {
            let blogInstaObject = BlogInsta(snapshot: BlogInstaSnapshot as! DataSnapshot)
            newImages.append(blogInstaObject)
}
self.images = newImages
self.imageCollection.reloadData()
})

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.imageCollection {
       return images.count
    } else {
        return popImageArray.count
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == self.imageCollection {
   let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
        cell.delegate = self
        cell.contentView.backgroundColor = UIColor.clear
    let image = images[indexPath.row]
        let text: NewsTextModel
        text = homePageTextArray[indexPath.row]
        cell.categoryButton.setTitle(text.buttonText, for: .normal)
        cell.newTitleLabel.text = text.title
    cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "1"))
        return cell
    } else {
       let cellB = popImageCollection.dequeueReusableCell(withReuseIdentifier: "popCell", for: indexPath) as! PopularCollectionViewCell
        let popPhotos = popImageArray[indexPath.row]
        cellB.popularImageView.image = popPhotos
        cellB.popularImageView.frame.size.width = view.frame.size.width
            return cellB
    }

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let desVC = mainStoryboard.instantiateViewController(withIdentifier: "MainDetailViewController") as! MainDetailViewController
    let imageIndex = images[indexPath.row]

    let imageURLString = imageIndex.url
    print(imageURLString)
    let imageUrl:URL = URL(string: imageURLString)!
    let imageData: NSData = NSData(contentsOf: imageUrl)!
    let image = UIImage(data: imageData as Data)
    desVC.detailImage.image = image
    performSegue(withIdentifier: "toDetails", sender: self)

}

func MusicWasPressed() {
    performSegue(withIdentifier: "homeToMusic", sender: self)
}

func SneakersWasPressed() {
    performSegue(withIdentifier: "homeToSneakers", sender: self)
}

func RandomWasPressed() {
    performSegue(withIdentifier: "homeToRandom", sender: self)
}

func FashionWasPressed() {
    performSegue(withIdentifier: "homeToFashion", sender: self)
}
func EntertainmentWasPressed() {
    performSegue(withIdentifier: "homeToEntertainment", sender: self)
}

}

A:

The problem is that you don't pass it here
 performSegue(withIdentifier: "toDetails", sender: self)

you create a desVC without a push , and use a segue , Also don't do
let imageData: NSData = NSData(contentsOf: imageUrl)!

as it blocks the main thread i recommend sending the url of the image and load it there say with SDWebImage
//
First to clarify you have 2 options first is creating a desVC as you did and init it with sended parameters then push to self.navigationController OR use a segue When you use segues and want to send data to destination implement prepare(for segue , so refactor to
1-
 performSegue(withIdentifier: "toDetails", sender: imageURLString )

2-
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toDetails" {
       let nextScene = segue.destination as? MainDetailViewController {
          nextScene.imageURLString = sennder as! String
          nextScene.sendedTitle = self.sendedTitle
       }

    }
}

3- Don't access UI elements before the destinationVC is presented


Q:

The overlap of two Gaussian states

According to e.g. Serafini (Quantum Continuous Variables), the Hilbert-Schmidt product ('overlap') of two multimode Gaussian states $\rho_1,\rho_2$ is
$$\text{Tr}[\rho_1\rho_2]=|\langle\psi_1|\psi_2\rangle|^2=\frac{2^n}{\sqrt{\text{Det}(\sigma_1+\sigma_2)}}e^{(r_1-r_2)^T(\sigma_1+\sigma_2)^{-1}(r_1-r_2)},$$
where $r_{1,2}$ are the displacements in phase space and $\sigma_1,\sigma_2$ the covariance matrices.
My question: is there a similar formula for $\langle\psi_1|\psi_2\rangle$ itself, retaining information on their relative phase?

A:

There cannot be such an expression because the covariance matrix and displacement don't contain the relative phase information. This is easy to see, since they are computed from the reduced density matrix (which does not depend on the phase of the state).
A way around this can be to include a third reference state and $\vert\chi\rangle$ and consider the overlap
$$
\langle \psi_1|\psi_2\rangle\langle\psi_2\vert\chi\rangle\langle\chi\vert\psi_1\rangle
$$
which only depends on the density matrices, and is thus a function of the covariance matrices & displacement.
Note, however, that also this quantity is (necessarily!) invariant under changing phases, so whether it gives you the desired information depends on the scenario you consider.


Q:

How to break up excel spreadsheet into separate excel sheets separated by rows

Hi I have an excel spreadsheet with about 10,000 records and about 8 columns.  I would like to break up the excel spreadsheet into different spreadsheets containing data from 250 rows each.  So for example.
Spread sheet 1 would have 250 rows
Spread sheet 2 would have another 250 rows (251-500 from the original 10,000 list) and so on so forth until it's all completed.  It should also retain the original header on each spreadsheet.
Any one can help?

A:

This should work assuming data from A1:Z1000. Just change the range, workbook name and "save as" path as needed.
Sub generateSheets()

Dim sheetName As String
Dim headerRng As Range

Set headerRng = Workbooks("GenerateSheetsTest.xlsm").Worksheets("sheet1").Range("A1:Z1")

Application.ScreenUpdating = False

For i = 0 To 1000 Step 250
sheetName = "Until" & i + 250
Set NewBook = Workbooks.Add
headerRng.Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
Workbooks("GenerateSheetsTest.xlsm").Worksheets("sheet1").Range("A" & i + 2 & ":Z" & i + 251).Copy
NewBook.Worksheets("Sheet1").Range("A2").PasteSpecial (xlPasteValues)
NewBook.SaveAs fileName:="C:\Users\" & Environ$("username") & "\Documents\Output\" & sheetName & ".xlsx"
ActiveSheet.Range("A1").Select
ActiveWorkbook.Close True
Next i

Application.ScreenUpdating = True

End Sub


Q:

How to replace a specific line in a file with an argument with shell script?

I would like to replace a specific line in a text document using a configurable argument. Text document example:
DialogUpdateTags,
DialogProductNotFound
{
    width:                          1000;
    height:                         166;
}

In the example above I want to edit line 4 "1000" specifically so the script doesn't edit other width values that might also be 1000. So far I have this:
echo "Enter the desired width size in pixels"
read pixelsize
echo "Width size will be $pixelsize"

After that I need a sed command, can anyone help?
Is there a way to point SEP only to line 4 and not edit anything else?

A:

With GNU sed:
pixelsize="30"
sed -E "4s/(width: *)[^;]*/\1$pixelsize/" file

Output:

DialogUpdateTags,
DialogProductNotFound
{
    width:                          30;
    height:                         166;
}

If you want to edit your file "in place" use sed's option -i.


Q:

HTML link that forces refresh?

Is there a way to construct a link to a URL that forces the browser to ignore any cache it might have for that URL?
We have some websites that have recently changed after literally years of static content. Users click shortcuts, favorites, or type URL's to these sites and get old, cached content. I would like to have a page with a link that goes to the same URL but forces the browser to get the fresh content.
is that possible? Cross-browser?

A:

Change all the links to the page with a nonsense query parameter: products.html?happy=days
Change all the resources on the page to use another nonsense query parameter: style.css?the=fonz

You can do it in a systematic way using dates or timestamps or version numbers, or haphazardly using sitcoms, muppets, mountain ranges, and small mammals.

A:

Add a url parameter to the end of the href with a unique value, say new Date().getTime():
...somePage.html?time=123456789


Q:

Knockout partial validation of viewmodel

I am rather new to KockoutJS
But I have this working jsFiddle which validates.
But I would like to have a set of about 5 observables and validate that set.
It is meant as some sort of wizard and at each step a validation of the observables in that step.
I have read about validatedObservable but do I have to make a var for it outside the viewModel and then reference the observables in the viewmodel?
I found this as only reference and having difficulties understanding the grouping and validating with knockout validation.
Here is my JS code:
function ovm() {
    var self = this;
    this.delStreet = ko.observable("").extend( {required: true} );
    this.deliveryNotSameAsInvoice = ko.observable(false);
    this.invStreet = ko.observable('');
    this.delCountry = ko.observable("");
    var invStreetCheck = ko.computed(function(){
        var checked = self.deliveryNotSameAsInvoice(),
            delStreet = self.delStreet();
        if(!checked)
            return self.invStreet(delStreet);
        return self.invStreet();
    });
}

var vm = new ovm();
ko.applyBindings(vm);

$("#s1").click(function(){
    alert(vm.delStreet.isValid());
});

A:

Here's how I solved this problem for someone else.
It uses ValidatedViewModel from Carl Schroed and allows you to choose which validation options you want to apply - extremely handy for multi-step forms.


Q:

Make a living as a math programming freelancer?

I would like to know how the (job) market for operations research works. My dream would be to work as a freelancer in the area of math programming. I have a PHD and several years of proven experience in programming, modeling, bioinformatics, and optimization.
There are some blogs and websites by small companies or individuals working in this area, however they do not tell how they "made it".
Can one make a decent living outside the walls of a big consulting firm or software company?

A:

Here's what I've seen succeed from my experience.
0) Be comfortable with OR methods. I'm assuming this is a given for anyone who finds this stack exchange.
1) Know your markets. Some aspects of business need OR more than others. Operations management has had a lot in my experience (surprise). One buddy of mine took his clients from consulting and started his own practice doing procurement and network design. For the more technically inclined, I would think the same could happen if you sniffed around for work in planning, logistics, and scheduling. As you noted consulting firms play in this space because they're great at selling themselves. You can be too. Consulting firms can't match your rate if you're independent, and you would be amazed by the number of small to mid market firms who pay people full time to solve by hand the problems I mentioned above. Get out of your comfort zone and start going to networking events and see what people react to. Also, get on sites like upwork. My other most successful friend in OR consulting brought in all his gigs that way.
2) Kill your delivery. This could mean either being comfortable with financial analysis and powerpoint for more strategic projects or being a solid software developer for those more tactical. I think you should be good enough at both of those that you can get a job doing them alone. On the more tactical side of things, this is why you see software companies working in this space too because they're awesome at making OR methods super simple to use. If you're a decent developer though, you can deliver 80% of the value of a software company's product at 20% of the time and cost (and use some finance skills to prove it). I've seen people do this by writing their math models with an ORM (i.e. TicDat or SqlAlchemy) so you quickly get something with data constraints and few changes between dev and production environments. Additionally some background in web development can go a long way here. An API or a GUI will make it as easy as possible for someone else to consume your work.
3) Don't be afraid to jump. No one I've met doing this had a "right time" to start working independently. They worked contracts at night; they used their vacation to network; they left their full time gigs not knowing what their next contract would be 6 months from then. Worst case, you fail, you're out a little money, but you've gained a ton of experience. I think there are plenty of software companies and consulting firms who would hire you just on the story that you tried this, and they would help to show upon hiring you what skills you were missing in order to succeed.
4) Connect with us. Hit up the people on the websites you've seen. Ask them how they did it. You'd be surprised how many experienced professionals would be willing to help you if you have the humility to ask.
Best of luck and I hope this helps.

A:

I like Sean Kelly’s response.  I’ll just add a few points to this.
Over my career, I’ve worked in small to large firms, always close to OR.  And, I’ve run into quite a few people who have been successful at being a freelance math modeler—either I worked with them, they brought me into projects, or I brought them into projects.
Here are a few other observations of different ways of making it:

Some have used their experience in big consulting firms to build a
network and build the skills to go out on their own.  So, you could
go to a big firm with the goal of figuring it out so you can go out
on your own.
You have to be good at sales—getting projects to actually sign can be
time consuming and harder than you think.
Related, you need to be prepared to weather the time, and more
important, the lack of cash coming in, between projects.  This time
can seem memoryless when you are in it, and endlessly frustrating
waiting for prospects to move forward or surface.  Remember, when you
are really busy with a project, your pipeline and network will grow
cold.
Make sure you are ready for the other aspects of being a
freelancer—collecting money for the work you do (be ready for some
firms to be super slow in paying) and being able to manage
expectations and tricky situations (like a client who claims you
didn’t actually do what they wanted and isn’t paying)
Don’t put pressure on yourself to make it an all-or-nothing type of
career choice.  I’ve seen people who do this jump between short-term
projects, long-term projects (that look almost like a job), and even
taking employment with firms.


Q:

Community Promotion Ads - 2017

It is a bit late into this new year, being that we're already in the second month, but we are now cycling the Community Promotion Ads for 2017!
What are Community Promotion Ads?
Community Promotion Ads are community-vetted advertisements that will show up on the main site, in the right sidebar. The purpose of this question is the vetting process. Images of the advertisements are provided, and community voting will enable the advertisements to be shown.
Why do we have Community Promotion Ads?
This is a method for the community to control what gets promoted to visitors on the site. For example, you might promote the following things:

the site's twitter account
interesting chemistry research sites
useful resources for practitioner and student alike
cool events or conferences
anything else your community would genuinely be interested in

The goal is for future visitors to find out about the stuff your community deems important. This also serves as a way to promote information and resources that are relevant to your own community's interests, both for those already in the community and those yet to join.
Why do we reset the ads every year?
Some services will maintain usefulness over the years, while other things will wane to allow for new faces to show up. Resetting the ads every year helps accommodate this, and allows old ads that have served their purpose to be cycled out for fresher ads for newer things. This helps keep the material in the ads relevant to not just the subject matter of the community, but to the current status of the community. We reset the ads once a year, every December.
The community promotion ads have no restrictions against reposting an ad from a previous cycle. If a particular service or ad is very valuable to the community and will continue to be so, it is a good idea to repost it. It may be helpful to give it a new face in the process, so as to prevent the imagery of the ad from getting stale after a year of exposure.
How does it work?
The answers you post to this question must conform to the following rules, or they will be ignored.

All answers should be in the exact form of:
[![Tagline to show on mouseover][1]][2]

   [1]: http://image-url
   [2]: http://clickthrough-url

Please do not add anything else to the body of the post. If you want to discuss something, do it in the comments.
The question must always be tagged with the magic community-ads tag. In addition to enabling the functionality of the advertisements, this tag also pre-fills the answer form with the above required form.

Image requirements

The image that you create must be 300 x 250 pixels, or double that if high DPI.
Must be hosted through our standard image uploader (imgur)
Must be GIF or PNG
No animated GIFs
Absolute limit on file size of 150 KB
If the background of the image is white or partially white, there must be a 1px border (2px if high DPI) surrounding it.

Score Threshold
There is a minimum score threshold an answer must meet (currently 6) before it will be shown on the main site.
You can check out the ads that have met the threshold with basic click stats here.

A:

A:

A:


Q:

PyTorch broadcasting: how this worked?

I'm new to Deep Learning. I'm studying from Udacity.
I came across one of the codes to build up a neural network, where 2 tensors are being added, specifically the 'bias' tensor with the output of the tensor-multiplication product.
It was kind of...
def activation(x):
return (1/(1+torch.exp(-x)))

inputs = images.view(images.shape[0], -1)
w1 = torch.randn(784, 256)
b1 = torch.randn(256)
h = activation(torch.mm(inputs,w1) + b1)

After flattening the MNIST, it came out as [64,784] (inputs).
I'm not getting how the bias tensor (b1) of dimension [256], could be added to the multiplication product of 'inputs' and 'w1' which comes out to be the dimensions of [256, 64].

A:

In simple terms, whenever we use "broadcasting" from a Python library (Numpy or PyTorch), what we are doing is treating our arrays (weight, bias) dimensionally compatible.
In other words, if you are operating with W of shape [256,64], and your bias is only [256]. Then, broadcasting will complete that lacking dimension.

As you can see in the image above, the dimension left is being filled so that our operations can be done successfully. Hope this is helpful


Q:

Why I can't define inline member function in another file?

I have three files:
1. Joy.h
class Joy
{
public:
    void test();
};

2. Joy.cpp

#include "Joy.h"
inline void Joy::test() {}

3. main.cpp

#include "Joy.h"
int main()
{
    Joy r;
    r.test();
    return 0;
}

I try to compile them using:
g++ cpp Joy.cpp

g++ say:
main.cpp:(.text+0x10): undefined reference to `Joy::test()'

Who can tell me why...
How to solve this problem if I don't want to define that test() function in the .h file and still want it to be an inline function?

A:

when you define an inline member function, you should prepend the member function's definition with the keyword inline, and you put the definition into a header file.
When you declare a function inline basically You are telling the compiler to (if possible)replace the code for calling the function with the contents of the function wherever the function is called. The idea is that the function body is is probably small and calling the function is more overhead than the body of the function itself.
To be able to do this the compiler needs to see the definition while compiling the code which calls the function this essentially means that the definition has to reside in the header because the code which calls the function only has access to the header file.
Good Read:
[9.7] How do you tell the compiler to make a member function inline?

A:

The compiler needs the complete definition of the function so that it could be inlined where it is called from. That is possible only if you define it in the header itself.
How does inline function work?
Say, you define this:
 inline void increment(int &i) { ++i; }

and then use it as:
int i = 0;
while( i < N )
{
    std::cout << i << std::endl;
    increment(i);
}

then the compiler translates this code into this (roughly speaking):
int i = 0;
while( i < N )
{
    std::cout << i << std::endl;
    ++i; //replaced the call with the equivalent code which the function
         //actually executes to produce the same effect
         //(edit typo) it replaces to ++i and not i++ as it was the original.
}

Such replacement of function-call with the code of function itself is said to be inlined. You can say, the function is inlined.
Note that the inline keyword is just a hint for the compiler : it tells the compiler if possible inline me. It is not guaranteed that every inline function call will be inlined by the compiler.

A:

From the standard (N3242, 7.1.2.4):

An inline function shall be defined in every translation unit in which
  it is used and shall have exactly the same definition in every case.

Have a look here as well: How do you tell the compiler to make a member function inline?


Q:

is there a way to get the result of web3's encodeFunctionCall with ethers?

I'm using web3 to get the RLP encoded data for a function call like so
const safeTransferFrom: any = tokenERC1155Abi.find((f) => f.name === 'safeTransferFrom');
const params: Array<any> = [identity, minterAddr, 1, amount, '0x0'];
web3.eth.abi.encodeFunctionCall(safeTransferFrom, params);

is there a way to achieve the same result with the ethers.js library?

A:

The equivalent in ethers.js involves first creating an "interface" object and calling a method on that:
> let ABI = [ "function transfer(address to, uint amount)" ];
> let iface = new ethers.utils.Interface(ABI);
> iface.encodeFunctionData("transfer", [ <function_params> ])

Taken from here


Q:

A countale partially ordered set that has an uncountable number of maximal chains

I'm looking for a countable set S with a partial order < that has an uncoubtable number of  maximal chains. I had many ideas but non of then is correct (for example- S= natural numbers, "<" is division- a < b iff a|b. But I think that in this case the numebr of maximal chains is countable).
Thanks!

A:

Take $S$ to be the set of all finite binary strings, and say $a\lt b$ iff $a$ is a prefix of $b$. Then every infinite binary string defines a maximal chain in $S$, and there are uncountably many infinite binary strings.
You can picture this same example as an infinite binary tree, which has countably many nodes but uncountably many branches; here $a\lt b$ iff $a$ is an ancestor of $b$.


Q:

Trying to get script to not run if a cell is not blank

The code is relatively straight forward. if I click on a cell in L8:L98, and the cell is blank, then the cell has "T" put into it and the other relevant cells are emptied.
If Intersect(Target, Range("C7:C98")) Is Nothing And Not Intersect(Target, Range("L7:L98")) Is Nothing Then
    Application.EnableEvents = False
    With Intersect(Target, Range("L7:L98"))
        .Value = "T"
        .Offset(, 1).Resize(, Col).ClearContents
End With

My problem is that if a cell on the same row in the C column has data in it, I want the if statement to return false and skip it. I also tried the code with Intersect(target.offset(, -9)... and without the intersect. Neither have worked for me.

A:

As VBA doesn't short-circuit best to break you code into two IF tests (so the second condition isn't run needlessly):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("L7:L98")) Is Nothing Then
    If Len(Cells(Target.Row, "C")) = 0 Then
        Application.EnableEvents = False
            With Intersect(Target, Range("L7:L98"))
                .Value = "T"
                'presume you set Col elswehere?
                .Offset(, 1).Resize(, Col).ClearContents
            End With
        Application.EnableEvents = True
    End If
End If
End Sub