text:
Q: Could not write JSON: could not initialize proxy - no Session error I'm trying to create a REST service using spring and JackSon JSON.
My DAOImpl:
    @Override
    @SuppressWarnings("unchecked")
    public Users findByUserName(String username) {

        Users user = new Users();
        session = getSessionFactory().openSession();
        try {
            transaction = session.beginTransaction();
            if (!username.isEmpty() && username != null) {
                List<Users> users = new ArrayList<Users>();
                users = session.createQuery("from Users where username=?")
                        .setParameter(0, username)
                        .list();

                if (!users.isEmpty()) {
                    user = users.get(0);
                }

                transaction.commit();
            }
        } catch (HibernateException e) {

            if (transaction != null) {
                transaction.rollback();
            }

            e.printStackTrace();
        } finally {
            session.close();
        }

        return user;
    }

My Controller class:
    @RequestMapping(value = "/rest/userbyname/{username}",
            method = RequestMethod.GET,
            headers = "Accept=application/json")
    public Users findByUserName(@PathVariable("username") String username) {

        return userDao.findByUserName(username);
    }

And I'm getting this error:

HTTP Status 500 - Could not write JSON: could not initialize proxy -
  no Session (through reference chain:
  com.spring.example.entities.Users["roles"]->com.enclaveit.brea.entities.Roles_$$_jvstd4_2["role"]);
  nested exception is
  com.fasterxml.jackson.databind.JsonMappingException: could not
  initialize proxy - no Session (through reference chain:
  com.enclaveit.brea.entities.Users["roles"]->com.enclaveit.brea.entities.Roles_$$_jvstd4_2["role"])

As I understand because the session is closed in DAOImpl class so in the controller the session is no more, is it correct? When I try to comment the code line session.close(); then the web work fine, I can receive the Json. But it is dangerous when a session couldn't close, right?
Looking for best solution.
NOTE: If you need more information please tell me.
Thank you.
UPDATE:
Hibernate config file:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- MySQL data source -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://192.168.10.116:3306/brea" />
        <property name="username" value="root" />
        <property name="password" value="brea@123" />
        <property name="maxActive" value="-1"/>
    </bean>
    <!-- If request parameter "targetUrl" is existed, then forward to this url -->
    <!-- For update login form -->
    <bean id="savedRequestAwareAuthenticationSuccessHandler"
        class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <property name="targetUrlParameter" value="targetUrl" />
     </bean>
    <!-- Hibernate session factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>orm/Roles.hbm.xml</value>
                <value>orm/Users.hbm.xml</value>
                <value>orm/UsersInfo.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
            <prop key="hibernate.dialect">
                           org.hibernate.dialect.MySQL5Dialect
                        </prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="userDao" class="com.enclaveit.brea.dao.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="myUserDetailsService"
                class="com.enclaveit.brea.services.MyUserDetailsService">
        <property name="userDao" ref="userDao" />
    </bean>

    <tx:annotation-driven />

    <!-- MUST have transaction manager, using aop and aspects  -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="dataSource" ref="dataSource" />
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
        <tx:method name="get*" read-only="true" />
        <tx:method name="find*" read-only="true" />
        <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="userServicePointCut"
        expression="execution(* com.enclaveit.brea.services.*Service.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
    </aop:config>
</beans>

Error log:
com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.spring.example.entities.Users["roles"]->com.spring.example.entities.Roles_$$_jvstdf1_2["role"])
    com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
    com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
    com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:184)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:605)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
    com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1819)
    org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:241)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:207)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:193)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
    org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    com.spring.example.entities.Roles_$$_jvstdf1_2.getRole(Roles_$$_jvstdf1_2.java)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.get(BeanPropertyWriter.java:679)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:534)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
    com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1819)
    org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:241)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:207)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:193)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)

A: Adding the proxy annotation to the Entity class does the job.
@Entity @Table(name="Country") @Proxy(lazy = false) public class Country {}

A: The quickest solution is to first remove the session and transaction handling code from your service and simply replace it with @Transactional in your code (and <tx:annotation-driven /> in your configuration.
@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly="true")
public Users findByUserName(String username) {
    Session session = getSessionFactory().getCurrentSession();
    return (Users) session
                    .createQuery("from Users where username=?")
                    .setParameter(0, username)
                    .uniqueResult();
}

Also note that session should be scoped to the method NEVER store the Session as in instance variable. (Imagine what would happen if 10 current calls to findByUserName are made what would happen to the instance variable session).
In your configuration enable annotation driven transaction management. (Assuming you already have a HibernateTransactionManager definedn!).
<tx:annotation-driven />

Next add an OpenSessionInViewFilter to your request handling chain (i.e. register the filter in your web.xml or initializer when using java config).
<filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    <!-- Replace with hibernate3, hibernate4 or hibernate5 depending on the hibernate version one uses -->
</filter>

<filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <servlet-name>dispatcher</servlet-name> <!-- name of your DispatcherServlet -->
</filter-mapping>

A: Since you are working with Spring framework, make use of declarative transaction management instead of programmatic transactions.
I believe your Users entity has role property with lazy loading. Either you can change this to eager loading (not preferable) or in DAO method load the role information using getter user.getRole() before session close.


text:
Q: Object parameters in URL with angular ui-router I need to construct a state url based on an object. Basically I want this state:
{
  id: 1,
  f: {
    "5": [
      "1",
      "7"
    ],
    "7": [
      "3",
      "6"
    ]
  }
}

To be transformed into this url:
http://localhost/resource/1?f[5][]=1&f[5][]=7&f[7][]=3&f[7][]=6

How do I specify such a url pattern with the ui-router config and how do I transition to that state?
Edit: I wasn't really clear on how or why I wanted this.
The main idea is to create a filter for some data on a page. I'd like the users to be able to bookmark the page with their filters applied.
The specific format of the url is nothing I invented, it's the standard way to provide arrays in query parameters for PHP. PHP parses the query with parse_str(), like this:
php > parse_str('f[5][]=1&f[5][]=7&f[7][]=3&f[7][]=6', $arr);
php > var_dump($arr);
array(1) {
  ["f"]=>
  array(2) {
    [5]=>
    array(2) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "7"
    }
    [7]=>
    array(2) {
      [0]=>
      string(1) "3"
      [1]=>
      string(1) "6"
    }
  }
}

What I want to do is to call $state.go() with my filter parameters (something like the state object above) and make ui-router change the url and state to those parameters on this specific url format.
I'm open to suggestions if there is a better way to do this.

A: Use the "json" param type which encodes objects as json, or make a custom param type which encodes the way you describe.
.state("foo", { url: "/foo?{queryParam:json}" });

Or
var customType = {
  encode: encodeFn,
  decode: decodeFn
}
    $urlMatcherFactoryProvider.type("phpQuery", customType);

    .state("foo", { url: "/foo?{queryParam:phpQuery}" });

A: I am not sure why you would want your data to be sent along with url (you should use a service instead). But here's how you send parameters with the url to switch to different state. The 'parameter' below is the object you need to send:
In your controller which holds the object:
$scope.parameter = {//whatever object you want
};

In your routes:
app.config(function config($stateProvider) {
    $stateProvider.state("example",{
        url: "fooURL/bar=:parameter",
        controller: "FooCtrl as foo",
        templateUrl: "templates/foo.html"
    })
})

In your HTML from which you want to redirect:
<div ui-sref="example({bar: parameter})">

The controller which handles the new redirected state:
app.controller('FooCtrl', ['$scope', '$stateParams', function($scope, $stateParams) {
    $scope.bar = $stateParams.bar;
}])

I am sure you can tweak the code to your requirements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interpreting Spatio-Temporal Variograms I've got spatio-temporal disease data at the county/annual level for 2000-2014. I'm analyzing it to try to pull out temporal variations in disease incidence and was told that I should generate a spatio-temporal variogram. The variogram appears to show a relationship but I'm having a hard time finding out how to interpret the graph (which is attached).
Is this graph showing that disease rates 10-15 years apart are more strongly correlated at <100 km, 200 km, and 500km? and that the temporal correlation drops off sharply at around 8 years apart?
If I remember correctly, the lower the gamma, the greater the autocorrelation? I've looked for a guide on interpretation for a while now but all I can find are guides on how to generate models from this data.

A: A variogram is a measure of dissimilarity in space/time. The lower is the variogram value, the higher is the correlation between the two pairs of data points.
Thinking about spatio-temporal correlation simultaneously is often tricky. For exploratory analysis purpose, statisticians sometimes tend to separately think about the spatial variogram at zero-time lag and the temporal variogram at zero-spatial lag, which are the two line plots you see when you look at the figure from the front and side planes. Variograms often give you a rough estimate about how your space-time correlation looks like. However, accurate estimates are usually evaluated by fitting a covariance model to your data.
From the figure above, I can draw the following observations:

*

*There seems to exist a strong temporal correlation up to almost 8 years apart (which is what the statisticians call: temporal range), after which correlation starts to die out.

*There seems to exist a fairly spatial correlation up to 200 kms apart.

*Your data seems to exhibit (a nugget effect), meaning that the data is noisy, because the intercept of the spatial and temporal variograms should be zero if the data is perfectly non-noisy. But in your case, the temporal variogram and spatial variograms have non-zero values for the intercepts.

*From the wigly look of the space-time surface, I might conclude that your data seems to exhibit some spatial-temporal interaction, which might support the argument of fitting a non-separable covariance model to the data, rather than separable models.


text:
Q: How can we Export data from Web Published Reports I have published an application that i did with power Bi, for some charts I want to make data downloadable for users.
I couldn't find any straight forward way to do that, some sites talk about implementing a script for that.
Is there any real way for published application that works?

A: One of the limitations of Publish to web is the inability to export data:

*

*Reports using row level security.

*Reports using any Live Connection data source, including Analysis Services Tabular  hosted on-premises, Analysis Services Multidimensional, and Azure Analysis Services.

*Reports shared to you directly or through an organizational content pack.

*Reports in a group in which you are not an edit member.

*"R" Visuals are not currently supported in Publish to web reports.

*Exporting Data from visuals in a report, which has been published to the web

*ArcGIS Maps for Power BI visuals.

*Reports containing report-level DAX measures.

*Single sign-on data query models.

*Secure confidential or proprietary information.

*The automatic authentication capability provided with the Embed option doesn't work with the Power BI JavaScript API. For the Power BI JavaScript API, use the user owns data approach to embedding. Learn more about user owns data.

Exporting data is possible, if you publish your report in Power BI Online and share it with your colleagues. But keep in mind, that even in this case it may not be possible or allowed, due to these limitations, e.g. if it has been disabled, or the user doesn't have enough permissions. In addition, it has limits on maximum columns, rows and data size.
The best option is to export the data directly from the data source, which is used to build this report.


text:
Q: Spinner's entries are too long I have a spinner in my android application with more than 100 options... Is there a way for the user to go to one letter faster than scrolling the spinner down? Like in a website select you enter one letter with the keyboard ("p" for example) and you go straight to options startin with letter "p"...
Thanks in advance

A: Why not use a AutoCompleteTextView. Check this sample code.


text:
Q: Dynamically replace matched special characters I have a special character file (with list of special characters). I have to read that file and check if the incoming request has any of the special character, if so: replace that with constant else: move it as is
in xslt 1.0 Tried with below code.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:regex="http://exlt.or/regular-expressions">
  <xsl:output method="xml" indent="yes"/>
  <xsl:variable name="charfile" select="document('chars.xml')"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:call-template name="checkAndReplace">
      <xsl:with-param name="text" select="."/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="checkAndReplace">
    <xsl:param name="text"/>
    <xsl:for-each select="$charfile/chars/char">
      <xsl:if test="contains($text,./value/text())">
        <xsl:copy-of select="translate($text,./value/text(),'*')"/>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

chars.xml :
<?xml version="1.0" encoding="utf-8"?>
<chars>
  <char>
    <value>@#128;</value>
  </char>
  <char>
    <value>@#129;</value>
  </char>
  <char>
    <value>@#130;</value>
  </char>
</chars>

INPUT:
<?xml version="1.0" encoding="utf-8"?>
<root>
  <child1>abc@#128;</child1>
  <child2>def@#129;</child2>
  <child3>hello</child3>
</root>

Output Required:
<?xml version="1.0" encoding="utf-8"?>
<root>
  <child1>abc*</child1>
  <child2>def*</child2>
  <child3>hello</child3>
</root>

A: Assuming that the file listing special characters should actually look like this:
chars.xml
<chars>
  <char>
    <value>€</value>
  </char>
  <char>
    <value>�</value>
  </char>
  <char>
    <value>‚</value>
  </char>
</chars>

you could use the following stylesheet:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="charfile" select="document('chars.xml')"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:variable name="search-chars">
    <xsl:for-each select="$charfile/chars/char">
        <xsl:value-of select="value"/>
    </xsl:for-each>
</xsl:variable>

<xsl:variable name="replace-chars">
    <xsl:for-each select="$charfile/chars/char">
        <xsl:text>*</xsl:text>
    </xsl:for-each>
</xsl:variable>

<xsl:template match="text()">
    <xsl:value-of select="translate(., $search-chars, $replace-chars)"/>
</xsl:template>

</xsl:stylesheet>

Given an input of:
XML
<root>
  <child1>abc€</child1>
  <child2>def�</child2>
  <child3>hello</child3>
</root>

the output will be:
Result
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child1>abc*</child1>
  <child2>def*</child2>
  <child3>hello</child3>
</root>


text:
Q: Gson not able to parse Array. But it is json array I have the following json string:
{"objKampfEntry":[{"deffSpielerId":"9","kampfId":"7","offSpielerId":"10","rundeCounter":"0","rundenList":[{"deffIsReady":"0","deffMove":"0","deffSpieler":{"ausdauer":"5","eiId":"0","gesichtId":"normal","helm":"0","id":"13","kraft":"6","leben":"12","lebenMax":"50","level":"1","name":"Test","niederlagen":"0","punkte":"1","rang":"1","rustung":"0","siege":"0","timestamp":"1397385595686","waffe":"0"},"done":"0","kampfId":"7","offIsReady":"1","offMove":"0","offSpieler":{"ausdauer":"5","eiId":"0","gesichtId":"normal","helm":"0","id":"14","kraft":"6","leben":"12","lebenMax":"50","level":"1","name":"Test2","niederlagen":"0","punkte":"1","rang":"1","rustung":"0","siege":"0","timestamp":"1397385841118","waffe":"0"},"rundeNr":"0","winner":"0"}]}]}

If I use
Gson gson = new Gson();
Type listOfKampfEntry = new TypeToken<List<ObjKampfEntry>>(){}.getType();
ArrayList<ObjKampfEntry> list = gson.fromJson(json, listOfKampfEntry);

I get this error:
04-13 12:45:48.706: W/System.err(4411): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
04-13 12:45:48.706: W/System.err(4411):     at com.google.gson.Gson.fromJson(Gson.java:815)
04-13 12:45:48.706: W/System.err(4411):     at com.google.gson.Gson.fromJson(Gson.java:768)
04-13 12:45:48.706: W/System.err(4411):     at com.google.gson.Gson.fromJson(Gson.java:717)

So I have an array of objKampfEntry and inside an array of rundenList. What am I doing wrong?
My ObjKampfEntry class:
public class ObjKampfEntry {

    private long kampfId;
    private long offSpielerId;
    private long deffSpielerId;

    private int rundeCounter;

    private ArrayList<Runde> rundenList = new ArrayList<Runde>();
    //constructor and getter/setter

}

And the runde object
public class Runde {

    private long kampfId;
    private long winner;
    private int rundeNr;
    private int offIsReady;
    private int deffIsReady;
    private int done;
    private Spieler offSpieler;
    private Spieler deffSpieler;
    private int offMove;
    private int deffMove;
...

Here the Spieler object
public abstract class ACharakter {

    protected long id;
    protected String name;
    protected int leben;
    protected int lebenMax;
    protected int kraft;
    protected int ausdauer;

public class Spieler extends ACharakter {

    private int rang;
    private int level;
    private int punkte;
    private long timestamp;
    private int waffe;
    private int rustung;
    private int helm;
    private int siege;
    private int niederlagen;
    private int eiId;
    private String gesichtId;

A: Your input is not a JSON array of ObjKampfEntry objects. Instead, it is a JSON object with one key/value pair whose value is a JSON array of ObjKampfEntry objects.
The "correct" input according to your scheme would be [{"deffSpielerId":"9","kampfId":"7",...}], as that will indeed map to a List<ObjKampfEntry>. If you can't change the input, then you'll need another class holding one field named objKampfEntry of type List<ObjKampfEntry>:
public class ObjKampfEntries {

    private ArrayList<ObjKampfEntry> objKampfEntry = new ArrayList<ObjKampfEntry>();

}

ObjKampfEntries entries = gson.fromJson(json, ObjKampfEntries.class);
List<ObjKampfEntry> list = entries.objKampfEntry;


text:
Q: How to run a jar file in command line which is packaged in another jar file? In my java code, I run a jar file (named file1.jar) from the command line like this:
process = Runtime.getRuntime().exec("cmd /c java -jar file1.jar");

If I package the whole project into a jar file (named file2.jar), then the command is invalid because of path problems. How can I solve this problem?


text:
Q: Windows NLB failover based on event ID? Is NLB capable of doing a failover once a specific event ID is triggered (Event ID 1000 application crash)?
If not, are there software that is capable of detecting application fault tolerance?


text:
Q: How can I run background task in node.js I saw that I could run background tasks by using nohup node index.js.
My problem is related with following source.
https://github.com/Palpasa/Node-Express-Seed.
In this source, package.json file contains nodemon and it is working when I start the server with npm start.
For now, I tried to run the server in background.
But it is crashing with following error.
[nodemon] 1.14.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`
/home/tom/Documents/work/wallet/app/app.js:3
import bodyParser from 'body-parser';
^^^^^^

SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
[nodemon] app crashed - waiting for file changes before starting...

How can I run this server in background?

A: You can run several screens on your putty.
screen
Then you will have one screen.
You can now run your node instance on this screen.
This screen is alive all the time.
Type CTRL+A+D to go out of the screen.
Your node instance is now always alive even you quit putty.

A: Child Process is what you would want to use.
const { spawn } = require('child_process');
const otherScript = spawn('node', ['script-you-wanna-run.js']);

otherScript.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

A: You probably need to use ES-2015 babel preset to transpile the import statements. If you don't need the ES6 import specifically, just use require
var bodyParser = require("body-parser")

On another note you can try using Forever npm package. This let's you start the node server in the background
FOREVER
npm install -g forever
forever start server.js

// To run on a custom po
PORT=3000 forever start server.js

A: You cannot run nodemon in the background (i.e nohup npm start <=> nohup nodemon app.js), nodemon supposed to be used for development environment, it let you see what changes are made on files during development, if you are looking for running express app in production, Then you should use a process manager, it restarts the app automatically when it crashes, or when changes are made, read this article for more information. Here is an example using pm2 module:
Install pm2:
npm install pm2 -g

Run app:
pm2 start app.js


text:
Q: SQL Server: How can I select all result of table when condition is FALSE? I got a trouble in stored procedure:
SELECT * FROM TESTTABLE
WHERE COUNT = CASE WHEN (@count = -1) THEN --SELECT ALL RESULT OF TESTTABLE--
ELSE @count END

When param @count is not equal -1, I want that query is the same with:
SELECT * FROM TESTTABLE

I tried with
SELECT * FROM TESTTABLE
WHERE COUNT = CASE WHEN (@count <> -1) THEN @count END

But it's not true.

A: Since it's a stored procedure, the best performance should come using 2 different queries:
if @count <> -1
  SELECT * FROM TESTTABLE
else
  SELECT * FROM TESTTABLE WHERE COUNT=@count

A: Since you are using a stored procedure you can use an if statement.  Something like:
IF @Count <> -1
BEGIN
   Select * From TestTable
END
ELSE
BEGIN
    Select * From TestTable Where 1=0
END

A: SELECT * FROM TESTTABLE WHERE COUNT=@count OR @count = -1


text:
Q: horizontal scrolling level select Ok so i have a good chunk of my game finished now and Im working on my level select view. I want to implement a horizontal scroll view with multiple buttons on each view, in something that looks like Angry Birds or Cut The Rope, or something like that. I know I use a scroll view and set anchor points from my reading on here and other sites but im not sure exactly how i can implement that. Im a bit of a noob and my game didnt need to implement any real graphics so im not familiar with open gl or quartz, although im not afraid to try to learn it.
Anyone know how i can implement anchor points in a horizontal scroll view for my level select view?
Thanks!

A: As already answered, you have to use UIScrollView. We use scroll view when our contents are too large to be shown on the screen.
Refer the class reference here and Some links that could hep you.
Apple's scrolling demo
Understanding Scrollview


text:
Q: import heavy excel to mysql using php I am having excel sheet which contains data in something like this ex. if sheet has  "city" and  "person name" columns.So every time we need to check whether the city exists in city table(mysql) or not if not then new row will be  inserted for city in city table similarly will check for person name also if don't exists in person table(mysql) then we need to save person name in person table .
So what can be the best way to import heavy excel file of  2gb atleast into mysql using php in the above explained scenario so that less queries will be executed with  less load on server and execution will be done in fraction of seconds.
Kindly suggest me the optimize solution for above scenario.

A: For high speed ingestion that needs to "normalize" the data as it goes, do it in two steps (after loading the raw data into a temp table):
First, add the new values (of host_name in this example):
# This should not be in the main transaction, and it shoud be with autocommit = ON
# In fact, it could lead to strange errors if this were part of the main transaction and it ROLLBACKed.
INSERT IGNORE INTO HostNorm (host_name)
    SELECT DISTINCT s.host_name
        FROM Staging AS s
        LEFT JOIN HostNorm AS n  ON n.host_name = s.host_name
        WHERE n.host_id IS NULL;

Then grab the host_id for putting into the Fact table:
# Also not in the main transaction, and it should be with autocommit = ON
# This multi-table UPDATE sets the ids in Staging:
UPDATE   HostNorm AS n
    JOIN Staging AS s  ON s.host_name = n host_name
    SET s.host_id = n.host_id

More discussion in my blog


text:
Q: What is the partition id / filesystem type for UDF? This is probably trivial to check using cfdisk on a UDF-formatted CD/DVD/Blu-Ray, but I have neither of them at hand.
I have created an UDF formatted partition on a USB hard drive to share data between Linux and Windows computers (FAT doesn't handle 4GB files, NTFS access rights support is not stable under Linux). I have only one problem now - Windows refuses to mount the partition as the file system type id is set to '83' ('Linux'). I have looked quite extensively and can not find what number should I put there?
(follow-up: "With what tool should I format a hard drive as UDF?")

A: It turns out there is no partition table for UDF and there is no partition ID assigned to it. This filesystem has to span the whole disk in oder to be recognized by Windows. Formatting a hard drive as UDF does not touch the existing partition table (be careful - it will contain stale information, and if you mount your drive using it, you will destroy the data!).
As a curiosity - UDF 2.5 and newer creates separate partitions (one or two per disk) for metadata. However, those partitions are also not visible in the standard DOS partition table.

A: Short answer: I would suggest to use MBR id 0x07 for UDF partitions.

Long answer:
Linux does not care about MBR partition ids and ignores it (*).
Windows 2000 and newer can assign a drive letter to the some partition with id PartitionType if and only if IsRecognizedPartition(PartitionType) is true. Moreover for non-FT partitions must hold that IsFTPartition(PartitionType) is false (otherwise that partition is detected as FT and not as ordinary FAT/NTFS/UDF/...).
Condition IsRecognizedPartition(PartitionType) && !IsFTPartition(PartitionType) apply for these MBR partition ids: 0x01, 0x04, 0x06, 0x07, 0x0B, 0x0C, 0x0E (**). Which means that Windows 2000 (and new) can recognize and use UDF partition if MBR partition id is one of those. There are probably no other restrictions and any supported file system accepts partition with any of those MBR id. Which means those MBR ids are not used for detection of file system.
But there are some recommendation by Microsoft when particular PartitionType should be used:

*

*0x01 - FAT12 primary partition or logical drive (fewer than 32,680 sectors in the volume)

*0x04 - FAT16 partition or logical drive (32,680–65,535 sectors or 16 MB–33 MB)

*0x06 - BIGDOS FAT16 partition or logical drive (33 MB–4 GB)

*0x07 - Installable File System (NTFS partition or logical drive)

*0x0B - FAT32 partition or logical drive

*0x0C - FAT32 partition or logical drive using BIOS INT 13h extensions (***)

*0x0E - BIGDOS FAT16 partition or logical drive using BIOS INT 13h extensions (***)

And also meaning by Microsoft:

*

*0x01 - Specifies a partition with 12-bit FAT entries.

*0x04 - Specifies a partition with 16-bit FAT entries.

*0x06 - Specifies an MS-DOS V4 huge partition.

*0x07 - Specifies an IFS partition.

*0x0B - Specifies a FAT32 partition.

*0x0C - Windows 95/98: Specifies a partition that uses extended INT 13 services.

On Wikipedia can be found also some recommendations:

*

*0x01 - CHS/LBA - DOS 2.0+ - FAT12 as primary partition in first physical 32 MB of disk ... (else use 0x06 instead)

*0x04 - CHS/LBA - DOS 3.0+ - FAT16 with less than 65536 sectors (32 MB) ... (else use 0x06 instead)

*0x06 - CHS/LBA - DOS 3.31+ - FAT16B with 65536 or more sectors. It must reside in first physical 8 GB of disk ... (else use 0x0E instead). Also used for FAT12 and FAT16 volumes in primary partitions if they are not residing in first physical 32 MB of disk.

*0x07 - CHS/LBA - OS/2 1.2+, Windows NT/CE - IFS/HPFS/NTFS/exFAT/QNX

*0x0B - CHS/LBA - DOS 7.1+ - FAT32 with CHS addressing

*0x0C - LBA - DOS 7.1+ - FAT32 with LBA

*0x0E - LBA - DOS 7.0+ - FAT16B with LBA

To complete list of ids, here is some information about older systems which do not support UDF formatted hard disk partition.
Windows NT 4.0 and older can assign a drive letter only to partitions with MBR id: 0x01, 0x04, 0x06, 0x07.
DOS-based Windows (95, 98 and ME) can assign a drive letter only to partitions with MBR ids: 0x01, 0x04, 0x06, 0x0B, 0x0C, 0x0E. MS-DOS itself can access only partitions with MBR ids: 0x01, 0x04, 0x06. Note that these systems uses MBR partition id for detection of file system. MBR partition id must match with file system on partition.
Conclusion:
Look at partition size: 0x01 and 0x04 should be used only for partitions in first 32MB of disk. 0x06 only in first 8GB of disk. 0x0B is for CHS addressing which has limit for 8GB disks. So without such limits are only ids: 0x07, 0x0C and 0x0E. As 0x0C and 0x0E are used for FAT partitions I would suggest to choose 0x07. It is mean for IFS (Installable File System) partitions and according to Wikipedia, Microsoft added support for UDF into Windows 2000 IFS API. Usage of 0x0C or 0x0E would cause DOS-based systems to show that partition as FAT, even it would be formatted as UDF. Partitions with MBR id 0x07 are hidden on those systems. They do not support UDF, therefore it is better choice as 0x0C or 0x0E.
GPT:
GPT partition layout is out of of this question, but it has similar problem as MBR. There is no partition GUID (GPT equivalent for MBR id) assigned for UDF. Because Windows XP x64 supports UDF and can recognize GPT data partition only with GUID EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 (Microsoft Basic Data Partition), it is the only possible choice for GPT.
Sources:

*

*https://technet.microsoft.com/en-us/library/cc976786.aspx

*https://technet.microsoft.com/en-us/library/cc768180.aspx

*https://technet.microsoft.com/en-us/sysinternals/ff563751

*https://technet.microsoft.com/en-us/sysinternals/aa363990

*https://www.microsoft.com/resources/documentation/windowsnt/4/server/reskit/en-us/resguide/diskover.mspx

*https://en.wikipedia.org/wiki/Partition_type

*https://en.wikipedia.org/wiki/Installable_file_system

*File Ntdddisk.h (part of WinDDK)

*File WinIoCtl.h (part of WinSDK)

(*) There is one exception: MBR Ids 0x05, 0x0F and 0x85 are used for detection of extended MBR partitions.
(**) Definitions of those two calls can be found in WinIoCtl.h file as they are declared as C macros.
(***) BIOS INT 13h extensions means usage of LBA instead CHS.

A: On the CD's and DVD's I deal with, there is no partition table.  On your USB hard drive,
you've written a partition table to the media.  I suspect if you format the entire drive
as a UDF disk without the partition table, Windows will have no problem mounting it.
You don't say what size your USB drive is, and you might be reluctant to dedicate the
whole drive as UDF, you could try setting the partition type with fdisk as NTFS or one of the
other MS 'supported' types.

A: The answer is partition type 06 (FAT16). Don't ask me why, ask Microsoft.

A: I have got the same problem. My USB hard disk is 320GB. Partition table looks like this:
Disk /dev/sda: 320.0 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x44fdfe06

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1       27963   224612766    c  W95 FAT32 (LBA)
/dev/sda2           27964       38913    87955875    5  Extended
/dev/sda5           27964       33366    43399566    7  HPFS/NTFS
/dev/sda6           33367       38913    44556246   83  Linux

Partition sda5 is a UDF rev. 1.5 and shoulb be readable by Windows XP and above. Linux reads it properly of course. Windows however is confused. It recognise partition as NTFS and then it assumes it is raw partition.
My experiment with UDF on pendrive showed me that systems tend to mistake UDF with FAT. They interpret UDF as FAT. It must be quite large similarities because i can see directory stucture of random characters. Linux says that disk is corrupted but it don't refuse to use it.
I think UDF (at least rev 1.5) is not well supported on USB drives.


text:
Q: How to see file history, stashes etc. on source control panel in VS Code I would like to see file history, stashes etc. on my source control panel like below image. How is it possible? By the way, my system is Mac OS
Currently I see only Changes Section

Image Reference

A: Installing Git Lens extension in VS Code worked for me.

A: Right-click on the top level headline (should be "Source Control" for the Changes section). This will show a menu from which all the displayed sections can be selected:


text:
Q: In TypeScript, how to get the keys of an object type whose values are of a given type? I've been trying to create a type that consists of the keys of type T whose values are strings. In pseudocode it would be keyof T where T[P] is a string.
The only way I can think of doing this is in two steps:
// a mapped type that filters out properties that aren't strings via a conditional type
type StringValueKeys<T> = { [P in keyof T]: T[P] extends string ? T[P] : never };

// all keys of the above type
type Key<T> = keyof StringValueKeys<T>;

However the TS compiler is saying that Key<T> is simply equal to keyof T, even though I've filtered out the keys whose values aren't strings by setting them to never using a conditional type.
So it is still allowing this, for example:
interface Thing {
    id: string;
    price: number;
    other: { stuff: boolean };
}

const key: Key<Thing> = 'other';

when the only allowed value of key should really be "id", not "id" | "price" | "other", as the other two keys' values are not strings.
Link to a code sample in the TypeScript playground

A: As a supplementary answer:
Since version 4.1 you can leverage key remapping for an alternative solution (note that core logic does not differ from jcalz's answer). Simply filter out keys that, when used to index the source type, do not produce a type assignable to the target type and extract the union of remaining keys with keyof:
type KeysWithValsOfType<T,V> = keyof { [ P in keyof T as T[P] extends V ? P : never ] : P };

interface Thing {
    id: string;
    price: number;
    test: number;
    other: { stuff: boolean };
}

type keys1 = KeysWithValsOfType<Thing, string>; //id -> ok
type keys2 = KeysWithValsOfType<Thing, number>; //price|test -> ok

Playground

As rightfully mentioned by Michal Minich:

Both can extract the union of string keys. Yet, when they should be used in more complex situation - like T extends Keys...<T, X> then TS is not able to "understand" your solution well.

Because the type above does not index with keyof T and instead uses keyof of the mapped type, the compiler cannot infer that T is indexable by the output union. To ensure the compiler about that, one can intersect the latter with keyof T:
type KeysWithValsOfType<T,V> = keyof { [ P in keyof T as T[P] extends V ? P : never ] : P } & keyof T;

function getNumValueC<T, K extends KeysWithValsOfType<T, number>>(thing: T, key: K) {
    return thing[key]; //OK
}

Updated Playground

A: This can be done with conditional types and indexed access types, like this:
type KeysMatching<T, V> = {[K in keyof T]-?: T[K] extends V ? K : never}[keyof T];

and then you pull out the keys whose properties match string like this:
const key: KeysMatching<Thing, string> = 'other'; // ERROR!
// '"other"' is not assignable to type '"id"'

In detail:
KeysMatching<Thing, string> ➡

{[K in keyof Thing]-?: Thing[K] extends string ? K : never}[keyof Thing] ➡

{
  id: string extends string ? 'id' : never;
  price: number extends string ? 'number' : never;
  other: { stuff: boolean } extends string ? 'other' : never;
}['id'|'price'|'other'] ➡

{ id: 'id', price: never, other: never }['id' | 'price' | 'other'] ➡

'id' | never | never ➡

'id'

Note that what you were doing:
type SetNonStringToNever<T> = { [P in keyof T]: T[P] extends string ? T[P] : never };

was really just turning non-string property values into never property values. It wasn't touching the keys.  Your Thing would become {id: string, price: never, other: never}.  And the keys of that are the same as the keys of Thing.  The main difference with that and KeysMatching is that you should be selecting keys, not values (so P and not T[P]).
Playground link to code


text:
Q: R bibliometrix package's thematicmap formatting I am trying to do bibliometrix analysis of articles using the bibliometrix package for R programming language. I have been able to extract the keywords from articles and everything works well using the code below. However, when I try to output the keyword cluster using the thematic map function, some of the keywords are overlayed on there. Is there a way to let each text display separately either from the network plot function or from the thematic map plots? See code and plots below
 NetMatrix <- biblioNetwork(M, analysis = "co-occurrences", network = "author_keywords", sep = ";")

S <- normalizeSimilarity(NetMatrix, type = "association")
net <- networkPlot(S, n = 200, Title = "co-occurrence network",type="fruchterman", labelsize = 0.7, halo = FALSE, cluster = "walktrap",remove.isolates=FALSE, remove.multiple=FALSE, noloops=TRUE, weighted=TRUE)

res <- thematicMap(net, NetMatrix, S)
plot(res$map)

The thematicmap plot is presented below
As you can see, the texts to the bottom left side are not legible and overriding each other. Your help is appreciated.
Thanks

A: One possible solution:
thematicMap(M, field = "ID", n = 250, minfreq = 5, stemming = FALSE, size = 0.5, n.labels = 1, repel = TRUE)

Change the size parameter


text:
Q: Linearly independent rows and matrices $2$ True or false: If $A$ has linearly independent rows then it forms a basis for $\text{Row}(A)$?

A: Hint: $\mbox{Row} A$, the row space of $A$, is the space spanned by the rows (considered as vectors) so the set of the row vectors spans the row space by definition! When do you call a set a basis...?

A: Considering the matrix $A \in R^{nxn}$ and you have $n$ linearly independent rows then the rows form a basis for the $R^n$ space. If this is the case then you are right.

A: The statement as written is false. The matrix $A$ does not (and cannot) be a basis for its row space. On the other hand, the rows of $A$, considered as vectors, if linearly independent do form a basis for the row space.
If this is exactly as the problem was posed to you, then perhaps it's a trick question designed to test your understanding of the nuances of these definitions.


text:
Q: How do I create a PHP static class property at runtime (dynamically)? I'd like to do something like this:
public static function createDynamic(){
    $mydynamicvar = 'module';
    self::$mydynamicvar = $value;
}

and be able to access the property from within the class with
$value = self::$module;

A: static variables must be part of the class definition, so you can't create them dynamically. Not even with Reflection:

chuck at manchuck dot com                                             2 years ago

It is important to note that calling ReflectionClass::setStaticPropertyValue will not allow you to add new static properties to a class.

But this looks very much like a XY Problem. You probably don't really want to add static properties to a PHP class at runtime; you have some use case that could be fulfilled also that way. Or that way would be the fastest way, were it available, to fulfill some use case. There well might be other ways.
Actually the use cases below are yet again possible solutions to some higher level problem. It might be worth it to reexamine the high level problem and refactor/rethink it in different terms, maybe skipping the need of meddling with static properties altogether.
I want a dictionary of properties inside my class.
trait HasDictionary {
    private static $keyValueDictionary = [ ];

    public static function propget($name) {
        if (!array_key_exists($name, static::$keyValueDictionary) {
            return null;
        }
        return static::$keyValueDictionary[$name];
    }

    public static function propset($name, $value) {
        if (array_key_exists($name, static::$keyValueDictionary) {
            $prev = static::$keyValueDictionary[$name];
        } else {
            $prev = null;
        }
        static::$keyValueDictionary[$name] = $value;
        return $prev;
    }
}

class MyClass
{
    use Traits\HasDictionary;

    ...$a = self::propget('something');

    self::propset('something', 'some value');
}

I want to associate some values to a class, or: I want a dictionary of properties inside some one else's class.
This actually happened to me and I found this question while investigating ways of doing it. I needed to see, in point B of my workflow, in which point ("A") a given class had been defined, and by what other part of code. In the end I stored that information into an array fed by my autoloader, and ended up being able to also store the debug_backtrace() at the moment of class first loading.
// Solution: store values somewhere else that you control.

class ClassPropertySingletonMap {
    use Traits\HasDictionary; // same as before

    public static function setClassProp($className, $prop, $value) {
        return self::propset("{$className}::{$prop}", $value);
    }

    public static function getClassProp($className, $prop) {
        return self::propget("{$className}::{$prop}");
    }
}

// Instead of
// $a = SomeClass::$someName;
// SomeClass::$someName = $b;

// we'll use
// $a = ClassPropertySingletonMap::getClassProp('SomeClass','someName');
// ClassPropertySingletonMap::setClassProp('SomeClass','someName', $b);

I want to change, not create, an existing property of a class.
// Use Reflection. The property is assumed private, for were it public
// you could do it as Class::$property = $whatever;

function setPrivateStaticProperty($class, $property, $value) {
    $reflector = new \ReflectionClass($class);
    $reflector->getProperty($property)->setAccessible(true);
    $reflector->setStaticPropertyValue($property, $value);
    $reflector->getProperty($property)->setAccessible(false);
}

A: Static properties must be defined in the class definition. Therefore, real static properties cannot be created dynamically like regular properties.
For example, if you run this:
<?php

class MyClass
{
    public static function createDynamic()
    {
        $mydynamicvar = 'module';
        self::$mydynamicvar = $value;
    }
}

MyClass::createDynamic();

var_dump(MyClass::$mydynamicvar);
var_dump(MyClass::$module);

...you'll get this error
Fatal error: Access to undeclared static property: MyClass::$mydynamicvar test.php on line 8

Notice how the error occurs on line 8 when trying to set the property instead of line 14 or 15 (as you might expect if you were simply doing it wrong and dynamically creating static properties was actually possible).

A: I don't know exactly why you would want to do this, but this works. You have to access the dynamic 'variables' like a function because there is no __getStatic() magic method in PHP yet.
class myclass{
    static $myvariablearray = array();

    public static function createDynamic($variable, $value){
        self::$myvariablearray[$variable] = $value;
    }

    public static function __callstatic($name, $arguments){
        return self::$myvariablearray[$name];
    }
}

myclass::createDynamic('module', 'test');
echo myclass::module();

A: A related problem that IS possible (in PHP 5.4.0 and up) is to include various separate groups of static variable or constant declarations and group them together into one class declaration.
Here is an example:
trait Added1 // This can be located in one Include file
    {
    static
    $x="hello"; // Can declare more variables here
    }
trait Added2 // This can be located in another Include file
    {
    static
    $y="world"; // Can declare more variables here
    }
class G // Global constant and variable declarations class
    {
    use Added1, Added2; // Combines all variable declarations
    }

echo G::$x." ".G::$y; // Shows "hello world" on the web page


text:
Q: Error when install package dplyr in R. Error in install.packages : missing value where TRUE/FALSE needed I tried to install package dplyr but it always show the error:
Error in install.packages : missing value where TRUE/FALSE needed

Here is the console history:
> install.packages("dplyr")
also installing the dependency 'BH'

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.3/BH_1.60.0-2.zip'
Content type 'application/zip' length 15529281 bytes (14.8 MB)
downloaded 14.8 MB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.3/dplyr_0.5.0.zip'
Content type 'application/zip' length 2409178 bytes (2.3 MB)
downloaded 2.3 MB

Error in install.packages : missing value where TRUE/FALSE needed

Anyone have any ideas? Thanks in advance

A: I had this problem in R for Windows 3.4

*

*Go to the CRAN webpage and download and install the R 3.4.0 Patched Build for Windows

*Run Rstudio as administrator.

*Install the package as usual.

A: It's a bit weird, but it worked for me.
Just closing the installed packages win-library folder while installing package resolved the mentioned error.

A: I tried changing my repository, and .libPaths variable, those didn't work. Simply rebooting my windows machine did the trick for me.

A: I had the same problem in R3.4 version,
it was solved by using
install.packages("tidyverse",dependencies = TRUE,repos = "http://cran.us.r-project.org")

A: I had the same problem where my rsession.exe was essentially being blocked by my Advanced System Care software from accessing this file index.html. When I clicked on index.html, I wasn't sent to any particular file just the base [This PC] folder home page on Windows 10. The error you had was present for me throughout 3.4.3, 3.4.3patched, and 3.2, so it was probably a problem I was dealing with that transcended the versions themselves.
I don't know why exactly the access was really needed, but allowing it got rid of the problem for me.

A: Disabling my Avast antivirus for 10 minutes while the package was installed resolved my proble.

A: Like @minette-van-zyl, this issue disappear when I disabled Avast (don't know why, though).


text:
Q: Add hours and minutes to datetime using input fields? I'm trying to add hours and minutes to the datetime using inputfields.
the inputfields are within a flash application but they are similar to any other HTML input fields.
so for the sake of this question, I will be using HTML input fields.
currently I cannot even add the hours to the datetime, let alone the minutes!
My PHP code looks like this:
$myTime = mysqli_real_escape_string($db_conx, $_POST['myTime']);
$myMinute = mysqli_real_escape_string($db_conx, $_POST['myMinute']);

    $end_date = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s"). ' + '.$myTime.' hours'));

and my input fields are like so:
    <input type="text" name="myTime" />
    <input type="text" name="myMinute" />

when I enter the $end_date into a MYSQL datetime field, I get this 1970-01-01 01:00:00
but I thought, with my code above, it should be today's date and time + whatever amount's passed through $myTime ?
could someone please advise on this issue?
Thanks

A: Use this code. Change variables according to you

$minutes_to_add = 5;
$h_to_add = 5;

$time = new DateTime(); //Here you can also pass your Dynamic Variable like DateTime($variable);
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$time->add(new DateInterval('PT' . $h_to_add . 'H'));

echo $stamp = $time->format('Y-m-d H:i:s');

A: Try something
$now = date("Y-m-d H:m:s");
//replace 3 with variable
$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now));

//try to use some thing like $minutes = ($hours * 60) + $minutes;
// so you dont need to add separately.
// replace 10 with your variable
$new_time = date("Y-m-d H:i:s", strtotime('+10 minutes', $now));


text:
Q: Set secure flag for cookies Symfony Azure I have to set the secure flag for my website cookies. My website is in Symfony 3.4 and it is deployed on Azure. I have tried this rule <httpCookies requireSSL="true" httpOnlyCookies="true"/> under <system.webServer> in  web.config file but it doesn't work and I tried adding this tag under <system.web> as well, but no luck.

A: I have set it in my symphony configuration and got it sorted for those cookies which were created by my application. I didn't have to do it by web.config.
Set these below parameters in the config.yml file.
config.yml
framework:
    session:
        cookie_httponly: true
        cookie_secure: true


text:
Q: Offset and Fetch Next Record occurs in multiple page Recently I hit a issue when use offset and fetch next to do pagination in SQL Server, some records occurs in multiple pages.
SELECT A.ID, A.Col1, A.Col2, A.Status
FROM (
    SELECT ID, Col1, Col2, Status
    FROM Table1
    ORDER BY Status
    OFFSET 100 ROWS FETCH NEXT 100 ROWS ONLY --# 100 just for sample, first page will be 0 and 100
) AS A
ORDER BY A.Status

ID is the primary key, and it occurs in different page, a lot of records with same status, but sequence in database should same based on my understanding. Now I use ROW_NUMBER without issue.
But still want to know any issue with OFFSET and FETCH NEXT, and how to fix this?

A: If there are multiple records with the same status, then order by status is not a stable clause; when there are ties, the database has to decide which record comes first, and this might not be consistent over consecutive executions of the same query.
To get a stable resultset, you need order by columns that whose combination represents a unique key. Here, a simple solution is to add the primary key to the clause:
So:
SELECT ID, Col1, Col2, Status
FROM Table1
ORDER BY Status, ID
OFFSET 100 ROWS FETCH NEXT 100 ROWS ONLY

Note that you don't need a subquery: you can select, sort and fetch in the same scope.


text:
Q: A Jpa query annotation to return results as key value pairs I have a users table and I am trying to use annotated Queries in spring boot to get a result set. I am able to get result set as a list, but that does not have field names. How do I get the result set with field name as key and value pairs?
Current response [[1,"Jay"]] , what I want to do is {"id":1,"Name":"Jay"}
-----Here is my repository class-----
 @Repository
 public interface UsersauthRepository2 extends JpaRepository<Users2,Long> {
 @Query("select id,name,email from Users u where LOWER(email) = LOWER(:email) and LOWER(u.password) = LOWER(:password)")
 List<Users2> querybyemail(@Param("email") String email,@Param("password") String password);
  }

A: The request doesn't return fields names.
If you need to get them :

*

*You have them already as method argument

*You need to use reflection.

Good luck


text:
Q: Why M-theory has only M2 and M5 branes? Why M-theory has only M2 and M5 branes? In string theory, depending on the type one considers, you get all kind of D-branes. What is so special in M-theory that only allows 2 and 5 branes?

A: The type of branes a theory has in constrained by the p-form fields it contains. There is only one supersymmetric gravity theory in 11d, and it has a single $p$-form with $p=4$, call it $G_4$. This means that the theory can possess brane solutions that either couple electrically to $G_4$ (M2 branes) or magnetically to $G_4$ (M5 branes).
To understand the dimensionality of an electric coupling, The $p$-form field corresponds to a $p-1$-form potential. $p-2$ of these directions correspond to the extended brane directions (if there are any), and the last one corresponds to time. Compare this with the familiar case of electromagnetism where $A_t$ couples electrically to a point particle's worldline, and the field strength is $F_2 = dA$. In the case of M-theory, this means that $G_4$ couples electrically to a two-dimensional object, i.e. M2 branes.
To see where the magnetic M5 branes come about, simple take the Hodge dual to obtain a 7-form: $\star G_4 = G_7$, and then $G_7$ couples (by the same arithmetic as above) to a 5-brane, i.e. M5 branes.
Oh, and just a comment, in the 10D string theories there are indeed many different branes, but not all kinds. They are constrained by the same counting. So for example, in terms of D-branes (not counting the NS branes), IIB only has odd-dimension branes and IIA has even ones.

A: In supergravity theory, 11d have 3 dimensional scalar object and 6 dimensional anti-symmetric tensor object. This allows that M-theory have M2 brane and M5 brane only.
(By studying on the following question,  D branes Ns brane and p-branes,
I found some interesting paper: Supermembranes, arXiv:hep-th/9611203. It seems to me that section "1.3 The brane scan" describes relevant information on this question. So I post it here. This review paper also covers other various dimensions such as 10d,9d, $\cdots$ up to 2d)


text:
Q: WebRTC android example, XMPP or Http Peer Connection? Is the example code of WebRTC example folder for Android /root/trunk/talk/examples/android/ is it using Http Peer Connection or is it using Libjingle XMPP protocol for communicating with server?
I am trying to create example android Application with WebRTC, which will talk with my local Http server for login and call.
My server is simple http not XMPP and i want some sample code to test it for android platform, so i am thinking of using this android example code in WebRTC code base if it is basic http WebRTC client for android.

A: To login and call (signaling part of your application) you could use socket.io. I leave you an example that worked for me:

https://github.com/pchab/AndroidRTC

This application uses android-websockets library which its name was changed to AndroidAsync and you can find it here:

https://github.com/koush/AndroidAsync

Hope it helps you!


text:
Q: LINQ how to pass method variable as column name in where clause I have a probleme with my code below. I want to pass my variable (relance) as columnname in my where clause but ...... It doesn't work . I need your help.
 public IList<ImportDataViewModel> LienNroList(string colName)
    {
        IEnumerable<ImportDataViewModel> result = new List<ImportDataViewModel>();
        IEnumerable<ImportDataViewModel> ImportDataViewModel = new List<ImportDataViewModel>();

        var col1 = context.col1;
        var col2 = context.col2;
        var col3 = context.col3;
        var col4 = context.col4;

        result = col1
           .GroupJoin(col2, Lien => Lien.code_INSEE, jdo => jdo.Ref_codeINSEE, (Lien, jdo) => new { Lien, jdo })
           .GroupJoin(col3, Lien => Lien.Lien.id, comm => comm.id_pf, (Lien, comm) => new { Lien.Lien, Lien.jdo, comm })
           .GroupJoin(col4, LienRest => LienRest.Lien.id, rel => rel.id_pf, (LienRest, rel) => new { rel, LienRest.Lien, LienRest.jdo }).DefaultIfEmpty()
           .Where(x => x.Lien.colName <= DateTime.Now)
           .SelectMany(LienNro => LienNro.rel.DefaultIfEmpty(), (rel, Lien) => new ImportDataViewModel()

           {});


text:
Q: Why transliteration not working for dynamically adding input fields? For the first input field present, transliteration is working perfectly. But when I add @addNeWrow, input field appears, but transliteration is working. I need to work transliteration for all the input fields I am adding via @addNewRow
I need to dynamically add input fields. In that case, for the first input field transliteration is working. For the second input field onwards transliteration is not working. Because transliteration id works only for one input field. So, how can I able to change id of input field and transliteration id dynamically?
So, the code for dynamically adding input fields is

            Date
            <input type="date" class="form-control" v-model="book.date" >

             Details
            <input type="text" class="form-control" v-model="book.details" id="transliterateTextarea2">

Add Another

So, whenever I clicks Add Another @addNewRow I am getting a new input field but transliteration is not working. I think problem arises because id="transliterateTextarea2" works for only one input field.
So, when I click on @addNewRow how can I able to change the transliteration id.
My script is
addForm = new Vue({
el: "#addForm",
  data: {
          seziure:[
          {
             date: null,
             details: null,

          },
        ],
    },
methods: {
      addNewRow: function() {
          this.seziure.push({ date: null, details: null, });
        },
},
})

My transliteration script is

So, here I have added a transliteration id as  var ids = [ "transliterateTextarea2" ];
THIS ID is actually working for first input field only. So, when I click @addNewRow, an input field comes but transliteration is not working
So, when I click on@addNewRow how can I dynamically add id's. So, that I can get transliteration for that input fields too.
Please help me to have an answer.
I need transliteration works for, each new input fields I am adding.

A: maybe you can try Objuect.assign(),the object you push to seziure maybe is not reactivity.  This is just my thoughts ,you can try only.
I were wrong..haha


text:
Q: neo4j create list of edges I have a stream of pairs ,  where id is numberic id of the node, and ids is the list of ids of the adjacent nodes.
I use this query to upsert nodes from such stream:
WITH ${ids.mkString("[", ",", "]")} as ids
UNWIND ids as u2id
MERGE (u1:User {Id:${id}})
MERGE (u2:User {Id:u2id})
CREATE UNIQUE p = (u1) - [:FRIEND] -> (u2)

And i have index on Id label
CREATE INDEX ON :User(Id)

The length of ids list is about 100-200 in average.
Now there are ~60 millions of nodes and mil. of edges in the database. Speed of upserting is about pairs per second. Neo4j running on dedicated machine with Core i5, 28Gb RAM and 2Tb WD Black.
I wonder how upserting query can be optimized or any tip to improve hardware.

A: These progressive changes should make the query faster.

*

*Perform MERGE of u1 just once
By moving the MERGE of u1 before the UNWIND, it will only be executed once (instead of once per u2id value).
MERGE (u1:User {Id:${id}})
WITH u1, ${ids.mkString("[", ",", "]")} as ids
UNWIND ids as u2id
MERGE (u2:User {Id:u2id})
CREATE UNIQUE (u1)-[:FRIEND]->(u2)

*In addition, use MERGE instead of CREATE UNIQUE
Your relationship creation use case should be satisfiable by MERGE as well as CREATE UNIQUE (since you ensure that both endpoints exist beforehand). In my profiling, I see that MERGE uses fewer DB hits (your mileage may vary, depending on your DB characteristics and neo4j version).
MERGE (u1:User {Id:${id}})
WITH u1, ${ids.mkString("[", ",", "]")} as ids
UNWIND ids as u2id
MERGE (u2:User {Id:u2id})
MERGE (u1)-[:FRIEND]->(u2)


text:
Q: Не могу вызвать метод в тернарном операторе public static double Foo(double x, double a, double b)
{
    a < b ? Console.WriteLine(a) : Console.WriteLine(b);
    return Math.Cos(2 * x) + Math.Sin(x - 3);
}

Что мешает в тернарном операторе вызвать метод Console.WriteLine(), и как было бы правильно? Вылезает ошибка:

В качестве оператора могут использоваться только выражения назначения, вызова, инкремента, декремента и создания нового объекта

A: То, что он возвращает void, а тернарный оператор является выражением.
Console.WriteLine(a < b ? a : b);


text:
Q: how to use escape characters in JSX I want to use some escape characters in my React application but I have not found any resource that how can I use escape character in my application.
Is any methodology available?

A: Use the same escape as Javascript (ECMAScript)
' single quote
" double quote
\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
For the HTML portion, use HTML escape characters.
There are some minor gotchas,to be aware of like evaluating escape chars between { }
HTML:

JSX:
class MyComponent extends React.Component {
  render() {
    console.info('Test line\nbreak');
    return
Hello {this.props.name} <>
;
  }
}

ReactDOM.render(
  <MyComponent name="Stackoverflow  < !-- comment in name -->" />,
  document.getElementById('container')
);

This program prints this to the console:
Test line
break

And the user's screen is the following:

Hello Stackoverflow < !-- comment in name --> <>


text:
Q: Meteor Collection exists in Mongo but returns ReferenceError in browser console I'm setting up a new Meteor project and am having trouble working with collections on the client side. Right now what I'm building is an administrative page where a user can maintain a list of schools.
Running meteor mongo and db.schools.find() in Terminal returns a BSON object just as I would expect, however when I enter "Schools" in the Chrome console it returns Uncaught ReferenceError: Schools is not defined which is a bummer.
My project architecture (simplified to the bits that reference the School collection) is as follows:
client/
  layouts/
    admin/
      schools.coffee
      schools.jade
  lib/
    subscriptions.coffee
lib/
  collections.coffee
server/
  lib/
    publications.coffee

The contents of each of these files (in the desirable load order) is:
1) lib/collections.coffee
 1| Schools = new Mongo.Collection('schools')

2) server/lib/publications.coffee
 1| Meteor.publish('schools'), ->
 2|   Schools.find()

3) client/lib/subscriptions.coffee
 1| Meteor.subscribe('schools')

4) client/layouts/admin/schools.coffee
76| Template.admin_schools.helpers
77|   schools: ->
78|     Schools.find()
79|   numSchools: ->
80|     Schools.find().count()
81|   hasSchools: ->
82|     Schools.find().count() > 0

5) client/layouts/admin/schools.jade
 4| h2.admin__header Schools
 5|   span.admin__record-count {{numSchools}} entries
...
22| table.admin__list
23|   if hasSchools
24|     each schools
25|       tr.admin__list-item
26|         td #{name}

I also have a form for new collection entries which calls Schools.insert, but the error there is the same.
When the page loads, I get the following error (likely because it is called first):
debug.js:41 Exception in template helper: ReferenceError: Schools is not defined
at Object.Template.admin_schools.helpers.numSchools

Those two errors, combined with the fact that I know there exists an entry in the collection, leads me to believe that the issue lies with the client side's awareness of the existence of the collection.
This discrepancy might possibly be due to load order (I am pretty sure I accounted for that by putting the important files in lib/ directories, though I would love a second opinion), or maybe due to a spelling/syntax mistake (though the absence of compile errors is puzzling). Maybe something completely different!
Thank you very much for your time and assistance, they are much appreciated.

A: Turns out that because this is CoffeeScript, placing an @ before Schools = new Mongo.Collection('schools') in lib/collections.coffee makes Schools a global variable, thereby solving the problem! Pretty simple fix in the end :)
Special thanks to Kishor for helping troubleshoot.

A: Have you checked your subscriptions on created?


text:
Q: How can i get the records that contain a single quotation mark in SQL Server? How can i get the records that contain a single quotation mark in SQL Server?
The following as you guess, is not valid, but you get the point
SELECT [Id], [Name] FROM [People] WHERE Name LIKE '%'%'

A: The double single quote is interpreted as a single quote in a string:
SELECT [Id], [Name] FROM [People] WHERE Name LIKE '%''%'

A: You need to escape the quote
SELECT [Id], [Name] FROM [People] WHERE Name LIKE '%''%'

A: In your query, the % are under 3 ' (like '%'%'). They should be under 4.
SELECT [Id], [Name] FROM [People] WHERE Name LIKE '%''%'

The % are now escaped in this query.

A: You can do the escape code as others have mentioned or you can use the char code 39, where CHAR(39) is '.
SELECT [Id], [Name] FROM [People] WHERE Name LIKE '%' + CHAR(39) + '%'


text:
Q: JavaScript createElement with ID I am creating a JavaScript array with 3 elements:
var employees =
    [
        {"firstName":"John", "lastName":"Doe"},
        {"firstName":"Anna", "lastName":"Smith"},
        {"firstName":"Peter", "lastName":"Jones"}
    ]

I want to use a for loop to loop through the data. Here is the for loop:
for (int i = 0; i < employees.length; i++)

I want to create a new
 for each object and place the data in the new
. I believe that I need to assign an id to each
. How would I achieve this?
Complete code thus far:
<!DOCTYPE html>

JSON Java Syntax Examples

A: *

*Replace int by var in for loop definition.

*Assign new element to variable, e.g new_p.

*Use textContent() function to set text content to your element.

*Finally append the new paragraph new_p to your body using appendChild() function.

Hope this helps.

Snippet

var employees =
    [
      {"firstName":"John", "lastName":"Doe"},
      {"firstName":"Anna", "lastName":"Smith"},
      {"firstName":"Peter", "lastName":"Jones"}
    ]

for (var i = 0; i < employees.length; i++)
{
    var new_p = document.createElement("p");

    new_p.textContent = employees[i].firstName + " " + employees[i].lastName;

    document.body.appendChild(new_p);
}

A: Ok after reading the comments and answers here and doing some more research I have found the solution and it works 100%. I am not assigning an ID to any of the newly created elements. I am using innerHTML to add the data to the element and then using appendChild to add the tag to the document.
Here is the working code:
<!DOCTYPE html>

JSON Java Syntax Examples

Thanks for all the responses!

A: Here's a modern approach:
First, define a function to create a DOM document fragment, based on an array of elements. A DOM fragment can be built up and inserted into the DOM all at once. In a simple example, it wouldn't make any difference, but it would be faster if there were a lot of DOM manipulations going on.
function createFragment(arr) {
  return arr.reduce(r, e) {
    r.appendChild(e);
    return r;
  }, document.createDocumentFragment());
}

Write the function to transform a particular employee's data into a p element:
function makeElt(emp) {
  var text = document.createTextNode(emp.firstName + ' ' + emp.lastName);
  var p = document.createElement('p');
  p.appendChild(text);
  return p;
}

With these pieces in place, we need only to write:
document.body .                 // To the document body,
  appendChild (                 // append
    createFragment (            // the fragment containing
      employees .               // all of the employees
        map (                   // transformed into
          makeElt               // a DOM element
)));

A: Try Below code:
        for (int i = 0; i < employees.length; i++)
            {
                var pObj = document.createElement("p");
        var t = document.createTextNode(employees[i].firstName + " " + employees[i].lastName);
                pObj.appendChild(t);
        document.body.appendChild(pObj);
            }


text:
Q: CURL Execution in PHP     $returnurl = "http://clietsite.com:9000/service";
    $curlPost = "rtyinstance=<parent><child>value</child></parent>";
    $ch1 = curl_init();
    if (!$ch1) die("Couldn't initialize a cURL handle");
    $headerinfo = apache_request_headers();
    curl_setopt($ch1, CURLOPT_URL, $returnurl);
    curl_setopt($ch1, CURLOPT_HEADER, 0);
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch1, CURLOPT_POST, true);
    curl_setopt($ch1, CURLOPT_POSTFIELDS, $curlPost);
    curl_setopt($ch1, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($ch1, CURLOPT_USERAGENT, $headerinfo['User-Agent']);
    curl_setopt($ch1, CURLOPT_TIMEOUT,1*60);
    $result = curl_exec($ch1);
    var_dump($result);
    echo $responseCode = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
    curl_close($ch1);

The above code returns responseCode 200, var dump prints string(0) "".
when i run in browser (I'm using PHP Version 5.2.17)
like
http://clietsite.com:9000/service?instance=<parent><child>value</child></parent>

Which successfully returns an xml.  don't know what could be the issue. Please help me solve this.

A: Via cURL you are using POST, while in the browser you issue a GET.
That might be the issue.
To 'convert' to GET, use this code:
$encoded_params = urlencode('<parent><child>value</child></parent>');
$returnurl = "http://clietsite.com:9000/service?rtyinstance=" . $encoded_params;
$ch1 = curl_init();
if (!$ch1) die("Couldn't initialize a cURL handle");
$headerinfo = apache_request_headers();
curl_setopt($ch1, CURLOPT_URL, $returnurl);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch1, CURLOPT_USERAGENT, $headerinfo['User-Agent']);
curl_setopt($ch1, CURLOPT_TIMEOUT,1*60);
$result = curl_exec($ch1);
var_dump($result);
echo $responseCode = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
curl_close($ch1);

A: The following URL is not available for me:
http://clietsite.com:9000/service?rtyinstance=<parent><child>value</child></parent>

Is that website really accessible from outside your computer/network? If you are hosting the script on one server and the website on another it might not work.


text: Q: Is it possible to show custom dialog just before navigating to other website resulted by address bar change Is it possible to show a dialog when the user navigates to other website changing the url address bar and pressing enter to carry out the navigation?


text:
Q: Type mismatch when using Scala Trait in Play? Using the Play! Framework 1.2.4. I've got a nifty trait that checks an API key and HTTPS, but if I want to access the account associated with that key and reference it in my controller, it throws a type mismatch; found : java.lang.Object required: Long
So here's my API controller (incomplete):
object API extends Controller with Squeryl with SecureAPI {

  import views.API._

  def job(param:String) = {

    val Job = models.Job
    param match {
      case "new"    => Job.createFromParams(params,thisAccount) //thisAccount comes from the trait
      case "update" =>
      case "get"    =>
      case "list"   =>
    }
  }

}

and the secure trait:
trait SecureAPI {
  self:Controller =>

  @Before
  def checkSecurity(key:String) = {
      if(!self.request.secure.booleanValue) {
          Redirect("https://" + request.host + request.url);
      } else {
          models.Account.getByKey(key) match {
            case Some(account)  =>  {
              renderArgs += "account" -> account.id
              Continue
            }
            case _  =>  Forbidden("Key is not authorized.")
          }
      }
  }

  def thisAccount = renderArgs("account").get
}

How would I properly access thisAccount? Thanks

A: Your problem is simply that renderArgs is only declared to return an Object from its get call (which is fair enough because it could be just about anything).
Consequently the inferred type of your thisAccount method will be () => Object.
You'll need to cast the returned type into a Long, something like (though perhaps with some error-checking):
def thisAccount = renderArgs("account").get.asInstanceOf[Long]


text:
Q: JQuery function access Hello I'm using jquery splitter widget
JQuery splitter widget
and I'm able to intialize it as documentation says
$('#foo').split({
    orientation: 'horizontal',
    limit: 10,
    position: '50%' // if there is no percentage it interpret it as pixels
});

What I don't know how to do (because my poort jquery knowledge) is how to destroy it i can see in js that there is a function destroy but I don't know how to access it.
splitter javascript
I've tried something like
$('#foo').destroy();

or
$('#foo').split('destroy');

but this does not work.
Could you please help me with this?
Thank you very much for any kind of help.
best regards team ol

A: You should be able to assign your instance to a variable and then access the destroy method through your reference.
var mySplitter = $('#foo').split({
  orientation: 'horizontal',
  limit: 10,
  position: '50%' // if there is no percentage it interpret it as pixels
});

// then you can do
mySplitter.destroy();


text:
Q: How to Link Excel to SharePoint list? I have a problem on how will I connect my excel to SharePoint. I have created a list in SharePoint and I need those data sync in excel that I want to create. I'm using excel 2016 and SharePoint 2016. Please refer to this link because I think this is what I supposed to do. The problem there is that I can't see the "SharePoint List" option in my excel.

A: Follow the steps in this article:
https://support.office.com/en-gb/article/Export-a-list-to-Excel-in-SharePoint-Online-40f4b5cd-cb8a-4106-817e-4a0bf7cd68b5
If your list on the sharePoint gets updated, you will need to Refresh connection in excel in order to get the updated data from the SharePoint List.


text:
Q: How to retrieve the date into three dropdown list? I have a birthdate field which is optional after inserting a record into clients table.
the default value will is "000-00-00" after insert.
Now, I want to edit the record in the table and would like to get the value of the birth_date field into three dropdown list.
The three dropdown list are Day, Month, and Year.
If there is no birthdate the selected value of the three dropdown should be "Day", "Month", and "Year".
I tried the following code and don't know if this is the best way.
$dateValue = '0000-00-00';
$year = explode("-", $dateValue);

if ($year[0] == "0000") {
    $selected_year = "Year";
            $selected_month = "Month";
            $selected_day = "Day";
}else{
    $selected_year = date("Y",strtotime($user['birth_date']));
}

If there is a better way for this, please let me know.
btw, I'm using codeigniter.

A: I think you are doing your test too late, it is much simpler to do it directly on $dateValue. Also, you can simplify the code by making use of the list function:-
$dateValue = '0000-00-0';
if($dateValue == '0000-00-00'){
    $values = array('Year', 'Month', 'Day');
} else {
    $values = explode('-', $dateValue);
}
list($selected_year, $selected_month, $selected_day) = $values;

var_dump($selected_year);
var_dump($selected_month);
var_dump($selected_day);

Gives the following output:-
string 'Year' (length=4)
string 'Month' (length=5)
string 'Day' (length=3)

Changing the first line to:-
$dateValue = '2012-11-3';

Gives:-
string '2012' (length=4)
string '11' (length=2)
string '3' (length=1)

Personally, I would hide this all away in a function to improve readability:-
function getValues($dateValue = '0000-00-00'){
    if($dateValue == '0000-00-00'){
        $values = array('Year', 'Month', 'Day');
    } else {
        $values = explode('-', $dateValue);
    }
    return $values;
}

Then use it like this:-
list($selected_year, $selected_month, $selected_day) = getValues('2012-11-03');

var_dump($selected_year);
var_dump($selected_month);
var_dump($selected_day);

A: well my suggestion is to use date_format mysql function to get year,day and month in your query like this
select *,DATE_FORMAT(date_field,'%Y') as selected_year,
DATE_FORMAT(date_field,'%d') as selected_day,
DATE_FORMAT(date_field,'%c') as selected_month
from user_table;

for more information date_format please check this link
Date_format
or mysql doc


text:
Q: How to use temporarySignedRoute() in Laravel? I have this route in the web.php:
Route::get('/email/sent/{email}', function(){
        return view('auth.passwords.email_sent');
})->name('forgot-password.email.sent')->middleware(['signed']);

In a controller I am generating a temporary signed route using:
$url = URL::temporarySignedRoute('forgot-password.email.sent', now()->hours(1), ['email' => $email]);

How ever everytime I visit the route it returns 403 Forbidden. But if I use signedRoute():
$url = URL::signedRoute('forgot-password.email.sent', ['email' => $email]);

It works, I think the problem is with the generated timestamps but I am not really sure.
Has anyone encountered this before?

A: now()->hours(1) sets the date to now except with the hour changed to the number passed, in your case 1, which is not what you want. And because 1 AM happens to be before the current time, the temporary route is already expired when you try to access it and you get a 403 error.
Try now()->addHours(1) instead.
In the future you could try to die & dump or log now()->hours(1) to check what's wrong with the date and time.
https://laravel.com/docs/9.x/helpers#method-now here the now helper is described. \Illuminate\Support\Carbon is instantiated, which wraps Carbon\Carbon, which means you can see the available methods here: https://carbon.nesbot.com/docs/.
You could also use Carbon directly if you wanted.


text:
Q: If $\theta = (59.3\pm 1.2)^{\circ} $, find $\tan(\theta)$ and it´s uncertainty. How can I find the uncertainty? I need to use this formula:
The general formula for uncertanties is:
$\sigma_q = \sigma_q (a,b,c,...)$ and $\mathrm{Cov}(a,b,c,...)=0$ $\,\,$then
$$\sigma_q ^2 = (\frac{\partial c}{\partial a}\sigma_a)^2+(\frac{\partial c}{\partial b}\sigma_b)^2+\,\,...$$
Is this correct: (?)
$$\sigma_{\tan(\theta)}^2 = (\frac{\partial {\tan(\theta)}}{\partial \theta}\sigma_ \theta )^2 \Rightarrow$$
$$\sigma_{\tan(\theta)} = \sec^2(\theta)\times1.2\Rightarrow$$
$$\sigma_{\tan(\theta)}=1.17 \times 1.2 = 1.4 \Rightarrow$$
$$\tan(\theta) = \tan(59.3)^{\circ} \pm \sigma_{\tan(\theta)} = 1.68 \pm 1.4 $$
thank you.

A: As $Harish has already shown, the maximum uncertainty is much smaller than what you have found.  Given that you are using the general formula for error propagation (using partial derivatives, etc.) I'm guessing you are not looking for the maximum uncertainty but for the "one-sigma" uncertainty.  So your answer should be a smaller than what he found.  Also, he has accidentally found twice the maximum error since he subtracted the lower bound from the top bound (the full range) instead of quoting half the range.
Your problem is that you are not paying careful attention to units.  In your second last line you say
$\sigma_{\tan{(\theta)}} = 1.17 \times 1.2$
But notice that your "1.2" came from the original uncertainty in $\theta$ so it is really $1.2^\circ$.  So this means your answer for the uncertainty in $\tan{\theta}$ is in degrees which can't be right since $\tan{\theta}$ should be a dimensionless number.  You need to put $\sigma_\theta$ into radians.  This will give you a far more reasonable answer.

A: Notice,
1. Taking positive sign
$$(\tan\theta)_{\text{max}}=\tan (59.3+1.2)^\circ=\tan 60.5^\circ$$

*Taking negative sign
$$(\tan\theta)_{\text{min}}=\tan (59.3-1.2)^\circ=\tan 58.1^\circ$$

Hence, the maximum possible uncertainty in the value of $\tan \theta$ $$=(\tan60.5^\circ-\tan 58.1^\circ)\approx 0.160926831$$


text:
Q: ImportError: No module named 'urllib3' Everytime I use pip command the command failed with error: "ImportError: No module named 'urllib3'".
I do got urllib3 installed, and when I'm trying to install urllib3 again I got the same error. What can I do?
I'm using windows 10.
I cant run "pip install virtualenv", I got the same error with any pip command.

A: May be worth double checking your PYTHONPATH Environment Variable in:
Control Panel\System and Security\System -> Advanced System Settings -> Environment Variables.
I had a rogue copy of Python that caused this exact error

A: You probably need to bootstrap your installation of pip so that you can move along with this.

*

*Download the bootstrap script from https://bootstrap.pypa.io/get-pip.py

*Using whatever version of Python you wish, run it, e.g.,
C:\\Python35.exe get-pip.py

After that finishes you should be able to pip install whatever you'd like.

A: For escaping this error try to install virtualenv through "pip install virtualenv" and create the virtual environment directory using "python3 -m venv myvenv" which will create a myvenv named folder now activate the myvenv folder using "source \myvenv\bin\activate" now you have your virtual environment setup now you can install whatever you want under the venv , which will not conflict with your base os installed programs try some googling to explore pic virtualenv setup and use. happy coding :)

A: I solved this issue by deinstalling python and reinstall it.
Then you can run
python -m pip install --upgrade pip

to get the latest version of pip