text:
Q: Exception using RestTemplate after upgrading to springBootVersion = '1.3.3.RELEASE' After upgrading to springBootVersion = '1.3.3.RELEASE' (and, spring-security-oauth2:2.0.9.RELEASE), when we make OAuth2RestTemplate exchange call, we get the below exception on the OAuth2AuthorizationServer. Below, I have listed also all the dependencies on the client side build.gradle.
I appreciate any help.
13:19:50.426 [http-nio-8888-exec-5] WARN  o.s.s.o.p.token.store.JdbcTokenStore/readAuthentication Failed to deserialize authentication for 9a1eea62-2be5-4b43-bdac-b39d6142c4f1
java.lang.IllegalArgumentException: java.io.InvalidClassException: org.springframework.security.core.authority.SimpleGrantedAuthority; local class incompatible: stream classdesc seri
alVersionUID = 320, local class serialVersionUID = 400
        at org.springframework.security.oauth2.common.util.SerializationUtils.deserialize(SerializationUtils.java:40)
        at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore.deserializeAuthentication(JdbcTokenStore.java:405)
        at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore$3.mapRow(JdbcTokenStore.java:198)
        at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore$3.mapRow(JdbcTokenStore.java:196)
        at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
        at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
        at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:693)
        at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:629)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:680)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:712)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:722)
        at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:796)
        at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore.readAuthentication(JdbcTokenStore.java:195)
        at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore.getAccessToken(JdbcTokenStore.java:129)
        at org.springframework.security.oauth2.provider.token.DefaultTokenServices.createAccessToken(DefaultTokenServices.java:84)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
        at com.sun.proxy.$Proxy67.createAccessToken(Unknown Source)
        at org.springframework.security.oauth2.provider.token.AbstractTokenGranter.getAccessToken(AbstractTokenGranter.java:70)
        at org.springframework.security.oauth2.provider.token.AbstractTokenGranter.grant(AbstractTokenGranter.java:65)
        at org.springframework.security.oauth2.provider.CompositeTokenGranter.grant(CompositeTokenGranter.java:38)
        at org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer$4.grant(AuthorizationServerEndpointsConfigurer.java:561)
        at org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(TokenEndpoint.java:132)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.flect.Method.invoke(Method.java:497)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
        at org.springframework.security.web.access.intFilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:213)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
       .springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
        at org.springframework.web.ficePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
     ava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.InvalidClassException: org.springframework.security.core.authority.SimpleGrantedAuthority; local class incompatible: stream classdesc serialVersionUID = 320, local
 class serialVersionUID = 400
        at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:621)
        at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1623)
        at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
        at java.util.HashSet.readObject(HashSet.java:333)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1900)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2000)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1924)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2000)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStva:1924)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
        at org.springframework.security.oauth2.common.util.SerializationUtils.deserialize(SerializationUtils.java:36)
        ... 118 common frames omitted
13:19:50.677 [http-nio-8888-exec-5] INFO  o.s.s.o.p.endpoint.TokenEndpoint/handleException Handling error: NullPointerException, null
13:19:50.693 [http-nio-8888-exec-5] DEBUG o.s.s.w.a.ExceptionTranslationFilter/doFilter Chain processed normally
13:19:50.693 [http-nio-8888-exec-5] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter/doFilter SecurityContextHolder now cleared, as request processing completed

Dependencies on the client build.gradle:
// Spring Boot
  providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
  compile("org.springframework.boot:spring-boot-starter-web")
  compile("org.springframework.boot:spring-boot-starter-actuator")
  compile("org.springframework:spring-jdbc")
  compile("org.springframework:spring-tx")

  // Spring Boot Security
  compile("org.springframework.boot:spring-boot-starter-security")
  compile("org.springframework.security.oauth:spring-security-oauth2:2.0.9.RELEASE")
  compile('org.springframework.security:spring-security-ldap:4.0.4.RELEASE')

  //jaxb xml marshaller
  compile('org.springframework:spring-oxm:4.2.4.RELEASE')

  // We will also need Spring Context Support that contains JavaMailSender support class.
  compile("org.springframework:spring-context-support")

  // Spring Boot Data Commons - Required for API Pagination
  compile("org.springframework.data:spring-data-commons-core:1.1.0.RELEASE")

  // MyBatis
  compile("org.mybatis:mybatis-spring:1.2.3")
  compile("org.mybatis:mybatis:3.3.0")

  // BoneCP - Connection Pooling
  compile("com.jolbox:bonecp:0.8.0.RELEASE")

  //  compile("org.postgresql:postgresql:9.4-1204-jdbc42")
  compile("com.oracle:ojdbc6:11.2.0.4")

  // Vaadin
  compile 'com.vaadin:vaadin-client-compiled:7.6.4'
  compile 'com.vaadin:vaadin-client:7.6.4'
  compile 'com.vaadin:vaadin-themes:7.6.4'
  compile 'com.vaadin:vaadin-server:7.6.4'
  compile 'com.vaadin:vaadin-push:7.6.4'

  // Official VaadinSpring Integration
  compile("com.vaadin:vaadin-spring-boot-starter:1.0.0")

  //Vaadin extentions - in the future more of those will go to official VaadinSpring Integration
  compile("org.vaadin.spring.extensions:vaadin-spring-ext-security:0.0.7.RELEASE")
  compile("org.vaadin.spring.extensions:vaadin-spring-ext-core:0.0.7.RELEASE")
  compile("org.vaadin.spring.extensions:vaadin-spring-ext-boot:0.0.7.RELEASE")
  compile("org.vaadin.spring.extensions:vaadin-spring-ext-test:0.0.7.RELEASE")

  // Vaadin add-ons
  compile("org.vaadin.spring.addons:vaadin-spring-addon-eventbus:0.0.6.RELEASE")
  compile("org.vaadin.spring.addons:vaadin-spring-addon-mvp:0.0.6.RELEASE")
  compile("org.vaadin.spring.addons:vaadin-spring-addon-i18n:0.0.6.RELEASE")
  compile("org.vaadin.addon:confirmdialog:2.1.3")
  compile("org.vaadin.addons:stepper:2.2.2")//numeric stepper

  compile("javax.mail:mail:1.4.3")

  // Lombok
  compile("org.projectlombok:lombok:1.16.6")

  compile("com.fasterxml.jackson.datatype:jackson-datatype-json-org:2.6.3")

  //Freemarker
  compile("org.freemarker:freemarker:2.3.23")

  //Spring Object/XML Marshalling
  compile("org.springframework:spring-oxm:4.2.4.RELEASE")

  //Spring-boot test
  testCompile("org.springframework.boot:spring-boot-starter-test")

  //Spring security test
  testCompile("org.springframework.security:spring-security-test:4.0.4.RELEASE")

  //The DBUnit library, is a common library that can help implement database-related testing
  testCompile("org.dbunit:dbunit:2.5.1")

  //H2 database Java Library
  testCompile("com.h2database:h2:1.3.160")

  //Apache POI library that supports reading and writing of files in Microsoft Office format
  testCompile("org.apache.poi:poi:3.2-FINAL")

  //MockMVC integration tests -> org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
  testCompile("com.jayway.jsonpath:json-path")

A: Solution was deleting already generated tokens (rows) from the OAUTH_ACCESS_TOKEN table.

A: In Spring security core : (SpringSecurityCoreVersion)
class org.springframework.security.core.authority.SimpleGrantedAuthority will have different serialVersionUID in each versions. so making all previously generated token non-deserializable  . So need to delete tokens generated by old versions whenever you upgrade versions.


text:
Q: php error on IIS: require_once failed to open stream, no such file or directory I have a fairly new server (couple months old) where I've got IIS and PHP running with FASTCGI.
Anyways, I have a script in  C:\inetpub\wwwroot\webservice_read_scripts\   that needs to go do a require_once on the phpmailer library in C:\inetpub\wwwroot\phpmailer.
I know I shouldn't use absolute URL's but I've been trying both absolute and relative and they just aren't working.
I have the absolute one in place right now:
    require_once("C:\inetpub\wwwroot\phpmailer\class.phpmailer.php")
In an attempt to get this to work, I've also tried, just ahead of this line... the following, in order to try to force the right directory to be set as the "include path":
chdir("..")
chdir("phpmailer")
set_include_path(getcwd());

And I'm getting the following two errors:
Warning: require_once(1): failed to open stream:  No such file or directory in (gives path to my executing script and refers to that require_once line)

Fatal error: require_once(): Failed opening required '1' (include_path="C:\inetpub\wwwroot\phpmailer") in (gives path to my script and that require_once line again)

The file IS there and is named correctly.
I figure it must be permissions?   I've got... "Users" and "IIS_USRS" groups set up for Read and Execute access.  There's a domain-level group named "IUSR" that I've set to full control too.
Not sure what to do next, as googling isn't finding me much more.
Any thoughts??

redpajama_set_name: RedPajamaStackExchange


text:
Q: Related posts from the blogosphere - dynamic integration of Google Blogsearch RSS on wordpress category pages I'm looking for a method to put the three latest "news" from Google Blogsearch/Twitter search feeds into the bottom of category Pages. Maybe like this (assuming we're on the archive page for the "Sports" category):
What others say about "Sport":

*

*Instapundit - Michael Jordan Comeback!

*Huffington post - Michael Jordan Comeback!

*Crazyguy - Michael Jordan Comeback!

So we all know that you can put
<?php include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('pathtofeed.com', 3); ?>

in a template-file and it will list the latest three items of a feed.
I would like to put the path to the feed of a query to Google Blogsearch, e.g. [http://blogsearch.google.com/blogsearch_feeds?hl=en&q=sport&ie=utf-8&num=10&output=rss][1]
Works fine. But I would like to replace the sport query with the template tag for the category title - so it dynamically queries Google for a RSS-feed of sport searches. I've tried this:
<?php
include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('www.blogsearch.google.com/blogsearch_feeds?hl=en&q=<?php single_cat_title() ?>&ie=utf-8&num=10&output=rss', 3);
?>

(omitted 'http' cause I can't post hyperlinks here as a new user).
But all I get is:

There was a problem with the feed, try again later.

(translated from Danish error message).
Is it the syntax?

A: You've got a couple of issues in that code.
The first is you have a <?php inside an already opened <?php section. Concatenation is the answer to that problem.
The second is the function single_cat_title() displays the category title by default. Meaning it "echo()"s it out. So you need to tell that function to return the value not display it.
My solution would be to add a line of code above your include there to get the category you're looking for along the lines of:
$current_category = single_cat_title("", false);

The "false" tells the function to return it as a value instead of displaying it by default, the first parameter is the prefix or the text to display before the category title.
Then concatenate the current_category variable into your include statement
You can check out that function on the Template Tags page in the Wordpress Codex.


text:
Q: BottomNavigationView nested navigation I have 3 fragments. I use Navigation component. The first fragment refers to the second fragment, the second to the third fragment. The BottomNavigationView element is associated with the first fragment. How to return to the first fragment from the third fragment by clicking on the menu item?
chart


text:
Q: How to store and retrieve passwords without being seen in the code using spock table I am looking for some good approaches on storing passwords within the framework (groovy+geb+spock+selenium). Currently I am using encrypt and decrypt methods using Crypto.Cipher. However I would like to know if others have any good approaches to do it. Such as any other algorithms/techniques/tools?
It looks something like below:
def "test" (){

given:

when
Login(username,password)

then

where:
username | password
"jass" | "testpass123"

//"jass" |  decryptPassword("some encrypted value ")

// instead of the actual password we are calling a
// function "decryptPassword" which takes encrypted value and
// returns the actual key to the calling function.

}

A: You can encrypt the password and store in the spock table. Write a separate method in other class for decrypt. Use the encrypted data. Call the decrypt method in password field instead of plain test.
More secure decrypt method should be converted as jar file and use it. So its difficult to find the decrypt algorithm.


text:
Q: Is it reasonable to define `poset homotopy' as a `natural transformation of posets'? Pausing to speak metaphorically for a bit, I have always thought of partial orders as being something like a simplified version of topological spaces.  (In the finite case at least, all topological spaces are partial orders).  This leads to thinking about continuous maps as a parallel concept to the idea of a poset homomorphism.  But is there a corresponding parallel notion for a homotopy of two continuous maps?
Here is a sketch of how I imagine this working:
Since all preorders are categories, and posets are preorders, we can think of any partial order $(\leq, C)$ as a category whose morphisms are just given by the relation $\leq$.  Now a homomorphism of posets is just a functor of these categories.  Taking this one step further, we can define a natural transformation of any two homomorphisms of posets, which I am thinking of as a candidate definition for a poset homotopy.
Now it is also true that CW complexes are technically posets under the incidence relation.  If we replace the posets in the above sketch with CW complexes and the functors with cellular maps, does the proposed definition for poset homotopy match the known definition for a `CW complex homotopy'?  (EDIT:  Or is this true for some variation of a CW complex; for example a finite or simplicial complex?)

A: For any finite poset $P$, we can consider the poset $sP$ of nonempty chains in $P$, ordered by inclusion.  There is a morphism $m_P:sP\to P$ sending each nonempty chain to its largest element.  If you modify the category of finite posets by

*

*Identifying maps $f,g:P\to Q$ whenever they are homotopic (ie $f(p)\leq g(p)$ for all $p\in P$); and

*Adjoining inverses for the maps $m_P$
then you get the usual homotopy category of finite complexes.  I won't swear that the details are completely straight, but certainly something like this is true.  Key points are that

*

*We can regard $P$ as an abstract simplicial complex, where the simplices are the nonempty chains.  We therefore have a geometric realisation $|P|$ (and these satisfy $|P\times Q|=|P|\times |Q|$).

*An arbitrary abstract simplicial complex $K$ need not arise from a poset, but if we let $sK$ denote the poset of simplices in $K$ then $|sK|$ is homeomorphic to $|K|$ by barycentric subdivision.

*If we write $I=\{0,1\}$ (ordered in the usual way) then $|I|$ is the unit interval.  If $f,g:P\to Q$ with $f\leq g$ then we can define $h:I\times P\to Q$ by $h(0,p)=f(p)$ and $h(1,p)=g(p)$, and then $|h|$ gives a homotopy between $|p|$ and $|q|$.

*The homeomorphism $|sP|\to |P|$ provided by barycentric subdivision is homotopic to $|m_P|$ (so in particular, $|m_P|$ is a homotopy equivalence).

The claim now follows from the simplicial approximation theorem.  I think I first saw this kind of formulation in a book by Rourke and Sanderson.

A: This is an interesting line of questions, but I think it doesn't quite work as stated.  First off, your notion of "homotopy" is not an equivalence relation (as far as I understand it), so it won't agree with a topological notion.
But there are also other issues; basically, any notion of "poset homotopy classes" along the lines you suggest will have finitely many classes of maps between two spaces, unlike real homotopy classes.
For instance, the poset $P = \{x,y,z,w\}$ with $x > z$, $x > w$, $y > z$, and $y > w$ corresponds to a finite topological space that is weakly homotopy equivalent to $S^1$, so $\pi_1(P) = \mathbb{Z}$.  But there are only finitely many poset maps from $P$ to $P$, even before taking any homotopy equivalence.


text:
Q: How to get current caller/principal in JMX mbean? I have one case which works on JBoss 4.2.

*

*Client login (with JAAS, ClientLoginModule)

*Client get JMX connection from JBoss JMX server

*Client call mbean API;

Server will check current caller/principal is, whether he/she has the enough privilege to do the action.
Now with Wildfly 9, we do the similar thing, moreover, we have set the username/password when getting JMX connection.
// urlString likes:service:jmx:remote://localhost:9999
JMXServiceURL serviceURL = new JMXServiceURL(urlString);
Map<String, Object> env = new HashMap<String, Object>();
String[] creds = new String[2];
creds[0] = username_;
creds[1] = password_;
env.put(JMXConnector.CREDENTIALS, creds);
JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, env);
MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();

However, at step3, JMX server find current caller/principal is null.
Do you know why? Or how to resolve this.
Are there any interceptors for JMX just like EJB?


text:
Q: Getting a print line to only print once and printing the line number of a file How do I keep "No Duplicates Found" print line from repeating instead of only getting it at the end and how do I print the line number of a file that I read into my program?
import java.util.*;
import java.io.*;

public class b{
    public static void main( String args[] ) throws Exception{
        Scanner infile = new Scanner( new File( args[0] ) );
        HashSet<String> h = new HashSet<String>();

        while(infile.hasNext()){
            String word = infile.next();
            if(h.contains(word)){
                System.out.println("DUPLICATE at line" + " " +  );
            }else if(!h.contains(word)){
                System.out.println("No Duplicate Found");
            }else{
                h.add(word);
            }
        }
    }
}

A: import java.util.*;
import java.io.*;

public class b{
    public static void main( String args[] ) throws Exception{
        Scanner infile = new Scanner( new File( args[0] ) );
        HashSet<String> h = new HashSet<String>();
        boolean noDuplicateFound;
        lineCount = 0;

        while(infile.hasNextLine()){
            lineCount++
            String word = infile.next();
            h.add(word);
            if(h.contains(word)){
                System.out.println("DUPLICATE at line: " + lineCount);
            }else if(!h.contains(word)){
                noDuplicateFound = true;
            }
        }
        if(noDuplicateFound)
            System.out.println("No Duplicate Found");
    }
}


text:
Q: cannot resolve symbol '__builtin_va_start' Visual Studio linux remote debug working on converting a C project to c++, this code works in a normal C++ project, but when I started remote debugging to speed up testing, I am no longer able to use the va_start macro
#include "Utilities.h"
#include <cstdarg>
#include <stdarg.h>
void Utilities::PrintLine(const char* text, ...)
    {
        char buffer[100];
        va_list args;         // resolved just fine
        va_start(text, args); // cannot resolve
        vsprintf(buffer, text, args);
        va_end(args);         // cannot resolve
        std::cout << buffer << "\n";
    }

A: I don't recognise your use of va_start . The following will work:
#include <iostream>
#include <cstdarg>

void PrintLine(const char* fmt, ...)
{
   char buffer[100];
   va_list args;
   va_start(args, fmt);
   vsprintf(buffer, fmt, args);
   va_end(args);
   std::cout << buffer << std::endl;
}

PrintLine ("var arg %d %d %d %d", 1, 2, 3, 4);


text:
Q: Change on the state of one component is affecting others (from same type) Having several components from the same type in one page, when changing the state of one of them it's affecting all!

state = {
    ...,
    projectErrorMessage: 'NA'
};

{ this.state.projectErrorMessage !== null ?
                                /*<Warning20 id={'ProjectError.'+this.props.project.Name} className="Error" alt={this.state.projectErrorMessage}/>*/
                                <Tooltip direction="bottom" renderIcon={Warning20} className="Error">

                                        {this.state.projectErrorMessage}

                                </Tooltip>
                            : null}

If I clear the project error message from one component, it clean it from all!
I'm passing the key inside from the wrapper component:

                        {filteredProjects.map(item =>
                            <Project
                                key={item.Name}
                                project={item}

Sandbox with all code:
https://codesandbox.io/s/fragrant-morning-267l5

A: Every project component listens to service.on("projectErrorClean", this.cleanProjectError);, so if that is called, all errors are cleared. You should pass the id of the cleared error to the service, so that only the one component with the matching id clears its errors. Same for all the other services. Hope this helps.


text:
Q: Excel VBA IfElse I am new to this forum and VBA for Excel.
I want to compare the value of a cell (called "FOO", which has a simple excel formula in it = (C9/(C6+C7))*100, this outputs a % figure) to some other cell values (which I have called "Red" (value is an integer = 125), "Amber" (115), "Yellow" (105) and "Green" (95).  Basically, the code I want to write should write a string value into a cell called "indicator" - either Red, Amber, Yellow, Green.
I tried the code below, but I cant understand why the code isn't outputting to the Indicator Cell...its been a long exhausting week, and my brain is addled by my toddler - please help!
Option Explicit

Sub check()

Dim FOO As Long
Dim Red As Long
Dim Amber As Long
Dim Yellow As Long
Dim Green As Long
Dim Indicator As String

With ThisWorkbook.Sheets("test")

 FOO = .Range("C8").Value
 Indicator = .Range("E4").Value
 Red = .Range("A1").Value
 Amber = .Range("A2").Value
 Yellow = .Range("A3").Value
 Green = .Range("A4").Value

End With

If FOO < Yellow Then
Indicator = "Green"

ElseIf FOO < Amber Then
Indicator = "Yellow"

ElseIf FOO < Red Then
Indicator = "Amber"

ElseIf FOO >= Red Then
Indicator = "Red"

End If

End Sub

PS, I had a go using Case If Select, but I cant make that work either ...I would be interested if there is a way of doing what I want using this function, as it seems more elegant.

A: This is not required Indicator = .Range("E4").Value
This is required Sheets("test").Range("E4").Text = Indicator before End Sub


text:
Q: Velocitiy of the mass on the moveable spring system
Actually I am confused at the this question. Generally kinetic energy is not conservative at momentum questions if there is no elastic collision but there is no friction on the system too.
Should I use energy conservation on the spring or not? Could you explain when should I use energy equality?

A: There is no friction and no inelastic collision so, yes, energy is conserved. The energy of the compressed spring is $\frac 1 2 kd^2$ so conservation of energy gives you:
$\frac 1 2 mv_m^2 + \frac 1 2 Mv_p^2 = \frac 1 2 kd^2$
and conservation of momentum gives you:
$mv_m + Mv_p = 0$


text:
Q: Removing null values from bag after group? I have the following:
(id: int, names: chararray)
And I group by id, creating a bag of names. I see that in the bag of names, there may be a null value. How do I remove null values from the bag?

A: You can use FILTER nested in FOREACH to remove tuples from the bag created by GROUP BY.
inpt = LOAD '...' as (id: int, names: chararray);
grp = GROUP inpt BY id;
result = FOREACH grp {
   no_nulls = FILTER inpt BY names is not null;
  GENERATE group, no_nulls;
};

Or just filter null names before grouping:
inpt = LOAD '...' as (id: int, names: chararray);
no_nulls = FILTER input BY names is not null;
grp = GROUP no_nulls BY id;


text:
Q: Can you have a pin floating on a microcontroller
Possible Duplicate:
Is it really a bad idea to leave an MCU input pin floating?

I am using a pic microcontroller that has about 36 GPIO pins, I am only using 31 of them, is it ok to have the ones that I don't use just floating or do I have to connect them to Vdd or Vcc

A: Floating pins can cause high power consumption. Microchip recommends making unused pins outputs and setting them low.

A: Not all IO pin architectures are the same. In fact, they are usually more different than one would expect. Usually either High-Z(floating) or Open Drain Low will yield the lowest power consumption, as documented in the datasheet or references for the part. On some devices not even all the IOs will have the same architecture so it is even possible that some unused pins should be left floating while others should be driven low or even configured for use by a certain peripheral for minimum consumption.In some applications, other parameters may matter more than low power consumption, like ESD tolerance or handling ruggedness. Again, the answers may be different part to part and pin to pin and requirements should be considered.In short, best not to make assumptions about black box systems. Look it up, take measurements, or contact a support engineer.


text:
Q: How can I replicate this js Geospatial query in morphia? Querying geospatial data in mongodb looks straight forward enough through the shell script, however, I'm trying to replicate some code in morphia (playmorphia).
Get all points within a certain radius, docs say:
> center = [50, 50]
> radius = 10
> db.places.find({"loc" : {"$within" : {"$center" : [center, radius]}}})

Here's my code in my Peak model:
Double[] loc = new Double(2);
// it's set to my [Longitude, Latitude]

List<Peak> peaks = play.modules.morphia.Model.ds().find(Peak.class).field("loc").near(loc[0], loc[1], 10/111.12).limit(50).asList();

It works but am I doing something wrong by using the ds().find()? Is there a more elegant way to do this using the model e.g. Peak.find..? Thanks!

A: You need to put indexes on geo fields.
Sample code from my project:
@Indexed(IndexDirection.GEO2D)
public Double[] geo = new Double[2];

List<User> pharmacist = MorphiaQuery.ds()
.createQuery(User.class)
.filter("isPharmacist",true)
.field("geo")
.within(nelat, nelng, swlat, swlng)
.field("geo")
.near(u.geo[0], u.geo[1])
.limit(limit)
.asList();

Check the manual:
http://code.google.com/p/morphia/wiki/Query#Geo-spatial

A: **@Indexed(IndexDirection.GEO2D)
    public Double[] geo = new Double[2];
public static string getResult`enter code here`() {
        DB datastore = ConnectionFactory.getInstance().getDatabaseMongo();
        double[] near = { 20.593684, 78.96288 };
        BasicDBObject basicDBObject = new BasicDBObject();
        basicDBObject.put("type", "Point");
        basicDBObject.put("coordinates", near);
        BasicDBObject geoNearParams = new BasicDBObject();
        geoNearParams.append("geoNear", <collection name>);
        geoNearParams.append("near", basicDBObject);
        geoNearParams.append("spherical", true);
        geoNearParams.append("maxDistance", 100);
        geoNearParams.append("limit", 10);
        CommandResult commandResult = datastore.command(geoNearParams);
        commandResult.getErrorMessage();
        Object data = commandResult.get("results");
        System.out.println(data.toString());
    }**


text:
Q: Recreating a simple table from Kenneth French's website (link in the description) I need someone help with recreating the following table in latex:

link: http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/six_portfolios.html
Here's what I have:
\begin{tabular}{ l l| l }
 & Small Value & Big Value  \\ \hline
 & Small Neutral & Big Neutral  \\ \hline
 & Small Growth & Big Growth \\
\end{tabular}

Any help?
Best regards,
Martin

A: You're almost there; the missing texts can be added using a \raisebox of 0pt depth and height:
\documentclass{article}

\begin{document}

\noindent
{
\renewcommand\arraystretch{1.3}
\begin{tabular}{ l l| l }
& \multicolumn{2}{c}{Median ME}
\\
\raisebox{-0.6\normalbaselineskip}[0pt][0pt]{70th BE/ME percentile} &
  Small Value & Big Value
\\ \cline{2-3}
\raisebox{-0.6\normalbaselineskip}[0pt][0pt]{30th BE/ME percentile} &
  Small Neutral & Big Neutral
\\ \cline{2-3}
& Small Growth & Big Growth
\end{tabular}
}

\end{document}

Here's a suggestion with no vertical rule (in my opinion it's superfluous) and using booktabs:
\documentclass{article}
\usepackage{booktabs}

\begin{document}

\noindent
\begin{tabular}{ l l l }
& \multicolumn{2}{c}{Median ME}
\\
\raisebox{-0.6\normalbaselineskip}[0pt][0pt]{70th BE/ME percentile} &
  Small Value & Big Value
\\ \cmidrule{2-3}
\raisebox{-0.6\normalbaselineskip}[0pt][0pt]{30th BE/ME percentile} &
  Small Neutral & Big Neutral
\\ \cmidrule{2-3}
& Small Growth & Big Growth
\end{tabular}

\end{document}


text:
Q: Loading a javascript element via AJAX I am having a small problem and even after one hour of trying I can't solve it. I am using JW Player to play a song and it works all right. Below the player is the list of songs , once a song in the list is clicked I reload the div containing the player with AJAX and change the javascript below that div to play new song. The div loads properly but the player doesn't load at all after AJAX Call. There are no errors just the player can't instantiate the second time.
Here is the code which displays the player:

Loading the player...

Here is what happens when the new song is loaded:
document.getElementById("myDiv").innerHTML='';
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

And here is the response text from separate php File:

Loading the player...

But after the AJAX Call player disappears and only the text loading the player... appears. Here is the url where the player is located:
contestlancer.com/davidicus

A: InnerHTML doesn't excuse the script. Your php should respond just a path to music or video file, and then re-setup for jwplayer.
Sorry but I was out to have dinner ;-)
I think your page doesn't need ajax to get html sourp from your php, because your page already knows which music file to be played.
I don't know exactly about jwplayer, but try this code instead your original loadXMLDoc().
function loadXMLDoc(str) {
    jwplayer("myElement2").setup({
        file: str,
        title: str,
        width: '100%',
        skin: "six/six3.xml",
        height: 30
    });
}

The title will be set as file name, but your page may be ok.

A: My bad after some research I found out that even though the script is appended via JS call it is not executed so you must execute it . So anyone having the same problem please note that the script loaded via AJAX must be executed via eval function in javascript.
So in my content AJAX file I gave the id testing to the script that is :


text:
Q: mysql c# unable to connect to host (0x800004005) i've got a problem. I cannot connect to a mysql database. This is my errormessage:

MySql.Data.MySqlClient.MySqlException(0x80004005): Unable to connect
  to any of the specifed MySQL hosts.

The  i think its an misstake in this lines. I cann connect form another extern server via C (same user) to the database.
MySqlConnection mdcon;
try
{
    string myConnectionString = String.Format("SERVER={0}; " +
                    "DATABASE={1}; " +
                    "UID={2}; " +
                    "port={3}; " +
                    "PASSWORD={4};", textBox_MD_IP.Text, textBox_MD_dbname.Text, textBox_MD_user.Text, textBox_MD_Port.Text, textBox_MD_pass.Text);
    MessageBox.Show(myConnectionString);
    mdcon = new MySqlConnection(myConnectionString);
    mdcon.Open();
    MessageBox.Show("Verbindung erfolgreich!");
    mdcon.Close();
}
catch (Exception msg)
{
    MessageBox.Show(msg.ToString());
    throw;
}

I would be very happy if somebody can help me.

A: MySQL Server can be configured to allow for conenctions from localhost only, from localhost and specified other computers, or from any computer. Hence check the configuration of the server.
Also, check firewall settings of your local computer.

A: string myConnectionString = String.Format("SERVER={0};" +
                    "DATABASE={1};" +
                    "UID={2};" +
                    "port={3};" +
                    "PASSWORD={4};", textBox_MD_IP.Text, textBox_MD_dbname.Text, textBox_MD_user.Text, textBox_MD_Port.Text, textBox_MD_pass.Text);

I think shouldn't use white-spaces in the connection string.
So change "DATABASE={1}; " to "DATABASE={1};" and etc.


text:
Q: Response cookie not being sent in Fetch request I'm currently sending a cookie back from my Node server like this:
res.setHeader('Set-Cookie', [`session=${sessionCookie}; HttpOnly; Secure`]);
res.status(200).send(JSON.stringify({status: 'success'}));

When I go to Chrome, I can see in the Network call that the session cookie is received. It's not making its way over to the Application tab.
I'm then going to make my call using Fetch (have tried both 'include' and 'same-origin' but cannot find the cookie in the Fetch request.
fetch(`http://localhost:3000/api/test`,
    {
      method: 'POST',
      credentials: 'same-origin'
    })

Is there anything wrong with this setup that may be causing the cookie to not make its way into the request?

A: In options object you need to pass same-origin in mode and include in credentials.
Hope this link will help you to solve the issue
https://stackoverflow.com/a/42735086/6712441
Thanks


text:
Q: How to serialize form data by number in javascript and submit with a specific number I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.

<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">

        <a href="user/<?php echo $username;?>">
         <img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">

          <input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
          <input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
          <input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
          <input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">

            <button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>

    </form>

javascript code

$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
  e.preventDefault();

    var add_comments = $("#add_comments").val();
    var question_id = $("#question_id").val();
    var answer_id = $("#answer_id").val();
    // var session_id = $("#session_id").val();

    if(add_comments == "" ){
        $("#error-message").html("All fields are required!").slideDown();
        $("#success-message").slideUp();

    }else{
  //Ajax
  $.ajax({
    url: "include/forms-data/comments.php",
    type: "POST",
    data: {
        add_comments: add_comments,
        question_id: question_id,
        answer_id: answer_id
    },
    success: function(data) {
      if (data != 0) {
          $("[id^=postCommentsForm").trigger("reset");
            $("#success-message").html("Question Added Successfully!").slideDown();
            $("#error-message").slideUp();
      } else {
        //alert("Can't save record");
            $("#error-message").html("Something went wrong!").slideDown();
            $("#success-message").slideUp();
      }
    }
  });

        }
      });
  });

How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.

A: Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
    $("[id^=comments]").click(function(e) {
      var element_id = this.getAttribute("id");
    });
});

Live Demo:

$(document).ready(function() {
    $("[id^=comments]").click(function(e) {
      console.log($(this).attr('id'));
    });
 });

<button id='comments1'>b</button>
<button id='comments2'>a</button>


text:
Q: CImg does not find function draw_text I'm trying to use the CImg library, but I can't get it to work. I'm working on a mac in terminal and I wrote a hello world program
#include "CImg.h"
using namespace cimg_library;
int main() {
const unsigned char purple[] = { 255,0,255 };
CImg<unsigned char>(640,400,1,3,0).draw_text("Hello World",100,100,purple).di\
splay("My first CImg code");
return 0;
}

which requires the "draw_text" function of the library. I included the header and compiled like
g++ -o hello_word.exe hello_world.cpp -O2 -L/usr/X11R6/lib -lm -lpthread -lX11 -I/opt/X11/include

The error I get is:
error: no matching function for call to 'cimg_library::CImg<unsigned char>::draw_text(const char [12], int, int, const unsigned char [3])'

Any ideas? Thank you!

A: Look at the reference doc for the signatures of the functions CImg<T>::draw_text() :
http://cimg.sourceforge.net/reference/structcimg__library_1_1CImg.html#a8ff42ad9cc3368b2d70621c23d36cf17
And now, try this :
CImg<unsigned char>(640,400,1,3,0).draw_text(100,100,"Hello World",purple).display("My first CImg code");

Also look at all examples provided in the CImg Library package (folder examples/), there are a lot of things to learn from them.


text:
Q: fontspec-color not working correctly with microtype package If I use the fontspec package together with the microtype package, the color-feature of fontspec does only colarize the last line of the paragraph instead of the whole paragraph, as the grouped \addfontfeature-command should work.
\documentclass{article}

\usepackage{fontspec}
\usepackage{xcolor}
\usepackage{microtype}

\setmainfont{DejaVu Serif}

\begin{document}
\twocolumn%
Test. Test. Test. Test. Test. Test.
Test. Test. Test. Test. Test. Test.
Test. Test. Test. Test. Test. Test.
Test. Test. Test. Test. Test. Test.
Test. Test.

\begingroup%
    \addfontfeature{Color=blue}%
    Test. Test. Test. Test. Test. Test.
    Test. Test. Test. Test. Test. Test.
    Test. Test. Test. Test. Test. Test.
    Test. Test. Test. Test. Test. Test.
    Test. Test.
\endgroup%

Test. Test. Test. Test. Test. Test.
Test. Test. Test. Test. Test. Test.
Test. Test. Test. Test. Test. Test.
Test. Test. Test. Test. Test. Test.
Test. Test.
\end{document}

The result looks like this:
.
I use LuaLaTeX with fontspec.sty (2013/03/16 v2.3a) and microtype.sty (2013/03/13 v2.5).

A: It is a bug in luaotfload, not in microtype nor fontspec. (@AndrewStacey had already reported this a while ago to me.) The same happens with plain luatex:
\input luaotfload.sty
\font\x="DejaVu Serif":color=FF00FF;expansion=default; \x
\pdfadjustspacing=2
\hsize=7cm
Test. Test. Test. Test. Test. Test. Test. Test. Test. Test. Test. Test.
Test. Test. Test. Test. Test. Test. Test. Test. Test. Test. Test. Test.
\bye

Only those lines appear in colour where no expansion takes place (here, the last line). It seems that the colourizing routine from luaotfload (in file otfl-font-clr.lua) doesn't recognize the expanded fonts as instances of the same base font.
EDIT: This bug has been fixed in luaotfload v2.2, thanks to Élie Roux and Philipp Gesang.


text:
Q: How to use bash return code in conditional? I have a small piece of code which checks IP address validity :
function valid_ip()
{
    local  ip=$1
    local  stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        if [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]; then
            stat=1
        else
            stat=0
        fi
    fi
    return $stat
}

But I am having problems with its usage in bash conditionals. I have tried many techniques to test its return value but most of them fail on me.
if [[ !$(valid_ip $IP) ]]; then

if [[ $(valid_ip IP) -eq 1 ]]; then

etc. etc. Can anyone suggest what should I do here ?
EDIT
Following your suggestions I have used something like :
  if valid_ip "$IP" ; then
      ... do stuff
  else
      perr "IP: \"$IP\" is not a valid IP address"
  fi

and I get errors like

IP: "10.9.205.228" is not a valid IP address

A: The return code is available in the special parameter $? after the command exits. Typically, you only need to use it when you want to save its value before running another command:
valid_ip "$IP1"
status1=$?
valid_ip "$IP2"
if [ $status1 -eq 0 ] || [ $? -eq 0 ]; then

or if you need to distinguish between various non-zero statuses:
valid_ip "$IP"
case $? in
    1) echo valid_IP failed because of foo ;;
    2) echo valid_IP failed because of bar ;;
    0) echo Success ;;
esac

Otherwise, you let the various operators check it implicitly:
if valid_ip "$IP"; then
    echo "OK"
fi

valid_IP "$IP" && echo "OK"

Here is a simple, idiomatic way of writing valid_ip:
valid_ip () {
    local ip=$1
    [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && {
        IFS='.' read a b c d <<< "$ip"
        (( a < 255 && b < 255 && c < 255 && d << 255 ))
    }
}

There are two expressions, the [[...]] and the { ... }; the two are joined by &&. If the first fails, then valid_ip fails. If it suceeds, then the second expression (the compound statement) is evaluated. The read splits the string into four variables, and each is tested separately inside the arithmetic expression. If all are true, then the ((...)) succeeds, which means the && list succeeds, which means that valid_ip succeeds. No need to store or return explicit return codes.

A: No parentheses needed if the exit status is inspected:
if valid_ip $IP ; then
    ...

Just call the function in the way you would call any other command.


text:
Q: Why are Asynchronous processes not called Synchronous? So I'm a little confused by this terminology.
Everyone refers to "Asynchronous" computing as running different processes on seperate threads, which gives the illusion that these processes are running at the same time.
This is not the definition of the word asynchronous.
a⋅syn⋅chro⋅nous
–adjective
1. not occurring at the same time.
2. (of a computer or other electrical machine) having each operation started only after the preceding operation is completed.

What am I not understanding here?

A: The word "synchronous" implies that a function call will be synchronized with some other event.
Asynchronous implies that no such synchronization occurs.
It seems like the definition that you have there should really be the definition for "concurrent," or something.  That definition looks wrong.

PS:
Here is the wiktionary definition:
asynchronous

*

*Not synchronous; occurring at different times.

*(computing, of a request or a message) allowing the client to continue during processing.

Which just so happens to be the exact opposite of what you posted.

A: I believe that the term was first used for synchronous vs. asynchronous communication. There synchronous means that the two communicating parts have a common clock signal that they run by, so they run in parallel. Asynchronous communication instead has a ready signal, so one part asks for data and gets a signal back when it's available.
The terms was then adapted to processes, but as there are obvious differences some aspects of the terms work differently. For a single thread process the natural way to request for something to be done is to make a synchronous call that transfers control to the subprocess, and then control is returned when it's done, and the process continues.
An asynchronous call works just like asynchronous communication in the aspect that you send a request for something to be done, and the process doing it returns a signal when it's done. The difference in the usage of the terms is that for processes it's in the asynchronous processing that the processes runs in parallel, while for communication it is the synchronous communication that run in parallel.
So "computer or electrical machine" is really a too wide scope for making a correct definition of the term, as it's used in slightly different ways for different techniques.

A: I would guess it's because they are not synchronized ;)
In other words... if one process gets stopped, killed, or is waiting for something, the other will carry on

A: I think there's a slant that is slightly different to most of the answers here.
Asynchronous means "not happening at the same time".
In the specific case of threading:

*

*Synchronous means "execute this code now".

*Asynchronous means "enqueue this work on a different thread that will be executed at some indeterminate time in the future"

This usually allows you to "do two things at once" because of reasons like:

*

*one thread is just waiting (e.g. for data to arrive on a serial port) so is asleep

*You have multiple processors, so the two threads can run concurrently.

However, even with 128 processor cores, the case is the same: the work will be executed "at some time in the future" (if perhaps the very near future) rather than "now".

A: It means that the two threads are not running in sync, that is, they are not both running on the same timeline.
I think it's a case of computer scientists being too clever about their use of words.
Synchronisation, in this context, would suggest that both threads start and end at the same time. Asynchrony in this sense, means both threads are free to start, execute and end as they require.

A: Your second definition is more helpful here:
2. [...] having each operation started only after the preceding operation is completed.

When you make an asynchronous call, that call might not be completed before the next operation is started. When the call is synchronous, it will be.

A: It really means that an asynchronous event is happening independently of other events whereas a synchronous event would be happening dependent of other events.

A: It's like: Flammable, Inflammable ( which mean the same thing )
Seriously -- it's just one of those quirks of the English language.  It doesn't really make sense.  You can try to explain it, but it would be just as easy to justify the reverse meanings.

A: Many of the answers here are not correct. IN-dependently has a beginning particle that says NOT dependently, just like A-synchronous, but the meaning of dependent and synchronous are not the same! :D
So three dependent persons would wait for an order, because they are dependent to the order, but they wait, so they are not synchronous.
In english and any other language with common roots with a, syn and chrono (italian: asincrono; spanish: asincrónico; french:
asynchrone; greek: a= not syn=together chronos=time)it means exactly the opposite.
The terminology is UTTERLY counter-intiutive. Async functions ARE synchronous, they happen at the same time, and that's their power. They DO NOT wait, they DO NOT depend, they DO NOT hold the user waiting, but all those NOTs refer to anything but synchronicity :)
The only answer possibly right is the CLOCK one, although it is still confusing. My personal interpretation is this story:
"A professor has an office, and he makes SYNCHRONOUS CALLS for students to come. He says out loud in the main university hall: 'Hey guys who wants to talk to me should come at 10 in the morning tomorrow.', or simply puts a sign saying the same stuff.
RESULT: at 10 in the morning you see a long queue. People had the same time so they came in in the same moment and they got "piled up in the process".
So the professor thinks it would be nice for students not to waste time in the queue (and do synchronous operations, that is, do parallel stuff in their lives at the same time, and that's where the confusion comes).
He decides students can substitute him in making ASYNCHRONOUS CALLS, that is, every time a student ends talking with him, the students may, e.g., call another student saying the professor is free to talk, in a room where students may do whatever they like in the meantime. So every student does not have a single SYNCHRONOUS CALL (10 in the morning, the same time for all) but they have 10, 10.10, 10.18, 10.27.. etc. according to the needed time for each discussion in the professor office."
Is that the meaning of having the same clock, @Guffa?


text:
Q: Linq skip is skipping the wrong results? I'm using a linq statement to get my company reviews, but it's skipping the wrong results.
If i pass it currentPage = 1 it gets the right results, if i pass it currentPage 2 it does it wrong. The amount of reviews per page is 10. The GUID id is also passed on correctly.
public IList<SupplierReview> GetAmount(int pageAmount, int currentPage, Guid companyId)
    {
        var total = _context.SupplierReview.Count();
        var skipAmount = pageAmount * (currentPage - 1);
        if (skipAmount < total)
        {
            if (pageAmount < (total - skipAmount))
            {
                //return the page amount of reviews

                return _context.SupplierReview
                    .Where(x => x.Company.Id == companyId)
                    .OrderBy(x => x.Id)
                    .OrderBy(x => x.ReviewDate)
                    .Skip(skipAmount)
                    .Take(pageAmount)
                    .ToList();
            }
            else
            {
                //if the left amount is less than the pageAmount,
                //then only the leftovers should get taken

                return _context.SupplierReview
                    .Where(x => x.Company.Id == companyId)
                    .OrderBy(x => x.Id)
                    .OrderBy(x => x.ReviewDate)
                    .Skip(skipAmount)
                    .Take(total - skipAmount)
                    .ToList();
            }
        }
        //if nothings left, return null
        return null;
    }

The mistake is probably silly, but I can't seem to see it... Any ideas?
Thanks!

A: My first thought about skipping too many pages was incorrect. It looks like you are mixing up the total count:
var total = _context.SupplierReview.Count();
then the count which match your company.ID:
Where(x => x.Company.Id == companyId)
I feel like the total calculation should include this Where? Look at your else condition. If you .Take(total - skipAmount), and total was calculated without regard to your company ID, you will end up trying to take too many, potentially a non-existent amount.

A: It is fine to specify bigger number than (actual)collection count to both Skip & Take extension methods, in this case you get an empty collection.
That means we can refine the code as shown below.
 return _context.SupplierReview
                    .Where(x => x.Company.Id == companyId)
                    .OrderBy(x => x.Id)
                    .OrderBy(x => x.ReviewDate)
                    .Skip(pageAmount * currentPage) //use currentPage + 1 if index assumed to start with 1
                    .Take(pageAmount)
                    .ToList();


text:
Q: Start Node server and run test in CICD I am currently trying to deploy some tests to Azure pipelines (but this should apply to any CICD framework)
I have an express project, and I am using supertest with mocha to run tests locally and everything is fine.
Now I want to deploy to production, and I want to run the tests in the pipeline before deployment happens.
The thing is that since these tests are running against http, they need a server running.
So, in my pipeline I have
npm install
 npm start
 npm test
But the thing is that npm test is not running when the server is started, but instead it just hangs in the server running.
Is there a way to start the tests when the server starts? and then stop the server when the tests are finished?
Or is there a better way to achieve all this?

A: If you're using supertest I would suggest to export the express app for the tests instead of running it as shown in their docs, and then you would only need to run npm install and npm test.
For example:
app.js
const express = require('express');
const app = express();

// Add middlewares

module.exports = app;

test.spec.js
const app = require('../app.js');

request(app)
  .get('/user')
  .set('Accept', 'application/json')
  .expect('Content-Type', /json/)
  .expect(200)
  ...


text:
Q: Too many characters in character literal error with embed tag in aspx page I'm struggling with a piece of code and getting error when using this code. what is the correct way to append Eval in this code ?
when I used
src='https://drive.google.com/viewerng/viewer?embedded=true&url=<%# Eval("InvoiceFilePath") %>'

It shows that embed tag must end with "/", when I close embed tag, the embed behavior doesn't work as expected.
    <asp:TemplateField HeaderText="View files">
        <ItemTemplate>
<embed src="https://drive.google.com/viewerng/viewer?embedded=true&url=<%# Eval('InvoiceFilePath') %>" runat="server" width="100" height="75">

         </ItemTemplate>
   </asp:TemplateField>

A: Try this it must work.
<asp:templatefield headertext="View files">
        <ItemTemplate>
<embed src="https://drive.google.com/viewerng/viewer?embedded=true&url='<%#Eval("InvoiceFilePath") %>' " runat="server" width="100" height="75">

         </ItemTemplate>
   </asp:templatefield>


text:
Q: Distributed Computing with Java. Best approach? I am developing a system, which can be in very simple terms described as below:

*

*There are multiple servers, each running the same Java App (for scalability).

*There is a common database server, which each application server talks to.

*Millions of clients, each connecting to one random server. Each client has one open socket with one server.

Now say, Client A is connected to Server A, and wants to send a message to Client B.
What is the best approach for this kind of problem? Whats the best way to keep track which client is connected to which server, and how to make the servers talk to each other.
This is a Java specific problem. If there was only one server, it could have been done through inter thread communication. But the problem is for multiple servers. Also, are there any open source libraries that make this task easier?

A: Either your servers need to be able to look up the location of clients (perhaps via the database, perhaps by a dedicated address server) or you need to remove the randomness by using hashing approaches or some other non-random partitioning, as suggested by Kru in the comments. (Either way, you have issues if a server goes down, but perhaps that's outside the scope of your question).
Your servers then need to be able to forward messages to the appropriate other server. The simplest way is for them to maintain socket connections to each other.
Another approach is to use a message queuing system. You might consider using a high-performance brokerless system such as ZeroMQ, which provides a socket-like API, but higher throughput and failure tolerance, plus richer messaging patterns. Higher-level messaging products can probably implement most of the system you describe anyway (handling scalability, addressing etc).
You might be able to use an existing protocol like XMPP rather than inventing your own distributed messaging system.

A: I believe you're looking for a Distributed Hash Table. You could use a Chord protocol, and you use the hash of the IP as the key. Using this key, the protocol will be able to route to the appropriate server that contains the key. (the server that maintains the connection with client B).
You can also check out existing java implementations of a DHT such as http://tomp2p.net/


text:
Q: Why some materials pass light and others do not? And what property is needed to own for this?
I can`t find this information

A: Absorption of Light by Material:
When a light wave strikes the surface of an object, a variety of things can happen. One of these things is called resonance. When resonance occurs between a light wave and an object, the object absorbs the energy of that light wave. The light energy stays inside the object when resonance occurs, and this is the reason for absorption of light.
What is a Transparent object?
An object is said to be transparent when light passes through it without being dispersed, or scattered. Clear glass is transparent, and clean water is transparent. Although light travels through these materials, we know that they also block things like wind, sound waves and the movements of people and animals. For example, you can't walk through glass. So, how can a light wave pass through the glass without being changed at all?
Light waves are absorbed by an object when the frequency of the light wave matches the resonant frequency of the object. Absorption occurs when none of the light waves are transmitted through the object. Transmission, if you weren't sure, just means the passing of electromagnetic waves through a material. In the case of objects that are transparent, all of the light waves pass through. Transparent objects exhibit complete transmission of the light waves through the object.

An object looks transparent because light waves pass through unchanged.
What really happens inside glass materials when a light wave passes through? We know that there aren't any tunnels connecting one side to the other. So, what's going on? When a light wave strikes the surface of the glass, it sets the electrons vibrating at a certain frequency. This frequency is not the resonant frequency of the glass. The vibrations pass from the surface atoms to the neighboring atoms and then on to more atoms through the bulk of the glass. The frequency doesn't change when the vibrations pass from one atom to another. Once this energy gets to the other side of the glass, it is re-emitted from the opposite surface. The light wave effectively passes through the glass unchanged. As a result, we can see straight through the glass, almost as though it isn't even there. So, now you know: transparency occurs because of the transmission of light waves through the bulk of an object.
When a light wave is neither absorbed nor transmitted by an object, then it is reflected.
Reflection - another cause for opacity:
Reflection is a change in the direction of a wave when it strikes a surface. Reflection can be specular (as in glossy or smooth-surfaced objects) or it can be diffuse (as in objects with rough surfaces). In either case, reflection occurs because the vibrations of the surface electrons do not pass their energy down through the material. Instead, they vibrate a little bit and then re-emit the energy back, away from the material. When this happens, the object appears to us as opaque. Opaque materials do not allow transmission of light waves. In other words, we can't see through an opaque object. We can only see the surface because the light waves are re-emitted from the surface back to our eyes. Opacity occurs because of the reflection of light waves off the surface of an object.

When light waves are reflected, an object appears opaque.

So, now you know that opacity occurs because of:

*

*Absorption of light by material

*Reflection of light by surface


text:
Q: Event Receiver for two lists. When inserting in one List it updates the second list How do I add an Event Receiver to two lists?
One must be updated when an Item is inserted in a second list.
I used public override void ItemAdding(SPItemEventProperties properties)
But what should i put in this method ?

A: Grzegorz,
What happens with Event Receivers, in the receiver in feature XML has a ListTemplateId which determines to which List template the event receiver is for... So lets say you need to add event receiver on custom list then ListTemplateId=100 or you want to add to Announcements template the ListTemplateId=104, like below:
`<Receivers ListTemplateId="100">`

Now if you attach event receiver to custom list template, the event will fire for every custom list you have in the scope! And you can identify the list in code by using properties... the SPItemEventProperties has a property called List.. which give you SPList, and you can either by GUID or Name identify the list and perform operation accordingly... What I do is create a SWITCH-CASE for different lists and perform operations according in the cases!
I hope this answered and clarify the concept of Event Receivers, you can read more over here and here
So when you have deployed the event receiver it will fire for both the lists, and you will first identify for which list it has been fired.. then code accordingly!


text:
Q: SqlClientFactory error with EF 6 - Unable to determine the provider name for provider factory I'm getting this error when I attempt access a collection within the context:
Unable to determine the provider name for provider factory of type 'Microsoft.Data.SqlClient.SqlClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
My config has the standard connection string:
<add name="someDb" connectionString="Data Source=****;Initial Catalog=****;Integrated Security=SSPI;MultipleActiveResultSets=True;" providerName="Micorsoft.Data.SqlClient" />

This has been working fine for years (the providerName was System.Data.SqlClient), now trying to upgrade to Standard2.0 with EF 6.2.
Hoping there's a fix I can make to the connection string or in the DbContext, but I'm stumped.

A: Do you have NuGet installed if not goto NuGet package manager and install then
Simply add a NuGet dependency on Microsoft.Data.SqlClient and update
this may help you.


text:
Q: why does my directive throws $unknown provider unknown provider  error:
 [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr?   p0=postbuttonsProvider%20%3C-%20postbuttons%20%3C-%20RandomBusinessCtrl
here is my code : the directive is defined as follows :
angular.module('home', ['ngAnimate', 'ui.bootstrap','ngDialog'])

.directive("postbutton", function(){
return {
    restrict: "E",
    bindToController: true,
    template: "<button>Post review</button>"
}
})

.controller('RandomBusinessCtrl',
    ['$scope','postbutton','pickRandomBusinesses','BusinessViewModel','config',
    function ($scope,postbutton,pickRandomBusinesses,BusinessViewModel,config) {

    });

my html is :

      <postbuttons></postbuttons>

A:
why does my directive throws $unknown provider

Because you are trying inject directive into controller. It doesn't make sense - you can only inject services.
Why directives are not injectable? Clearly, one might want to use its API from controller? Well, the reason why is the core or Angular app architecture. Directives being part of view layer of the application, should not be interacted from controller directly. Another important thing to understand is that services (what you inject) is intentionally singletones - while directives cannot be, of course.
In your case you don't need to worry about it: directive is registered on the same module so it's available in template.
Correct controller definition would be:
.controller('RandomBusinessCtrl' [
    '$scope', 'pickRandomBusinesses', 'BusinessViewModel', 'config',
    function ($scope, pickRandomBusinesses, BusinessViewModel, config) {

});


text:
Q: I can't stop a grails application (3.2.8) I start a grails application (3.2.8) with "grails run-app". It takes the defaults and start at "http://localhost:8080".
From IntelliJ, or even from the windows terminal I invoke "grails stop-app" and I get the following message:
| Application not found via JMX, attempting remote shutdown.
| Shutting down application...
| Error Application not running.
In application.groovy I added:
grails.project.fork.run = true
with no effect.
What is the right way to stop the server? I particularly need it when I set dbCreate = 'create-drop' to clean the database.

A: Do you have this in your build.gradle?
bootRun {
    jvmArgs('-Dspring.output.ansi.enabled=always')
    addResources = true
}

Otherwise do you have a g:include?  Could be this issue:
https://github.com/grails/grails-core/issues/10411

A: I see this with the simplest of apps in 3.3.3. I tracked it down to permissions on the Spring Boot "shutdown" endpoint. I fixed it by adding the following to grails-app/conf/application.yml:
management:
    security:
        enabled: false

Since this works, I assume "grails stop-app" is essentially doing this:
curl -X POST localhost:8080/shutdown

I'm new to Grails, so there may be a better solution that doesn't require dropping down to the Spring Boot level.


text:
Q: Sphinxql - How to use query having order by while using Sphinxql in PHP without using sphinxapi.php i have been using mysql FTS , but recently switched to sphinx for testing purpose.
installed sphinx on centos 7
Linux production 3.10.0-123.8.1.el7.x86_64 #1 GNU/Linux

sphinx.conf
source content_src1
{
    type            = mysql
    sql_host        = localhost
    sql_user        =
    sql_pass        =
    sql_db          = t_prod2
    sql_port        = 3306  # optional, default is 3306

    sql_query       = \
        SELECT content.record_num, \
                    content.title, \
                    content.category, \
                    content.upload_date, \
                    content.comments_count, \
                    content.verified, \
                    content.uploader, \
                    content.size \
                    FROM content WHERE enabled = 1

    sql_attr_uint       = record_num
    sql_attr_string = title
}

index content_index1
{
    source          = content_src1
    path            = /var/lib/sphinx/content_index1
    morphology              = stem_en

    min_word_len            = 1
    min_prefix_len          = 0
    min_infix_len           = 1
    docinfo                 = extern

}

i am using php to connect sphinxql and run queries, .like this
$sphinxql = @mysqli_connect($sphinxql_host.':'.$sphinxql_port,'','');

$sphinxql_query = "SELECT id FROM $sphinx_index WHERE MATCH('".mysqli_real_escape_string($prod1,$q)."') LIMIT  $from,$max_results";

simple queries are working fine, i.e. queries without any order by condition.
but when i tried to run sql queries having order by , sphinx is throwing errors .
i.e.
query and their errors.
SELECT id FROM $sphinx_index WHERE MATCH('".mysqli_real_escape_string($prod1,$q)."') ORDER BY title DESC LIMIT  $from,$max_results

index content_index1: sort-by attribute 'title' not found

another try, i replaced field name with @field name
SELECT id FROM $sphinx_index WHERE MATCH('".mysqli_real_escape_string($prod1,$q)."') ORDER BY @title DESC LIMIT  $from,$max_results

sphinxql: syntax error, unexpected USERVAR, expecting IDENT (or 55 other tokens) near '@title DESC LIMIT 0,25'

table has order by fields like title, category , upload_date , size , verified
so how can i use order by in my sphinxql query

update 1
i have managed to run queries "not having order by" , but queries having "order by" not working properly,doesnt gives error, gives result sets, but if i change the direction of sort by attribute , the results sets doesnt changes.
updated fields and attributes are as.
sql_field_string = title
sql_field_string = og_name
sql_field_string = hash
sql_field_string = keywords

sql_attr_timestamp = upload_date_timestamp

sql_attr_uint = category
sql_attr_uint = comments_count
sql_attr_bool = verified
sql_attr_bigint = size

A: Have you tried using that column as sql_attr_string?
http://sphinxsearch.com/docs/current.html#conf-sql-attr-string
You need at least version 2.0.1 to use an ORDER BY clause on such attribute:

Starting from 2.0.1-beta string attributes can be used for sorting and grouping(ORDER BY, GROUP BY, WITHIN GROUP ORDER BY).


text:
Q: Pygame: How can I limit this program not to get keyboard events while showing sth on display? I have a program like this. It works well bout there is a problem!
By pressing the 'Down' key it shows a circle on the screen for 5 seconds and also by 'Space-down' and 'Space-up' does something else (calculates pressing time). But I don't want it to 'calculate' when is showing the circle. in the other words I don't want it to get keyboard events (or does nothing if gets keyboard events) when is showing the circle. for this purpose I added the 'p' as a condition. it somehow works! I mean during the circle show the program doesn't calculate even if you press 'Space' key. But the problem is when the circle show gets over. It  does calculations just  as like as you pressed the 'Space' key after circle show time. I mean if you press the 'Space' key during circle show time, it does calculations immediately after when the circle show gets over.
Its like that the program gets key events even during the circle show, but waits until when the condition (p == 0 ) becomes true.
Please help me to fix this situation.
p = 0
gameloop = True
while gameloop:

for event in pygame.event.get():

    if (event.type == pygame.QUIT):
            gameloop = False

    if event.type == pygame.KEYDOWN:
        if (event.key == pygame.K_DOWN)  :

                p += 1
                start_time = time.time()
                end_time = start_time + 5
                while end_time > time.time():
                    # showing a circle on display
                p -= 1

    if (event.type == pygame.KEYDOWN):
        if (event.key == pygame.K_SPACE)  and (p == 0)  :

            # Do something

    if (event.type == pygame.KEYUP)  :
        if (event.key == pygame.K_SPACE) and (p == 0) :

            # Do somthing

A: I found out that if you press 'Space' key during circle show time it doesn't operates in that moment but after when the circle show gets over it operates immediately. It likes that you press 'Space' instantly after circle show time. therefore it takes just as long as system operate time (as I said this program calculates 'Space' key pressing time : space_up_time - space_down_time) and when you press 'Space' key during circle show time, every time it returns a time about 0.002 second which is system operate time. So to solve my problem I added another condition : h + 0.01 < time.time(). Now it works perfectly! But let me know if there is another way because one could press keys very fast maybe faster than 0.002 second !!!
start_time = time.time()
end_time = start_time + ex
while end_time > time.time():
        # Drawing a circle
h = time.time()

      if (event.type == pygame.KEYDOWN):

        if (event.key == pygame.K_SPACE)  and ( h+0.01 < time.time())  :
               # Do calculations


text:
Q: Magnetic susceptibility Currently I'm doing the simulation of Ising Model with Monte Carlo method. I got a curve which the magnetic susceptibility diverge (precisely due to finite size effect, it is not diverge but show the similar trend) when the temperature approach at critical temperature which is the point the model change from ferromagnetic state to paramagnetic state. This is what I expected as the second order phase transition, the second derivative on the free energy function is diverge. But I found so many graph which describe the magnetic susceptibility of material changing from ferromagnetic to paramagnetic got something like this
Why there is such difference?


text:
Q: Remove Discord Markdown How do I remove mark down in discord.py?
I was making an eval command but I realized that sending it with markdown eg. '```py print("example code")```', breaks it.
I want to make it easier for me and the other admin/mod to use it for debugging purposes in my bot.
@client.command()
async def eval(ctx, *,  code):
    out, err = io.StringIO(), io.StringIO()
    sys.stdout = out
    sys.stderr = err

    await ctx.channel.trigger_typing()
    await aexec(code)

    results = out.getvalue()
    errors = err.getvalue()

    await ctx.send(embed = discord.Embed(title = "Eval", description=f"Output Is \n```bash\n{results}```"))
    await ctx.send(embed = discord.Embed(title = "Code", description=f"Input Is \n```py\n{code}```"))

the above code is what I've tried so far..

A: I've been playing with your code for the past hours, I wanted to figured it out :P
This is the only way i could access the code when there was markdown in the command input.
@client.command()
async def eval(ctx, *, code):
    raw = f'{ctx.message.content}'[12:-3] # Get rid of markdown + py and last 3 ```
    #Might want to add if statements in case the input doesn't include py / something else.
    print (raw) # Testing purpose
    out, err = io.StringIO(), io.StringIO()
    sys.stdout = out
    sys.stderr = err
    await ctx.channel.trigger_typing()
    exec(raw) # no need for await

    results = out.getvalue()
    errors = err.getvalue()

    await ctx.send(embed = discord.Embed(title = "Eval", description=f"Output Is \n```bash\n{results}```"))
    await ctx.send(embed = discord.Embed(title = "Code", description=f"Input Is \n```py\n{raw}```"))
    await ctx.send(embed = discord.Embed(title = "Errors", description=f"Errors are \n```py\n{errors}```")) #Added this output to see errors


text:
Q: Unable to POST nested JSON using Invoke-WebRequest I am trying to create a script that will copy some Django permissions, modify them and then re-apply them to our instance.
I appear to have no problems reading / writing the requests, with the exception of the permissions "constraints" value. This value needs to be sent in the form of a JSON query. It appears that as the actual POST action itself needs to be performed as a JSON query, the Invoke-WebRequest cmdlet is modifying the nested JSON and adding escape characters.
An example of the POST code in question is below (the remaining part of the script appears fine and is long so have not included however can do so if needed):
$PostBody  = @{'name' = $newPermName
               'groups' = @($queGroupIDResult.results[0].id[0]) | ConvertTo-Json
               'actions' = ConvertTo-Json @($subTempResult.actions)
               'constraints' = @($subtempresult.constraints) | ConvertTo-Json}

Try  {$postResponse = Invoke-RestMethod -Body $PostBody -Headers @{ 'Authorization' = "Token $strapikey" } -Method Post -URI "$strserverurl/api/users/permissions/"
      Write-Host "--- Permission built"} #-ContentType 'application/json'
Catch{Write-Host -ForegroundColor Red "--- There was an error performing the API post query"}

An example of the 'constraints' value is:
@($subtempresult.constraints) | ConvertTo-Json
{
 "slug": "strsiteslug"
}

However when this is sent via Invoke-WebRequest it appears in the Django backend as:
"[\r\n {\r\n \"slug\": \"strsiteslug\"\r\n }\r\n]

If I do not ConvertTo-Json the @($subtempresult.constraints) value, then I just see SystemObject[] in the django backend.
I'm not really sure where to go from here, it feels as though I've tried every which way / combination of splatting / converting the variables before I try and post them with no success.


text:
Q: Convert IGrouping to IList I want to take results from a IGrouping query and put it into a list.
I tried to do do this as follow:
The Entity class
public class WordRank
{

    public string Word { get; set; }
    public string WordScore { get; set; }
}

The method
     public void DisplayArticles()
    {
        var articles = this.articleRepository.TextMinerFindBy(this.view.Client, this.view.Brand, this.view.Project, this.view.Term, this.view.Channel, this.view.Begin, this.view.End, this.view.OnlyCategorized, this.view.UniquePosts);
        string snippets = string.Empty;

        foreach (var article in articles)
        {
            snippets = snippets + " " + article.Snippet;
        }

        Regex wordCountPattern = new Regex(@"[.,;:!?""\s-]");
        string snippetCollection = wordCountPattern.Replace(snippets, " ");

        var words = snippetCollection.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        var groups = words.GroupBy(w => w);

        foreach (var item in groups)
        {
            this.view.Words.Add(item);
        }
    }

But is not possible to assign item to IList.
Can anybody give me light?
Thanks

A: EDIT: Okay, now that we know what you're trying to do (see comments):
foreach (var group in groups)
{
    this.view.Words.Add(new WordRank { Word = group.Key,
                                       WordScore = group.Count() });
}

Or if you're happy to replace the whole of this.view.Words with a List<WordRank>, replace the whole bottom bit with:
this.view.Words = words.GroupBy(w => w)
                       .Select(new WordRank { Word = group.Key,
                                              WordScore = group.Count() })
                       .ToList();


text:
Q: How To Make Log In system Using vb.net and SQL Server I'm using this code and every time I press the loginBTN where my code are nothing happens im done with connecting in the server which is SQL Server
 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loginbtn.Click
    Dim username As String
    Dim password As String
    Dim password1 As String

    Dim oleConn As New SqlConnection(main.conString)
    oleConn.Open()

    Try
        Dim login As String = "Select *from admin where username = '" & usernametxt.Text & "' AND password = '" & passwordtxt.Text & "' "

        Dim command As New SqlDataAdapter(login, oleConn)
        Dim command1 As New SqlCommand(login, oleConn)
        Dim reader1 As SqlDataReader = command1.ExecuteReader()

        If reader1.HasRows Then
            While reader1.Read
                username = reader1("username")
                password = reader1("password")

                password1 = passwordtxt.Text()

                If username = usernametxt.Text And password = password1 Then
                    main.Show()
                    Me.Hide()
                End If
            End While
        Else
            PictureBox1.Show()
            errorLabel.Show()
            Beep()
            'MsgBox("wrong password or username")
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        oleConn.Close()
    End Try
End Sub


text:
Q: Identifying paths between nodes on a graph, whilst finding potential loops Lets say I have a graph like the following:

It is directed, and can also have cycles. If I wanted to find all the possible routes from node 0 to node 9, I have found that I could use a depth-first search algorithm, keeping the list of visited nodes in a collection to prevent the cycles from affecting the algorithm.
However, what I haven't been able to work out is how I can adapt DFS to find which nodes could be passed more than once when travelling between node 0 and node 9.
In the example, we can see that nodes 1, 5, 6, and 3 could be accessed more than once if travelling from 0 to 9, due to the loops. However, I'm not sure how this can be effectively implemented in an algorithm.
I have already tried counting the number of times a node is visited, but this seems to cause the algorithm to iterate infinitely.
How can I find all possible paths between two points in a directed graph, whilst simultaneously finding the points that could be accessed more than once (in a loop) on the way?

A: You can do it separately in linear time.
Let's find strongly connected components and shrink them. Now we've got a DAG.
A node can be passed twice (or more times) iff the size of the component is greater than 2, it's reachable from the source node, and the target node is reachable from it.
If you're fine with exponential time, you can use the following fact: if there a path that contains the given node twice, there is such a path with at most 3n vertices (let's take a look at its two occurrences. We can cut out all cycle between them. We can also cut out all cycle before and after them).
That is, you can keep using your recursive solution (which never terminates), but always kill a branch of recursion if you've got more than 3n nodes in the path (there might be an even better bound than 3n, but this one is easy to prove).


text:
Q: Creating Whatsapp bot for removing idle members? Scenario
i am in a test project to build a bot for a Whats App group which could analyze the members involvement status based on their post counts or their idleness for a while and it should remove such members if they continue to be idle for (say) 2 weeks.
Question
is it possible to create such a bot in PHP or else should i stick with java ? i don't want to use any third party API i like to code it from scratch. i need a suggestion to do this.
the reason i that i mentioned PHP is , there exists free PHP hosting online so there will not be a purchase of hosting for this small test project.


text:
Q: How to impute data from one dataframe to another in r I have two data frames df1 and df2
df1= data.frame( ts = c('2020-01-15', '2020-01-16' , '2020-01-17', '2020-01-20', '2020-01-22','2020-
                         01-24','2020-01-27','2020-01-30','2020-01-31'),
              lla=c(12,13,14,15,16,17,18,19,20),
              llb=c(1,2,3,4,6,5,9,8,7),
              llc=c(0.6,1.6,2.6,3.6,4.6,5.6,6.6,7.6,8.6),
              lld=c(10,11,12,13,14,15,16,154,167))

df2= data.frame( ts = c('2020-01-17','2020-01-24','2020-01-31'),
             lla=NA,llb=NA,llc=NA,lld=NA)

if the date of df2$ts matches df1$ts it will look back 4 days ago and impute the max value of every column in df2.
For example:
the 1st value of df2$ts is "2020-01-17" matches to df1$ts .. it will look back 4 days means , it will filter out the data of df1$ts between 2020-01-13 to 2020-01-17 so we get
#code
df1[(as.Date(df1$ts)>= (as.Date(df2[1,1])-2)) &
   (as.Date(df1$ts)<= (as.Date(df2[1,1]))),]
#i am writing this in a loop so that it would iterate over every date of df2

df1= data.frame( ts = c('2020-01-15', '2020-01-16' , '2020-01-17'),
              lla=c(12,13,14),
              llb=c(1,2,3),
              llc=c(0.6,1.6,2.6),
              lld=c(10,11,12))

So now we have to get the max of every column which we would achieve with this code
#would return the maximum of every column
apply(ohlc[(as.Date(ohlc$ts)>= (as.Date(cls[1,1])-2)) &
  (as.Date(ohlc$ts)<= (as.Date(cls[1,1]))),],2,max)

But I don't know how to input this data in df2 for matching date i.e "2020-01-17" and so on for other dates of df2

A: Try:
libray(dplyr)
df1 <- df1 %>% mutate(ts=as.Date(ts))
df2 <- df2 %>% mutate(ts=as.Date(ts))

my_function <- function(x,df){
      df %>% filter(ts >= (x$ts-3) &  ts <= x$ts) %>%
            mutate(ts=x$ts) %>%
            summarise(across(.cols = lla:lld, .fns = max)) %>%
            mutate(ts=x$ts)}

lapply(split(df2,df2$ts),my_function,df=df1) %>% do.call(rbind,.)

A: Here is an option with roll after creating a new column 4 days back
library(data.table)
library(lubridate)
# // convert columns to Date class
df1$ts <- as.Date(df1$ts)
df2$ts <- as.Date(df2$ts)
nm1 <- names(df2)[-1]
# // change the type of NA columns from logical to numeric
setDT(df2)[, (nm1) := lapply(.SD, as.numeric), .SDcols = nm1]

# // subtract 4 days from ts to create ts1
setDT(df1)[, ts1 := ts %m-% days(4)]

# do a rolling join while getting the `max` for each column
df2[df1, (nm1) := lapply(mget(paste0("i.", nm1)), max),
           on = .(ts = ts1), roll = -Inf, by = .EACHI]

A: Alternate approach using runner
df1$ts <- as.Date(df1$ts)
df2$ts <- as.Date(df2$ts)

library(runner)
library(dplyr)

df2 %>%
  mutate(across(!ts, ~max_run(x = df1[[cur_column()]],
                              k = 4,
                              idx = df1$ts,
                              at = cur_data()[[1]])))

#>           ts lla llb llc lld
#> 1 2020-01-17  14   3 2.6  12
#> 2 2020-01-24  17   6 5.6  15
#> 3 2020-01-31  20   8 8.6 167

Created on 2021-06-06 by the reprex package (v2.0.0)