text:
Q: Spring Boot and Spring Cloud Security OAUTH 2 SSO Failing with latest releases I am trying to upgrade a sample Spring Boot and Spring Cloud Security with OAuth from Spring Boot 1.4.1 + Brixton.RELEASE to Spring Boot 1.5.3+ Dalston.RELEASE. However, it has been a long hard try without any success.
It seems for some reason the resource server security filter chain is not getting fired. As a result the call to "/me" or "/user" is being handled by default security filter chain. I am thinking if this is a problem with order. But tried to explicitly set the order of the security filter chains as follows

*

*Auth Server 6

*Web Default 5

*Resource server 3 (hard coded ??)

Since the default filter chain is handling the request, it is always going to the login page, which generates HTML and the SSO client (server side thymeleaf web UI) fails.
The source code is below
Authorization server
@SpringBootApplication
public class MyAuthServerApplication {

public static void main(String[] args) {
    SpringApplication.run(MyAuthServerApplication.class, args);
}
}

Then the authorization server configuration
@Configuration
@EnableAuthorizationServer
@Order(6)
public class AuthorizationServerConfigurer extends A
uthorizationServerConfigurerAdapter {

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws
Exception {
    clients.inMemory()
            .withClient("myauthserver")
            .secret("verysecretpassword")
            .redirectUris("http://localhost:8080/")
            .authorizedGrantTypes("authorization_code", "refresh_token")
            .scopes("myscope")
            .autoApprove(true);
}
}

Then the resource server class
@Configuration
@EnableResourceServer
public class ResourceServerConfigurer extends
ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/user")
            .authorizeRequests()
            .anyRequest()
            .authenticated();
}
}

The web MVC configuration
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

 @Override
 public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("login").setViewName("login");
 }
 }

The default spring security configuration
@Configuration
@EnableWebSecurity
@Order(9)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and().csrf()
            .and().formLogin().loginPage("/login");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
    auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
            .and()
                .withUser("admin").password("admin").roles("USER", "ADMIN");
}
}

The resource controller
@RestController
public class ResourceController {

@RequestMapping(value = { "/user" }, produces = "application/json")
public Map<String, Object> user(OAuth2Authentication user) {
    Map<String, Object> userDetails = new HashMap<>();
    userDetails.put("user", user.getUserAuthentication().getPrincipal());
    userDetails.put("authorities",

AuthorityUtils.
 authorityListToSet(user.getUserAuthentication().getAuthorities()));
    return userDetails;
}

}
Finally the configuration - application.yml for the auth server
server:
  port: 9090
  contextPath: /auth

logging:
  level:
      org.springframework: INFO
      org.springframework.security: DEBUG

The login.html Thymeleaf template is not shown here.
OAUTH 2 SSO Client Web App
@SpringBootApplication
public class MyWebsiteApplication {

public static void main(String[] args) {
    SpringApplication.run(MyWebsiteApplication.class, args);
}
}

The web security configuration
@Configuration
@EnableOAuth2Sso
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/").permitAll()   // Allow navigating to index
 page,
            .anyRequest().authenticated();  // but secure all the other URLs
}
}

The web controller
@Controller
public class MyWebsiteController {
/**
 * Default index page to verify that our application works.
 */
@RequestMapping("/")
@ResponseBody
public String helloWorld() {
    return "Hello world!";
}

/**
 * Return a ModelAndView which will cause the
'src/main/resources/templates/time.html' template to be rendered,
 * with the current time.
 */
@RequestMapping("/time")
public ModelAndView time() {
    ModelAndView mav = new ModelAndView("time");
    mav.addObject("currentTime", getCurrentTime());
    return mav;
}

private String getCurrentTime() {
    return LocalTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME);
}
}

The application configuration - application.yml for the client web app
server:
  port: 8080
  contextPath: /

security:
  oauth2:
  client:
    accessTokenUri: http://localhost:9090/auth/oauth/token
    userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
    clientId: myauthserver
    clientSecret: verysecretpassword
  resource:
    userInfoUri: http://localhost:9090/auth/user

The Thymeleaf template for the time.html page is not shown here.
There must be some subtle little configuration thats wrong or some bug I do not know. Any help or ideas highly appreciated.

A: Solution
Guess was right the ordering of the security filter chain got was changed. Here is the link to the
Spring 1.5.x release note
Modified code is here and will upload it to Github later. All changes on the auth server configuration.
The Spring security configuration - remove the @Order annotation.
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and().csrf()
            .and().formLogin().loginPage("/login");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
    auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
            .and()
                .withUser("admin").password("admin").roles("USER", "ADMIN");
}
}

Then change the application.yml as follows
server:
  port: 9090
  contextPath: /auth

logging:
  level:
    org.springframework: INFO
    org.springframework.security: DEBUG

security:
  oauth2:
    resource:
    filter-order : 3

That's it then the time is displayed on the client application /time url after authentication on the auth server.


text:
Q: How can i choose the optimal lag in GARCH-MIDAS? I have to choose individual GARCH-MIDAS models for some variables. But the BIC value continues to decrease as I increase the lag (its even the case for k=70 and more which is unrealistic) so the BIC, only, isn't really helping.
Is there any condition to choose the maximum lag in GARCH MIDAS? (The significance of some parameter for instance.)

A: In my paper Low-frequency Modeling for Capturing Volatility Persistence: A Dynamically Complete Realized EGARCH-MIDAS Model, it was also the case that the log-likelihood was increasing with the allowed number of lags and so will information criteria since the number of parameters are constant.
Our approach was to simply estimate the model for different values of $k$ and stop when the improvement in the log-likelihood was negligible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem using subtable in IEEEtran class I am using the IEEEtran class with the journal option. I would like to insert two tables side by side, each with its respective subcaption. However, when I use the subcaption package I get the following result:

My code is:
\begin{table}[]
\centering
\begin{subtable}[c]{0.25\textwidth}
    \centering
    \begin{tabular}{lll}
     & \textbf{Original} & \textbf{SMOTE-Tomek} \\ \hline
    \textbf{class 0} & 11645 & 10444 \\ \hline
    \textbf{class 1} & 618 & 10305 \\ \hline
    \textbf{class 2} & 618 & 9976 \\ \hline
    \textbf{class 3} & 682 & 11597 \\ \hline
    \textbf{class 4} & 736 & 10190 \\ \hline
    \textbf{class 5} & 829 & 10462 \\ \hline
    \end{tabular}
    \subcaption{Client 1 balance by SMOTE-Tomek}
\end{subtable}%
\begin{subtable}[c]{0.25\textwidth}
    \centering
    \begin{tabular}{lll}
     & \textbf{Original} & \textbf{SMOTE-Tomek} \\ \hline
    \textbf{class 0} & 11645 & 10444 \\ \hline
    \textbf{class 1} & 618 & 10305 \\ \hline
    \textbf{class 2} & 618 & 9976 \\ \hline
    \textbf{class 3} & 682 & 11597 \\ \hline
    \textbf{class 4} & 736 & 10190 \\ \hline
    \textbf{class 5} & 829 & 10462 \\ \hline
    \end{tabular}
    \subcaption{Client 2 balance by SMOTE-Tomek}
\end{subtable}
\caption{principal}

\end{table}

A: It very much looks like the widths of the tabular environments exceed 0.25\textwidth. For starters, I would make the tabular environments less wide by forcing a line break in the SMOTE-Tomek header cells.
I would also try to give the tabular material a more inviting look by using the machinery of the booktabs package -- specifically, the user macros \toprule, \midrule, \bottomrule -- while getting rid of all instances of \hline. Finally, I'd line up the numbers on their (implicit) decimal markers, and I wouldn't use bold-facing in the header cells, as it's simply not needed.

\documentclass[journal]{IEEEtran}
\usepackage{subcaption,lipsum,booktabs}
\usepackage{siunitx} % for 'S' column type
\begin{document}

\begin{table}
\captionsetup[subtable]{justification=centering} % optional
\begin{subtable}{0.45\columnwidth}
    \centering
    \begin{tabular}{@{} l *{2}{S[table-format=5.0,group-four-digits=true]} @{}}
    \toprule
    Class & {Original} & {SMOTE-} \\
    & & {Tomek} \\
    \midrule
    {0} & 11645 & 10444 \\
    {1} &   618 & 10305 \\
    {2} &   618 &  9976 \\ \addlinespace
    {3} &   682 & 11597 \\
    {4} &   736 & 10190 \\
    {5} &   829 & 10462 \\
    \bottomrule
    \end{tabular}
    \caption{Client 1 balance by SMOTE-Tomek}
\end{subtable}%
\hfill
\begin{subtable}{0.45\columnwidth}
    \centering
    \begin{tabular}{@{} l *{2}{S[table-format=5.0,group-four-digits=true]} @{}}
    \toprule
    Class& {Original} & {SMOTE-} \\
    & & {Tomek} \\
    \midrule
    {0} & 11645 & 10444 \\
    {1} &   618 & 10305 \\
    {2} &   618 &  9976 \\ \addlinespace
    {3} &   682 & 11597 \\
    {4} &   736 & 10190 \\
    {5} &   829 & 10462 \\
    \bottomrule
    \end{tabular}
    \caption{Client 2 balance by SMOTE-Tomek}
\end{subtable}
\caption{principal}

\end{table}

\lipsum % filler text
\end{document}

A: Similar as in @Mico answer (+1), but with use of the tabularray and subfloat environment as is defined in the subcaption package (version 3.1) and manually broken text in the column head of the last table column:
\documentclass[journal]{IEEEtran}
\usepackage{subcaption}
\captionsetup[subtable]{justification=centering} % optional

\usepackage{tabularray}
\UseTblrLibrary{booktabs, siunitx, varwidth}

\usepackage{lipsum}  % for dummy text

\begin{document}
    \begin{table}
    \sisetup{table-format=5,
             group-four-digits=true}
    \centering
\subfloat[Client 1 balance by SMOTE-Tomek]%
{
\begin{tblr}{colspec={ c *{2}{Q[c,m, si]} },
             measure=vbox
            }
    \toprule
Class & {{{Original}}} & {{{SMOTE-\\ Tomek}}} \\
    \midrule
0   & 11645 & 10444 \\
1   &   618 & 10305 \\
2   &   618 &  9976 \\ \addlinespace
3   &   682 & 11597 \\
4   &   736 & 10190 \\
5   &   829 & 10462 \\
    \bottomrule
\end{tblr}
}%
\hfil
\subfloat[Client 2 balance by SMOTE-Tomek]%
{
\begin{tblr}{colspec={ c *{2}{Q[c,m, si]} },
             measure=vbox
            }
    \toprule
Class & {{{Original}}} & {{{SMOTE-\\ Tomek}}} \\
    \midrule
0   & 11645 & 10444 \\
1   &   618 & 10305 \\
2   &   618 &  9976 \\ \addlinespace
3   &   682 & 11597 \\
4   &   736 & 10190 \\
5   &   829 & 10462 \\
    \bottomrule
\end{tblr}
}%
\caption{principal}
\label{tab:principal}
    \end{table}

\lipsum
\end{document}


text:
Q: Unable to find method 'org.gradle.api.tasks.compile.CompileOptions I didn't change anything.
Please somebody help me to solve this:

ERROR: Unable to find method 'org.gradle.api.tasks.compile.CompileOptions.setBootClasspath(Ljava/lang/String;)V'.
  Possible causes for this unexpected error include:
  Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
  Re-download dependencies and sync project (requires network)
The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
  Stop Gradle build processes (requires restart)
Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

A: app(build.gradle)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath 'com.google.gms:google-services:3.1.2'
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'

        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url "https://maven.google.com" }
        google()
    }

    // source :
    // https://stackoverflow.com/questions/34828426/disable-javadoc-check-for-bintray-upload
    tasks.withType(Javadoc) {
        options.addStringOption('Xdoclint:none', '-quiet')
        options.addStringOption('encoding', 'UTF-8')
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


text:
Q: Microsoft's MPEG-2 demuxer filter - can I change an elementary stream pin's PID while the graph is running? I'm working with multi-program UDP MPEG-2 TS streams that, -unfortunately- dynamically re-map their elementary stream PIDs at random intervals. The stream is being demuxed using Microsoft's MPEG-2 demultiplexer filter.
I'm using the PSI-Parser filter (an example filter included in the DirectShow base classes) in order to react to the PAT/PMT changes.
The code is properly reacting to the change, yet I am experiencing some odd crashes (heap memory corruption) right after I remap the Demuxer pins to their new ID's. (The re-mapping is performed inside the thread that is processing graph events, while the EC_PROGRAMCHANGED message is being processed).
The crash could be due to faulty code in my part, yet I have not found any reference that tells me if changing the pin PID mapping is safe while the graph is running.
Can anyone provide some info if this is operation is safe, and if it is not, what could I do to minimize capture disruption?

A: I managed to find the source code for a Windows CE version of the demuxer filter. Inspecting it, indeed, it seems that it is safe to remap a pin while the filter is running.
I also managed to find the source of my problems with the PSI-Parser filter.
When a new transport stream is detected, or the PAT version changes, the PAT is flushed, (all programs are removed, the table is re-parsed and repopulated).
There is a subtle bug within the CPATProcessor::flush() method.
//
// flush
//
// flush an array of struct: m_mpeg2_program[];
// and unmap all PMT_PIDs pids, except one: PAT
BOOL CPATProcessor::flush()
{
    BOOL bResult = TRUE;
    bResult = m_pPrograms->free_programs();   // CPrograms::free_programs() call
    if(bResult == FALSE)
        return bResult;
    bResult = UnmapPmtPid();
    return bResult;
}// flush

Here's the CPrograms::free_programs() implementation.
_inline BOOL free_programs()
    {
        for(int i= 0; i<m_ProgramCount; i++){
            if(!HeapFree(GetProcessHeap(), 0, (LPVOID) m_programs[i] ))
                return FALSE;
        }
        return TRUE;
    }

The problem here is that the m_ProgramCount member is never cleared. So, -apart from reporting the wrong number of programs in the table after a flush (since it is updated incrementally for each program found in the table)-, the next time the table is flushed, it will try to release memory that was already released.
Here's my updated version that fixes the heap corruption errors:
_inline BOOL free_programs()
    {
        for(int i= 0; i<m_ProgramCount; i++){
            if(!HeapFree(GetProcessHeap(), 0, (LPVOID) m_programs[i] ))
                return FALSE;
        }
        m_ProgramCount = 0;  // This was missing,  next call will try to free memory twice
        return TRUE;
    }


text:
Q: Ecg signal from ad8232 for Arrhythmia classification project I intend to make a realtime Arrhythmia classification system, I use ad8232 as a device for getting ecg signal. Here is the project I using
https://medium.datadriveninvestor.com/ecg-arrhythmia-classification-using-a-2-d-convolutional-neural-network-33aa586bad67
I use the model he provided, and use his test data(sample.csv), it works properly, but something went wrong when using my own data, but i am not going to ask where I did I went wrong, I would like to know whether my direction is right or wrong.
My question is

*

*Is all leads of ecg can be fed into that model to do prediction?

*He turned ecg signal into 2d image and augmented it, this seems like he is talking about the former step of trainning phase, but does my signal which fed into the model to do prediction will be also transformed in 2d and augmented?

*Does my signal has to be denoised, because he said signal don't have to be denoised if using 2d convolutional model to predict it

*The data generate from ad8232 is from 0 to 1024, but its sample data is from -1 < x < 1, If my data is usually between 300 < x < 700, can I process my data like this (x - 500)/1000, make it between -1 < x < 1. Is my method reasonable?

Please tell me which step of my thinking is wrong thank you!


text:
Q: Defining Tomcat servlet context parameters Scenario:
foo.war file contains a default value of init parameter fooParam=1.
This is defined in foo.war!WEB_INF/web.xml which contains:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <context-param>
      <param-name>fooParam</param-name>
      <param-value>1</param-value>
      <description>
        my parameter "fooParam"
      </description>
    </context-param>

    ...

OK, now I want to be able to override it in a config file in the Tomcat {$CATALINA_HOME}/conf/ directory. Where/how can I do this???

A: According to the documentation of the Context element:

Context Parameters
You can configure named values that
  will be made visible to the web
  application as servlet context
  initialization parameters by nesting
  <Parameter> elements inside this
  element. For example, you can create
  an initialization parameter like this:
<Context ...>
  ...
  <Parameter name="companyName" value="My Company, Incorporated"
         override="false"/>
  ...
</Context>

This is equivalent to the inclusion of
  the following element in the web
  application deployment descriptor
  (/WEB-INF/web.xml):
<context-param>
  <param-name>companyName</param-name>
  <param-value>My Company, Incorporated</param-value>
</context-param>

but does not require modification of
  the deployment descriptor to customize
  this value.
The valid attributes for a
  <Parameter> element are as follows:
...

About the override attribute of a <Parameter>, the documentation says:

Set this to false if you do not want a <context-param> for the same parameter name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.

Setting it to false should do the trick. This was the "how" part.

For the "where" part, read refer to the introduction of The Context Container:

For Tomcat 6, unlike Tomcat 4.x, it is NOT recommended to place <Context> elements directly in the server.xml file. This is because it makes modifing the Context configuration more invasive since the main conf/server.xml file cannot be reloaded without restarting Tomcat.
Context elements may be explicitly defined:

*

*In the $CATALINA_BASE/conf/context.xml file: the Context element information will be loaded by all webapps.

*In the $CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default file: the Context element information will be loaded by all webapps of that host.

*In individual files (with a ".xml" extension) in the $CATALINA_BASE/conf/[enginename]/[hostname]/ directory. The name of the file (less the .xml extension) will be used as the context path. Multi-level context paths may be defined using #, e.g. foo#bar.xml for a context path of /foo/bar. The default web application may be defined by using a file called ROOT.xml.

*Only if a context file does not exist for the application in the $CATALINA_BASE/conf/[enginename]/[hostname]/, in an individual file at /META-INF/context.xml inside the application files. If the web application is packaged as a WAR then /META-INF/context.xml will be copied to $CATALINA_BASE/conf/[enginename]/[hostname]/ and renamed to match the application's context path. Once this file exists, it will not be replaced if a new WAR with a newer /META-INF/context.xml is placed in the host's appBase.

*Inside a Host element in the main conf/server.xml.

  With the exception of server.xml, files that define Context  elements may only define a single Context element.

A: Argh! I thought I had asked this before. It's really hard to search on this website sometimes.
where/how to setup configuration resources for Tomcat .war files


text:
Q: Spin and its connection to magnetic field How the intrinsic spin of an electron results in a magnetic field? How does spin couples to the magnetic field? I mean to ask how does the phenomenon of Spin orbit coupling happens physically? Is the electron really spinning or not?

A: The electron is not spinning. Elementary particles are considered to be point-like particles, meaning that they do not have an internal structure. The spin is, as you say, an intrinsic property of particles. It is a pure quantum mechanical property that particles just have. The spin induces a spin magnetic moment:
$$\vec{\mu_{s}}=g\frac{q}{2m}\vec{S}$$
So if an external magnetic field is applied, it will exert a torque on the particle's magnetic moment depending on its orientation with respect to the field.
$$\vec{\tau}=\vec{\mu}\times\vec{B}$$

A: Just as said in the other quite exhaustive answers, I would remark that the image
is physically meaningless! Electrons and elementary particles don't rotate! They can be thought as very tiny balls and so comes the missleading idealization that they can rotate but actually they can't because they must be thought as point-like particles!
By the way, and that's actually another possible source of confusion, Spin is one of two types of angular momentum in quantum mechanics, the other being orbital angular momentum. The orbital angular momentum operator is the quantum-mechanical counterpart to the classical angular momentum of orbital revolution: it arises when a particle executes a rotating or twisting trajectory (such as when an electron orbits a nucleus).
The existence of spin angular momentum is inferred from experiments, such as the Stern–Gerlach experiment, in which particles are observed to possess angular momentum that cannot be accounted for by orbital angular momentum alone. Remeber that there is not a classical analogue of the spin and it must be considered as an intrinsic quantum property of matter!


text:
Q: ibpy: extract API responses for multiple contracts I am interested in using ibpy with Interactive Brokers API to get real time tick data for a given universe of 100 stocks.  The code below, from examples on the web works for one stock.  Can someone tell me how i can do this for 100 stocks at the same time?
Python script:
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from time import sleep

def my_callback_handler(msg):
    inside_mkt_bid = ''
    inside_mkt_ask = ''

    if msg.field == 1:
        inside_mkt_bid = msg.price
        print 'bid', inside_mkt_bid
    elif msg.field == 2:
        inside_mkt_ask = msg.price
        print 'ask', inside_mkt_ask

tws = ibConnection()
tws.register(my_callback_handler, message.tickSize, message.tickPrice)
tws.connect()

c = Contract()
c.m_symbol = "DATA"
c.m_secType = "STK"
c.m_exchange = "SMART"
c.m_currency = "USD"

tws.reqMktData(1,c,"",False)
sleep(25)

print 'All done'

tws.disconnect()

Command line output:
    Server Version: 76
    TWS Time at connection:20150508 13:42:02 EST
    bid 111.42
    ask 111.5
    bid 111.43
    bid 111.44
    bid 111.42
    bid 111.38
    bid 111.32
    ask 111.44
    All done

A: When you request data, you give a tickerId that identifies which request the response message is for.
I would read a list of securities from a file and put them in a data frame and just use the index as the tickerId.  It will make finding and storing the data that much easier.
Here's how I make the data structure
from __future__ import print_function #I'm using 3.x style print
import pandas as pd

#better to read these from a file
contracts = pd.DataFrame([
        ['IBM','SMART','USD'],
        ['AAPL','SMART','USD'],
        ['GOOG','SMART','USD'],
        ['ES','GLOBEX','USD','201506','50'],
        ['CL','NYMEX','USD','201506','1000']
])

# make decent column names
contracts.columns = ['sym','exch','curr','expiry','mult']

#add these specific column names to match the name returned by TickType.getField()
contracts['bidPrice'] = 0
contracts['askPrice'] = 0
contracts['lastPrice'] = 0

Now to make the requests I just loop through the data frame.  In the callback I use the tickerId to find the row in the data frame.
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from ib.ext.TickType import TickType as tt
from time import sleep

def error_handler(msg):
    print (msg)

def my_callback_handler(msg):
    if msg.field in [tt.BID,tt.ASK,tt.LAST]:
        #now we can just store the response in the data frame
        contracts.loc[msg.tickerId,tt.getField(msg.field)] = msg.price
        if msg.field == tt.LAST:
            print(contracts.loc[msg.tickerId,'sym'],msg.price)

tws = ibConnection(clientId=1)
tws.register(my_callback_handler, message.tickPrice, message.tickSize)
tws.register(error_handler, 'Error')
tws.connect()

for index, row in contracts.iterrows():
    c = Contract()
    c.m_symbol = row['sym']
    c.m_exchange = row['exch']
    c.m_currency = row['curr']
    c.m_secType = 'STK' if row['expiry'] is None else 'FUT'
    c.m_expiry = row['expiry']
    c.m_multiplier = row['mult']
    # the tickerId is just the index in but for some reason it needs str()
    tws.reqMktData(str(index),c,"",False)

Now I have all my current data if I want to use it somehow.  Another option would be some structure to save it and make a graph.


text:
Q: Export to PDF function dont give option to Save Or Open on Browser public string ExportToPDF_ManageDefects(bool isEmailPDF, DataTable dt, string headerText)
    {

        string timeStamp = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
        string pdfName = string.Empty;
        //string headerText = string.Empty;
        //Create document
        Document document = new Document(PageSize.A4, 10, 10, 10, 10);
        PdfWriter writer = null;
        FileStream fs =null;
        try
        {
            if (!isEmailPDF)
            {
                pdfName = headerText+"_" + timeStamp + ".pdf";
                fs = new FileStream(HttpContext.Current.Server.MapPath("~/PDFReport/"+pdfName), FileMode.Create, FileAccess.Write, FileShare.None);
                writer = PdfWriter.GetInstance(document, fs);
            }
            else
            {
                writer = PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
            }

            DataTable filteredData = dt;// (DataTable)HttpContext.Current.Session["filteredData"];
            document.Open();
            document.Add(CreatePDFTable_HeaderImage());
            document.Add(CreatePDFTable_HeaderText(headerText));
            document.Add(CreatePDFTable_SearchText(headerText));
            document.Add(CreatePDFTable_BodyDataTable(filteredData));
            document.Add(CreatePDFTable_Footer());
            document.Close();

            if (isEmailPDF)
            {
                HttpContext.Current.Response.ContentType = "application/PDF";
                HttpContext.Current.Response.AddHeader("Content-Disposition:", "attachment; filename='"+headerText+"'" + timeStamp + ".pdf");
                HttpContext.Current.Response.Write("<script>window.open('"+headerText+"_" + timeStamp + ".pdf',target='new');</script>");
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.End();
            }
        }
        catch (Exception ex)
        {

        }
        return pdfName;

In my case i am trying to popup Save or Open window on browser, Where as the physical file is saved in above said path.
The requirement is to open in new tab or else at least it should ask for Save or Open
Also i have used
response.End(); // -- Have tried to changing this line to -->
HttpContext.Current.ApplicationInstance.CompleteRequest(); // -- This does not throw the exception but don't work for me.
The parameters are as follows : IsEmail = False, headerText = GroupDetails_201666185411, dt = Set of DataTable.

A: In my html page a just added this code and my work was done.
<Triggers>
            <asp:PostBackTrigger ControlID="btnPDF" />
            <asp:PostBackTrigger ControlID="btnCSV" />
        </Triggers>

After that i have written the JavaScript code to open my PDF file in new tab.
function NewWindow() {
        document.forms[0].target = "_blank";
    }

And called the same function on my button event.
<asp:Button ID="btnPDF" runat="server" CssClass="BigBtn" OnClientClick="NewWindow();"></asp:Button>

Thanks all =)


text:
Q: Can I call a method on other objects created by the same constructor in javascript? Lets say I have an object constructor that a third-party page developer can insert in their page, called "Widget".  It could be something like a tooltip, for example.
var Widget = function(settings, callbacks) {
    this.hide = function() {
        //some code...
    };

    this.show = function() {
        this.isShowing = true;

        //more code...
    }
}

When this Widget is shown, I want to hide any other shown Widget.  Is there a way the "show" method can call the "hide" method on the other instance(s) of Widget whose "this.isShowing" is true, or on all instances of Widget?

A: You can, but you need to maintain references to those instances. You could maintain them on a property of the function itself:
var Widget = function(settings, callbacks) {
  Widget.instances.push(this);
  // More code
};
Widget.instances = [];

And then, just access Widget.instances to get the all the widgets created.
You may want to create some kind of destructor to remove a widget from the list though (myWidget.destroy() or something), because this might generate a memory leak if you instantiate too many of them.


text:
Q: modf does not work properly This code should display if first 3 digits of fractional part contains "9", but does not work. "mod" variable, surprisingly, is 0 for any number.
int main( void )
{
    float number, dmod;
    int mod;
    double digit_1, digit_2, digit_3;
    double search=9;

    cout<<"Enter the number:";
    cin>>number;

    mod = modf(number, &dmod);
    digit_1 = mod /100 % 10;
    digit_2 = mod /10  % 10;
    digit_3 = mod /1   % 10;

    if( (digit_1 == search) || (digit_2 == search) || (digit_3 ==search) )
    {
        cout<<"mod contains 9"<<endl;
    }
    else
    {
        cout<<"mod does not contains 9"<<endl;
    }
 }

A: Your problem is that modf returns the fractional part, not an integer representing the fractional part. The value returned is always less than one and then when assigned to an int it gets truncated down to 0.
Maybe you wanted to multiply the return by 1000: mod = modf(number, &dmod) * 1000.0;


text:
Q: powerhouse of ideas
Powerhouse: chiefly US : someone or something that is full of a
  particular thing
http://www.learnersdictionary.com/definition/powerhouse
(Merriam Webster Learner's Dictionary)

According to this thread growth-powerhouse -- meaning?

As Adam has indicated in his comment, powerhouse is often used
  metaphorically to indicate something which is known to be strong or
  powerful in some respect.

Take this example from Merriam Webster Learner's Dictionary

He is a powerhouse of ideas.

I find this sentence still hard to understand.  Does it mean he can produce a lot of ideas (a source of ideas)? Or does it mean he is a source of inspiration (he inspires others to have ideas)?

A: A power-house originally meant a building containg a steam-engine (or possibly a water-wheel) i.e. a building that 'is a source of power', so it is most likely that the author means that the person 'is a source of' ideas rather than a source of inspiration, but there is not that much difference in the two meanings, and either is plausible.

A: "Powerhouse", like any other metaphor, has a figurative meaning implied by the literal meaning; however, in the case where there are several possible meanings you have to look at how it's most commonly used.  Some examples pulled from the internet:

*

*Damon had appeared in eleven other films before winning his first Oscar, but it was his role as a heroin addict veteran in 1996's Courage Under Fire that won him the respect and admiration of many powerhouse actors.

*Each process does leech some nutrients, but the beet is a veritable nutritional powerhouse to begin with, so a certain degree of deterioration doesn't negate the vegetable's positive properties.

*From his haunting acoustic material as heard on the albums Harvest and Harvest Moon to his garage rock powerhouse band Crazy Horse, Neil Young has been following his own inspired musical compass for the better part of four decades.

From these (and many others) we should assume that "powerhouse" refers to something "full of power", or, depending on the context, significance, usefulness, influence, and other applications of power.
It does not seem to be used to mean something that "produces power", as in a "power plant", so it's unlikely your sentence implies he is a "source of ideas" as in someone who inspires ideas in other people.

A: Literally, powerhouse is an electrical generating station or plant.
The word is also used figuratively in some senses. Here in the sentence presented, it means a lot of/full of.  If someone is a powerhouse of ideas, it means they have a lot of/are full of ideas.


text:
Q: How do I force Chrome to load a fresh copy of a page? I am developing a new website, and I originally had a Url redirect on the domain that took users to an existing site in order to avoid a parked domain notice showing up.  When it came to put the first version of the site up on the web, I removed the redirect and waited a good 48 hours (for the DNS to catch up with the change).  But even after this wait, every time I tried navigating to the domain, it redirected anyway.  I became suspicious that it might not be because the domain was redirecting, but because Chrome (my browser of choice) had the old routing cached.  I confirmed this was the case by running Edge on the domain -- it took me right to the new website.
It appears that I need to instruct Chrome to stop caching pages, and always check for a new version of the website.  The must be a way to do this.  Someone please tell me.  I am a fairly new Chrome user and don't know much about setting options in it.
I have looked in Options, but no setting there seems to be the equivalent of Internet Explorer's "get new copy of each page".  In fact, Edge doesn't seem to have it, either!!

A: There was a similar question posted here:
https://productforums.google.com/forum/#!topic/chrome/xR-6YAkcASQ
The answers are quite old so I don't know if it's been updated but back then it didn't look like chrome had an automated process (it probably still doesn't).
From the source above, two manual solutions are:

*

*Press CTRL+SHIFT+DELETE and manually clear the cache each time; or

*You will need to add a '?random.number' or "?date.code" to every link each time a URL is pressed on your website.
For example, if  'myhomepage.html?272772' is stored in the cache, then by generating a new random number eg. 'myhomepage.html?2474789', Google Chrome will be forced to look for a new copy.
Sorry if this is no help!
Edit: A potentially even better solution if you are developing using the Chrome Development Tools is found at this source:
https://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development
With a screenshot of the upvoted solution:

Hopefully this is an appropriate way to answer using another source.

A: The other answer might be good for you own Chrome instance, but every other user will have the same problem.  The problem is that Chrome needs to have must-revalidate in the Cache-Control` header in order to re-check files to see if they need to be re-fetched.
To fix this once and for all for all users, include the following response header:
Cache-Control: must-validate

This tells Chrome to check with the server, and see if there is a newer file.  If there is a newer file, it will receive it in the response.  If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.
If you do NOT set this header, then in the absence of any other settings that invalidate the file, Chrome will never check with the server to see if there is a newer version.
Here is a blog post that discusses the issue further.

A: Press Ctrl + F5 or Shift + F5 to load a fresh copy of the website.
Otherwise, you can switch off the caching feature from the developers tool. To do so:

*

*Visit the website and press F12.

*Go to networks tab and check the box "Disable cache".

This way you can always force the website to load fresh content and not cached files.

A: I tried EVERYTHING. This is what finally worked:
Command prompt:
ipconfig /flushdns

THIS finally worked.

A: On desktop, you can delete the cache for that website only via this
chrome://settings/siteData?searchSubpage=example.com

Replace example.com with your domain

Then you can either go to each relevant entry and hit the garbage icon, or just click "Remove All Shown" to get rid of everything matching the query


text:
Q: MySQL Inner Join too slow My machine disk is SSD and memory is 32GB.
My executed SQL:
SELECT `country_detail`.`country_name` AS `country_name`
FROM `statistic_detail`
  INNER JOIN `country_detail` ON (`statistic_detail`.`country` = `country_detail`.`country_code`)
GROUP BY 1;

The SQL need cost 30 second. So slowly! My explain is:

I don't understand why it need so much time?
I know how optimize it, I want to know why it is so slow.
My table information is:
CREATE TABLE `statistic_detail` (
  `date` varchar(10) NOT NULL,
  `os` varchar(10) NOT NULL,
  `ver` varchar(16) NOT NULL,
  `country` varchar(16) NOT NULL,
  `utype` varchar(8) NOT NULL,
  `stype` varchar(32) NOT NULL,
  `language` varchar(16) NOT NULL,
  `num0` bigint DEFAULT NULL,
  `num1` double DEFAULT NULL,
  `num2` double DEFAULT NULL,
  `num3` double DEFAULT NULL,
  `num4` double DEFAULT NULL,
  `num5` double DEFAULT NULL,
  `num6` double DEFAULT NULL,
  `num7` double DEFAULT NULL,
  `num8` double DEFAULT NULL,
  `num9` double DEFAULT NULL,
  `num10` double DEFAULT NULL,
  `num11` double DEFAULT NULL,
  `num12` double DEFAULT NULL,
  `num13` double NOT NULL,
  PRIMARY KEY (`country`, `ver`, `language`, `utype`, `stype`, `os`, `date`),
  KEY `ver_idx` (`ver`),
  KEY `language_idx` (`language`),
  KEY `utype_idx` (`utype`),
  KEY `stype_idx` (`stype`),
  KEY `os_idx` (`os`),
  KEY `date_idx` (`date`),
  KEY `country_idx` (`country`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

13731253 rows.
CREATE TABLE `country_detail` (
  `country_code` varchar(20) NOT NULL,
  `country_name` varchar(16),
  `region_code` varchar(16),
  `region_name` varchar(16),
  PRIMARY KEY (`country_code`),
  KEY `region_code_idx` (`region_code`),
  KEY `region_name_idx` (`region_name`),
  KEY `country_name_idx` (`country_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

334 rows.

A: To understand the reason behind slowness of your current query, you need to understand the Nested Loop Join algorithm used by MySQL. Basically, for every country_code value in the country table, it is looking for all the matching rows in the statistic table. So if you look at your explain, it is roughly accessing 334*306 rows (a large number). Unfortunately, in this case, MySQL optimizer is not smart enough to stop searching for the row as soon as a match is found (because you are using Group By, and no aggregation function is being used).
Now, JOIN is unnecessary here, as it seems that you are just looking to check that the "country" has atleast one corresponding row in the statistic_detail table. This query can be written in a more performant way using EXISTS() on a Correlated Subquery. Exists() stops as soon as a matching row is found in the statistic table.
Try the following query:
SELECT cd.country_name
FROM country_detail AS cd
WHERE EXISTS (SELECT 1 FROM statistic_detail AS sd
              WHERE sd.country = cd.country_code)

If country_name values are not UNIQUE in the country_detail table, you can additionally utilize DISTINCT clause to get rid of duplicates:
SELECT DISTINCT cd.country_name
FROM country_detail AS cd
WHERE EXISTS (SELECT 1 FROM statistic_detail AS sd
              WHERE sd.country = cd.country_code)


text:
Q: Real size of iOS 9? I want to clear some things. I have an iphone 6s (16 GB). In the Storage section I have used: 5 GB and Available: 6.6 GB.
The difference from 11.6 GB to 16GB I asume it's the OS space.
Why if I add the size of the storage apps from doesn't add up to 5 GB ?

A: You have to take into account all other files which get cached in apps, I was trying to work out why I had near to no storage left on my iPhone 6. I noticed that Spotify was taking up a lot of my space as I saved a large playlist offline, I deleted the App and it was still taking up the space. The storage on the device can be taken up my media in iMessage and other social apps such as Messenger & WhatsApp.
I go through and just delete a lot of old photos and videos (seems to be where most of my storage gets taken up) but I regret getting the 16GB model ;-;
Hope this was of some help to you!


text:
Q: has_many associations So, my question is: how to make possible that calls:
Clan.win #to get all won rounds
Clan.blue #to get all rounds when clan was in blue team

or even this:
Clan.matches_win #need to calculate which team won match by counting rounds
Clan.matches_lost

Round model:
class Round < ActiveRecord::Base
  belongs_to :match
  has_and_belongs_to_many :banned_champions, :class_name => "Champion", :join_table => "banned_champions_rounds"
  belongs_to :clan_blue, :class_name => "Clan", :foreign_key => "clan_blue_id"
  belongs_to :clan_purple, :class_name => "Clan", :foreign_key => "clan_purple_id"
  belongs_to :winner, :class_name => "Clan", :foreign_key => "winner_id"
end

Clan model:
class Clan < ActiveRecord::Base
  has_many :players
  has_many :rounds
end

Match model:
class Match < ActiveRecord::Base
  has_many :rounds
end

A: In your Clan class:
def win
  rounds.where("winner_id = ?", self.id)
end

The others are more or less the same.


text:
Q: FreeRTOS+STM32F4+CPP stuck when call the vTaskDelay I'm using STM32F405RGT + HAL driver + FreeRTOSv9. And the code is C++. First of all, when I wrote the code of C, there is no problem. But C++, something wrong.
entry point in main.cc
extern "C" int main(void) {

  HAL_Init();
  SystemClock_Config();

  xTaskCreate(startup, "startup", STARTUP_TASK_STACK, NULL, STARTUP_TASK_PRIO, NULL);
  vTaskStartScheduler();

  return 0;
}

And "startup" task is
static void startup(void *param) {

  Config::GetInstance().Init();
  Command::GetInstance().Init();

  while (1) {

    trace("startup\r\n");
    vTaskDelay(M2T(1000));
  }

  vTaskDelete(nullptr);
}

In "Command::GetInstance().Init()", create another task and in that task, just vTaskDelay(_500ms) and printf("something\r\n"). That's all.
If I use "HAL_Delay()" in the "startup" task, everything is OK. In the console, I can see two strings - "startup" and "something". But when I use the "vTaskDelay()" in the "startup" task, it should stuck in the "vTaskDelay()" and system calls "HardFault_Handler()".
I really don't know why.

A: Probably you should not increment the Systick correctly in the interrupt handler. You should check your interrupt tick or check a special define in the file freertos_config.h at the end of file to be compatible freertos with the hal_delay.


text:
Q: opencv : set model position using rotation and translation vector I have a 3D model in unity. I calculate rotation and translation vector using opencv solvePnP vector.
Now, I try to set model position with these values. My C# code is below :
Vector3 objPosition;
objPosition.x = gameObject.transform.position.x + tvec.x;
objPosition.y = gameObject.transform.position.y + tvec.y;
objPosition.z = gameObject.transform.position.z + tvec.z;
gameObject.transform.position = objPosition;

Quaternion quat = new Quaternion(rvec.x, rvec.y, rvec.z, 1.0f);
gameObject.transform.rotation = quat;

But the result is not true for me. How can I use opencv rotation and translation vector in unity?
EDIT
I have a 3d model. I determine correspondencs point on object and model manually.I want to put on 2d image that contains a known object. I get camera and object relation using solvePnp.
I use, to show 3d model on unity scene, opencv rotation and translation vector. Maybe I should change my question.
How can I detect object position and orientation using 3d-2d point correspondences?

A: Take a look at the  Unity documentation for Euler to Quaternion calculations
Quaternion quat = Quaternion.Euler(new Vector3(rvec.x, rvec.y, rvec.z))


text:
Q: C/C++ conditional macros combining Can I combine macros while writing code for C or C++? If not, why? If yes, how?
I'm interested on how to solve the following (not correct and NOT compiling!!!) idea:
#define FREE(x) if((x)) {                                         \
#ifdef MEM_DEBUG_                                                 \
    fprintf(stderr, "free:%p (%s:%d)\n", (x), __FILE__, __LINE__); \
#endif                                                             \
    free((x)); }

So, what I want to achieve is this:
I want to define the macro FREE in way that it will include an extra line if I have the MEM_DEBUG defined.
I know, that for solving this I can have two defines for the FREE based on MEM_DEBUG, like:
#ifdef MEM_DEBUG
  #define FREE() something
#else
  #define FREE() something else
#endif

but I'm just curios if there is another way!

A: Yes, you can define macros to encapsulate the idea of doing something when the flag is set.
#ifdef MEM_DEBUG
#   define IF_MEM_DEBUG( ... ) __VA_ARGS__
#   define IF_MEM_NDEBUG( ... )
#else
#   define IF_MEM_DEBUG( ... )
#   define IF_MEM_NDEBUG( ... ) __VA_ARGS__
#endif

#define FREE(x) \
if((x)) { \
    IF_MEM_DEBUG( \
        fprintf(stderr, "free:%p (%s:%d)\n", (x), __FILE__, __LINE__); \
    ) \
    free((x)); \
}

A: No, it's not possible to put preprocessing directives (lines starting with #) inside a macro definition. So the only thing you can do is the second method you mention - put the definitions inside the conditionals.
Of course, if you're working on a bigger macro and only a part of it is #if-dependent, you can isolate the dependent part into a separate macro and use this in the bigger one, to keep the divergent definitions as small as possible.


text:
Q: How can I transfer mathematical expressions between Mathematica and Maple? Is there a simple way to copy mathematical expressions between Mathematica and Maple (or at least in one direction)? I mean only expressions built from numbers and predefined mathematical functions, whithout any patterns or programmatical constructs like Function, Map or Nest.
Ideally, I want functions with different definitions to be automatically adjusted, for example the Mathematica expression EllipticF[Pi/6, 1/4] should be converted to the Maple expression EllipticF(1/2, 1/2).

A: I assume you have Maple to use. If so, Simply open Maple and type the Mathematica command itself directly into Maple using the FromMma package built-into Maple, like this:
restart;
with(MmaTranslator); #load the package
(*[FromMma, FromMmaNotebook, Mma, MmaToMaple]*)

and now can use it
FromMma(`Integrate[Cos[x],x]`);

One can also use Maple convert command with the FromMma option, like this:
convert(`Integrate[Cos[x],x]`, FromMma);

For your example:
FromMma(`EllipticF[Pi/6, 1/4]`);

You can also use a Mathematica computational expression, not just single commands, like this, and then use the resulting Maple command inside Maple:
r:=convert(`Table[i,{i,10}];`, FromMma);
(* r := [seq(i, i = 1 .. 10)] *)

Now run the result in Maple:
r;
(*[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]*)

see http://www.maplesoft.com/support/help/Maple/view.aspx?path=MmaTranslator for information on the MmaTranslator package.
For translating Maple back to Mathematica: The only program I know about that converts Maple to Mathematica is http://library.wolfram.com/infocenter/Conferences/5397

From Maple 9 Worksheets to Mathematica Notebooks

by Yves Papegay. However, I can't find the actual program or the software. You can try to contact the author on this. This was from The 2004 Wolfram Technology Conference.

A: There is actually a dedicated (yet outdated) package for converting Maple code to Mathematica:
MapleConverter by L. Hohmuth
https://library.wolfram.com/infocenter/Demos/188
Recently I got in touch with Mr. Hohmuth and WRI and after some friendly e-mail exchange they kindly agreed to relicense the code under the MIT license
https://library.wolfram.com/infocenter/Demos/188/Readme.txt

Licensing
Copyright 2020 Wolfram Research, Inc
Permission is hereby granted, free of charge, to any person obtaining
  a  copy of this software and associated documentation files (the
  "Software"),  to deal in the Software without restriction, including
  without limitation  the rights to use, copy, modify, merge, publish,
  distribute, sublicense,  and/or sell copies of the Software, and to
  permit persons to whom the  Software is furnished to do so, subject to
  the following conditions:
The above copyright notice and this permission notice shall be
  included in  all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE  AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN  THE
  SOFTWARE.

Notice that the code is very much outdated and doesn't enjoy any support from the WRI side, but since it is open source now, nothing prevents us from forking it and adding various improvements. At least this is something I'm planning to do. However, I'm more interested in parsing single expressions and not whole worksheets.

A: You can open a whole Mathematica notebook in Maple using its Open... menu, and all expressions in the notebook will be converted to Maple representation:

A: Convert Maple expressions to Mathematica:
Through latex:

Through free form input:


text:
Q: Mediastore.Audio.Media.DATA return nothing I tried to list all audio file with a Cursor and Content resolver, I get song title, artist of songs and Id but the problem is that I can't get the path it return nothing when I try to display it in Toast.
Thanks for your help.
Here is the code and how I get songs:
ContentResolver musicResolver = this.getContentResolver();
    Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri,
            null,
            null,
            null,
            MediaStore.Audio.Media.TITLE + " ASC");

    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns
        int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media._ID);
        int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        int pathColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA);

        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            String thisPath = musicCursor.getString(pathColumn);
            arrayChansons.add(new Chanson(thisId, thisTitle, thisArtist, thisPath));
        }
        while (musicCursor.moveToNext());
        musicCursor.close();


text:
Q: Transform the xml using I have an xml like below:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="user">1234</entry>
<entry key="name">sam</entry>
</properties>

I want to transform the key value(key="user" to key="cm:user") into a new xml file using xslt, the output xml should be like this
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="cm:user">1234</entry>
<entry key="name">sam</entry>
</properties>

I am using the below xslt and saxon jar:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="http://schema.infor.com/InforOAGIS/2">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:template match="@*|node()">
<xsl:result-document href="foo.xml" method="xml">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:result-document>
</xsl:template>

<xsl:template match="@key[.='user']">
<xsl:attribute name="key">
        <xsl:value-of select="'cm:user'"/>
    </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

When I run it I am getting the below error:

XTDE1490: Cannot write more than one result document to the same URI:

Could someone please help me with this..

A: You simply need
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

<xsl:template match="@key[.='user']">
<xsl:attribute name="key">
        <xsl:value-of select="'cm:user'"/>
    </xsl:attribute>
 </xsl:template>

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

If you want to define the result file name using xsl:result-document then add a template
<xsl:template match="/">
  <xsl:result-document href="foo.xml">
    <xsl:apply-templates/>
  </xsl:result-document>
</xsl:template>


text:
Q: JSON messes up my diacritics I'm sending a string using jQuery AJAX POST and JSON:
$.ajax({
    type: "POST",
    dataType: "JSON",
    url: "someUrl.asp?param1=someParam1",
    contentType: "charset=utf-8",
    data: JSON.stringify({
        some_code: $( "#some_code" ).length > 0 ? $("#some_code").val() : ''
        })
    })

Serverside is VBScript/ASP.
some_code is a textbox with following text: someValue čšžćđ that needs to be saved just like that.
When scanning network traffic (IE9) I see this:
some_code=someValue Äšžćđ
When looking in the database (Oracle 12c) I see this:
someValue ?????
Html page encoding is Windows-1250.
NLS_LANG and NLS_CHARACTERSET are Slovenian.
I've tried out advice from at least a dozen different links, but to no avail, so I'm turning to you guys and girls. Thank you!

A: Right from the comments think I understand the issue;
The JSON has to be sent as contentType: "charset=utf-8" so the page someUrl.asp will also need to process in UTF-8 to do this follow the below steps.

Based on your comment have made some changes to the below code.

*

*First re-save the someUrl.asp file using UTF-8 encoding not ASCII.

*Set the first line in someUrl.asp to;
<%@Language="VBScript" CodePage = 65001 %>

*Then add the following lines;
<%
Response.Charset = "Windows-1250"
Response.CodePage = 1250
%>

Note: When making changes always remember to save the file with UTF-8 encoding.


text:
Q: How to get average based on list of Ids in entity framework I have a table let says Products which contains two column(ProductId, Price). I am getting list of product Ids from client(IOS, Android). Instead of iterating over the list and getting the price one by one and then calculate average, Is there any better way to do so?

A: If I understand correctly, you have a list with product Ids and want to get the average price for the selected products. You can use a combination of Contains and Average like this:
List<int> productIds = ...;
var averagePrice = db.Products
    .Where(p => productIds.Contains(p.ProductId))
    .Select(p => p.Price)
    .DefaultIfEmpty()
    .Average();

The Select followed by DefaultIfEmpty is needed to avoid exception when the filtered set contains no records.
Update: As per comment, getting several aggregates with a single query is also possible by using group by constant construct:
var info = (from p in db.Products
            where productIds.Contains(p.ProductId)
            group p by 0 into g // any constant would work
            select new
            {
               MinPrice = g.Min(p => p.Price),
               MaxPrice = g.Max(p => p.Price),
               AveragePrice = g.Average(p => p.Price),
            }).FirstOrDefault();
var minPrice = info != null ? info.MinPrice : 0;
var maxPrice = info != null ? info.MaxPrice : 0;
var averagePrice = info != null ? info.AveragePrice : 0;

A: var average = ProductList.Select(p => p.Price).Average();


text:
Q: If $p(x)=ax^3 -2x^2 +bx+c$, find $a, b$ and $c$ if $p(0)=12$, $p(-1)=3$ and $p(2)=36$ If $p(x)=ax^3 -2x^2 +bx+c$, find $a, b$ and $c$ if $p(0)=12$,  $p(-1)=3$ and $p(2)=36$
Can someone please teach me how to do this question thanks!

A: Use $p(2)=36$ , you'll have
$8a - 8 + 2b + 12 = 36$.
Simplify it, you'll get $4a+b=16$.
Together with the equation you've written down,
$a=3$,$b=4$

A: This is really a problem in basic linear algebra.  If we simply plug in the three given values of the independent variable $x$, we obtain the three equations for $a$, $b$, $c$:
$p(0) = 12$ becomes
$c = 12$;
$p(-1) = 3$ becomes
$-a -b +c = 5$;
$p(2) = 36$ becomes
$8a + 2b + c = 44$;
looks like we get $c$ for free!  Plugging $c= 12$ into the second and third equations yields
$-a -b = -7$;
$8a + 2b = 32$;
looks like we get
$6a = 18$,
$a = 3$;
and finally,
$b= 4$.
This method actually generalizes to arbitrary polynomials; the powers of the different values of $x$ form a matrix and the coefficients form a vector; the rest is clearly linear algabra.  Glad to be of assistance in this matter.  Cheers.

A: So, you already found out that $c=12$. You also showed that $-a-b+10=3$, which we can simplify to $-a-b=-7$.
Doing a similar substitution,
$$a(2)^3-2(2)^2+b(2)+c=36.$$
The arithmetic is not too difficult:
$$8a-8+2b+c=36.$$
We can definitely move that $-8$ over, and remember how we already found out that $c=12$? Let's substitute that too:
$$8a+2b+12=44.$$
Now for the 12:
$$\color{blue}{8a+2b}=\color{blue}{32}.$$
This is good. Remember how we said that $-a-b=-7$? Let's just multiply that by $2$:
$$\color{red}{-2a-2b}=\color{red}{-14}.$$
Now check this out: if we add these two previous equations together, the $b$-terms will cancel (i.e., $2b-2b=0$):
$$\color{blue}{8a+2b}\color{red}{-2a-2b}=\color{blue}{32}\color{red}{-14}$$
or
$$6a=18.$$
From here, it is very easy to find $a$, and now that you have two of the three variables, finding $b$ should be very easy after a bit of substitution. I hope this helps.


text:
Q: Dropping Placemark on current location and separate location mkmapview I'm having a few issues with MKMapView! I'm new to the mapping!
What i'm trying to do:
Mapview loads up and drops a placemarker on user's current location, and on the address of the selected customer.
This code drops a placemarker on the address of the selected customer fine, but i can't seem to get it to drop one on the user's current location!
Any ideas why?
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:postcodeForMap
             completionHandler:^(NSArray* placemarks, NSError* error){
                     NSLog(@"Co-ordinate geocode is %@", [placemarks objectAtIndex:0]);
                 for (CLPlacemark* aPlacemark in placemarks)

                 {
                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
                     MKPlacemark *mPlacemark = [[MKPlacemark alloc] initWithCoordinate:mapView.userLocation.location.coordinate addressDictionary:nil];

                     MKCoordinateRegion region = mapView.region;
                     region.center = placemark.region.center;
                     region.span.longitudeDelta /= 8.0;
                     region.span.latitudeDelta /= 8.0;

                     [mapView setRegion:region animated:YES];
                     [mapView addAnnotation:placemark];
                     [mapView addAnnotation:mPlacemark];

                 }
             }
 ];

A: You can get user location using the following code
-(void)viewDidLoad{
    CLLocationManager *locationManager=[[CLLocationManager alloc] init];
    locationManager.delegate=self;//THIS IS IMPORTANT
    [locationManager startUpdatingLocation];
}

When you tell the location manager to get the locations if Allowed the locationmanager calls its delegate method see below
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
          //newLocation is your current Location

   self.userLocation=newLocation;//Once you got the location generate the places..
   [self generatePlaces];
   [manager stopUpdatingLocation];

}

-(void)generatePlaces{
  CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:postcodeForMap
             completionHandler:^(NSArray* placemarks, NSError* error){
                     NSLog(@"Co-ordinate geocode is %@", [placemarks objectAtIndex:0]);
                 for (CLPlacemark* aPlacemark in placemarks)

                 {
                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
                     //EDITED
                     MKPlacemark *mPlacemark = [[MKPlacemark alloc] initWithCoordinate:self.userLocation.coordinate addressDictionary:nil];

                     MKCoordinateRegion region = mapView.region;
                     region.center = placemark.region.center;
                     region.span.longitudeDelta /= 8.0;
                     region.span.latitudeDelta /= 8.0;

                     [mapView setRegion:region animated:YES];
                     [mapView addAnnotation:placemark];
                     [mapView addAnnotation:mPlacemark];

                 }
             }
 ];
}

A: For Your consideration. It is easy to drop any image or url or pin to user current location.
For that you have to implement.
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

if (annotation == mapView.userLocation)
{

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;

    return annView;

}
}


text:
Q: Geddy - create new item I am an absolute beginner in node.js and geddy. I've followed a few tutorials and now I try to write something similar for my purposes.
When I try to create a new item, though, I get the following message:
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D not found.

I have no idea where this could come from. I've looked through the code and found nothing.
Controller:
var ArithmeticProblemTypes = function () {
  this.respondsWith =[ 'html', 'json', 'xml', 'js', 'txt'];

  this.index = function (req, resp, params) {
    var self = this;

    geddy.model.ArithmeticProblemType.all(function (err, arithmetic_problem_types) {
        self.respond({
            params: params, arithmetic_problem_types: arithmetic_problem_types
        });
    });
  };

  this.add = function (req, resp, params) {
    this.respond({
        params: params
    });
  };

  this.create = function (req, resp, params) {
    var self = this, arithmetic_problem_type = geddy.model.ArithmeticProblemType.create({
        name: '1', title: 'open', numberType: '1', numberRanges: '1', operators: '1', askedFor: '1', specialProblemCategory: '1', askedForNumDenomOrBoth: '1',
            reducedFractions:'1', mixedFractions: '1'
    });

    arithmetic_problem_type.save(function (err, data) {
        if (err) {
            params.errors = err;
            self.transfer('add');
        } else {
            self.redirect({
                controller: self.name
            });
        }
    });
  };
....................................................................
};

exports.ArithmeticProblemTypes = ArithmeticProblemTypes;

add.html.ejs

  <%= partial('_form', {params: params}); %>

index.html.ejs

Arithmetic Problem Types List

  <%- linkTo('Create a new Aritmetic Problem Type', addArithmeticProblemTypePath, {class: 'btn pull-right'}) %>

<% if (arithmetic_problem_types && arithmetic_problem_types.length) { %>
  <% for (var i in arithmetic_problem_types) { %>

<%- linkTo(arithmetic_problem_types[i].title, arithmeticProblemTypePath(arithmetic_problem_types[i].id)) %>

<%= arithmetic_problem_types[i].status; %>

 <% } %>
<% } %>

How can I get rid of that message and make it work?
EDIT:
This is the beginning of the _form.html.ejs file:
<%
  var isUpdate = params.action == 'edit'
, formTitle = isUpdate ? 'Update this Arithmetic Problem Type' : 'Create a new Arithmetic Problem Type'
, action = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=PUT' : arithmeticProblemTypePath
, deleteAction = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=DELETE' : ''
, btnText = isUpdate ? 'Update' : 'Add'
, nameValue = isUpdate ? arithmeticProblemTypePath.name : ''
, errors = params.errors;
%>
<form id="arithmetic-problem-type-form" class="form-horizontal" action="<%= action %>" method="POST">
     ....
</form>

EDIT2:
Inspecting the page where I should write the name of the item and click the add button, I've found this

  <form id="arithmetic-problem-type-form" class="form-horizontal" action="function (id) {
      options.id = id;
      return helpersBase.urlFor.action(options);
    }" method="POST">
  <fieldset>
    <legend>Create a new Arithmetic Problem Type</legend>

      Title

        <input class="span6" name="name" placeholder="enter name" type="text">

      <input class="btn btn-primary" type="submit" value="Add">

  </fieldset>
</form>

Indeed the message comes from the action attribute of the form element, but how can I solve it?

A: The message is telling you that the requested URL could not be found. AKA 404
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D
is definitely not a nice looking url. So i'm assuming there's something wrong with your form's action attribute. If that's what happened when you validate the form.
If that's what happened when you click the link to "Create a new arithmetic problem type" then you should probably put parenthesis after addArithmeticProblemTypePath


text:
Q: Google - Project Tango - Point Cloud Extraction - Skeletal Tracking Has anyone had any luck extracting point cloud data into the Tango File system? Also looking for anyone who's had luck with skeletal tracking via point cloud data.
Any tips or suggestions are welcomed!

A: Regarding extracting the point cloud data to the file system, please take a look of this post: How do I export Point Cloud Data (Project Tango)?

A: Thanks Jason. Point Cloud extraction was a bit more tricky on the Java side of things, but it's working!
We're noticing some pretty slow performance when exporting the point cloud data in real time. Would love to hear tips on improving the performance of the I/O!
Still no word on existing skeletal tracking engines. Is there a java based NUI out there anywhere?


text:
Q: First time login core php logic in drupal I dont' want to do it by using other modules, ex rules, first_login etc
In theme page.tpl.php i want a logic that will check if user is logged in first time and show him some message,

A: This should be done in a module, not in page.tpl.php.
Why do you only want to do it in page.tpl.php?
Module code may look like this:
function MODULENAME_user_login(&$edit, $account) {
  // If this is user's first time log-in.
  if ($account->access == 0) {
    drupal_set_message('first time login');
  }
}


text:
Q: Django - ImportError : no module named django.core.wsgi I am trying to deploy my Django application with Apache and mod_wsgi.
I installed and configured them according to following references:-
https://modwsgi.readthedocs.io/en/develop/user-guides/quick-installation-guide.html
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/modwsgi/
My django project tree - /home/zahlen
 mysite
├── db.sqlite3
├── log
│   ├── access.log
│   └── error.log
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── settings.py
│   ├── static
│   ├── templates
│   ├── urls.py
│   ├── views.py
│   ├── wsgi.py
├── places
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── static
│   ├── templates
│   ├── tests.py
│   ├── urls.py
│   ├── views.py
└── static

django is present in /home/zahlen/.local/lib/site-packages
//apache2/apache2.conf
....
....
LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
WSGIPythonPath /home/zahlen/mysite:/home/zahlen/.local/lib/python2.7/site-packages
<Directory /home/zahlen/mysite/mysite>
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

//apache2/sites-available/000-default.conf  VirtualHost Configuration
<VirtualHost *:80>
    ServerName www.mysite.com
    ServerAlias mysite.com
    ServerAdmin webmaster@mysite.com
    Alias /static /home/zahlen/mysite/mysite
    <Directory /home/zahlen/mysite/static>
        Require all granted
    </Directory>
    ErrorLog /home/zahlen/mysite/log/error.log
    CustomLog /home/zahlen/mysite/log/access.log combined

    <Directory /home/zahlen/mysite/mysite/>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess mysite.com python-path=/home/zahlen/mysite
    WSGIProcessGroup mysite.com
    WSGIScriptAlias / /home/zahlen/mysite/mysite/wsgi.py
</VirtualHost>

Django and mod_wsgi are configured to use python2.7
 . Vitualenv is not used and
Apache uses the Event MPM
All of this is on a Ubuntu Server Virtual Machine.
//log/apache2/error.log gives the following line which verifies use of python2.7
....
[Sat Feb 17 02:16:45.475182 2018] [mpm_event:notice] [pid 7282:tid 140680615626624] AH00489: Apache/2.4.18 (Ubuntu) OpenSSL/1.0.2g mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
....

/home/zahlen/mysite/mysite/wsgi.py
import os,sys
sys.path.append('/home/zahlen/mysite')
sys.path.append('/home/zahlen/mysite/mysite')
sys.path.append('/home/zahlen/.local/lib/python2.7/site-packages')
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = get_wsgi_application()

My browser throws Internal Server Error on the host machine every time i open my site using ip address of the VM
//mysite/log/error.log
[Sat Feb 17 02:13:55.862423 2018] [wsgi:error] [pid 7152:tid 139643385603840] [remote 192.168.56.1:46153] mod_wsgi (pid=7152): Target WSGI script '/home/zahlen/mysite/mysite/wsgi.py' cannot be loaded as Python module.
[Sat Feb 17 02:13:55.862536 2018] [wsgi:error] [pid 7152:tid 139643385603840] [remote 192.168.56.1:46153] mod_wsgi (pid=7152): Exception occurred processing WSGI script '/home/zahlen/mysite/mysite/wsgi.py'.
[Sat Feb 17 02:13:55.862579 2018] [wsgi:error] [pid 7152:tid 139643385603840] [remote 192.168.56.1:46153] Traceback (most recent call last):
[Sat Feb 17 02:13:55.862619 2018] [wsgi:error] [pid 7152:tid 139643385603840] [remote 192.168.56.1:46153]   File "/home/zahlen/mysite/mysite/wsgi.py", line 12, in <module>
[Sat Feb 17 02:13:55.862743 2018] [wsgi:error] [pid 7152:tid 139643385603840] [remote 192.168.56.1:46153]     from django.core.wsgi import get_wsgi_application
[Sat Feb 17 02:13:55.862781 2018] [wsgi:error] [pid 7152:tid 139643385603840] [remote 192.168.56.1:46153] ImportError: No module named django.core.wsgi

It seems that wsgi.py couldn't import the django package but it is present in /home/zahlen/.local/lib/site-packages/python2.7 directory
Can anyone light me the issue please?

A: Set up sys.path in the wsgi.py before you import Django module.


text:
Q: How can I make it impossible for my class member functions to be called in main? I'm writing a few classes for a homework assignment and I want it to be impossible for my class member functions to be called in main. If they are, I want the program to exit. How would I know when my member functions are being called? As for the class, each object represents a color in the format of <100,200,215>. Thanks for the help!
class Color{

public:
    Color( unsigned red = 0, unsigned green = 0, unsigned blue = 0 );    //  ctor
    unsigned getRed() const;    //  accessor
    unsigned getGreen() const;    //  accessor
    unsigned getBlue() const;    //  accessor
    Color & setRed( unsigned red );    //  mutator
    Color & setGreen( unsigned green );    //  mutator
    Color & setBlue( unsigned blue );    //  mutator
    const Color & output() const;
private:
    unsigned myRed;
    unsigned myGreen;
    unsigned myBlue;
    static unsigned okColor(unsigned color);

}; //Class Color

int main(int argc, const char * argv[])
{

}

Color::Color( unsigned red, unsigned green, unsigned blue):
myRed(okColor(red)),myGreen(okColor(green)),myBlue(okColor(blue))
{
    //initialization list here...
}

//accessors
unsigned Color::getRed() const {return myRed;}
unsigned Color::getGreen() const {return myGreen;}
unsigned Color::getBlue() const {return myBlue;}

//mutators
Color & Color::setRed(unsigned red){
    myRed = okColor(red);
    return *this;
}

Color & Color::setGreen(unsigned green){
    myGreen = okColor(green);
    return *this;
}

Color & Color::setBlue(unsigned blue){
    myBlue = okColor(blue);
    return *this;
}

//output
const Color & Color::output() const{

    cout << "<" << myRed << "," << myGreen << "," << myBlue << ">" << endl;
    return *this;
}

//checkers
unsigned Color::okColor(unsigned myColor){

    if (myColor > 255) {
        die("Color intensity is out of range!");
    }

    return myColor;
}

bool die(const string & msg){

    cerr << endl << "Fatal error: " << msg <<endl;
    exit(EXIT_FAILURE);
}

Color mixture( const Color & color0, const Color & color1, double weight){

    double color1Multiplier = 0;
    Color mixture;
    unsigned mixtureRed;
    unsigned mixtureBlue;
    unsigned mixtureGreen;

    color1Multiplier = 1 - weight;

    mixtureRed = (color0.getRed() * weight) + (color1.getRed() * color1Multiplier);
    mixtureBlue = (color0.getBlue() * weight) + (color1.getBlue() * color1Multiplier);
    mixtureGreen = (color0.getGreen() * weight) + (color1.getGreen() * color1Multiplier);

    mixture.setRed(mixtureRed);
    mixture.setBlue(mixtureBlue);
    mixture.setGreen(mixtureGreen);

    return mixture;
}

A: It is simple to prevent your class from being called from main. Don't create the class in main - no class -> no way to call the member functions (unless they are static). You can also move your #include of the class header to some file that isn't in the same source as main.
Unfortunately, there is no (trivial and/or portable) way to determine which function called your code [especially if we bear in mind that modern compilers quite often move code around, so although your code is calling mixture from main, the compiler decides to just move that into main, because that makes it faster, smaller or whatever other goal the compiler has with inlining functions].
Other that that, there is no way to stop a function from being called from any function that has access to the object. For nearly every aspect of functions, main is no different from other functions. The only difference is that main is called from the C++ runtime library. But the compiler doesn't really care if your function is called main, kerflunk or fred.

A: If you create a global object it will be initialised before main, and destroyed after main exits.
You can use this fact to set a flag and behave however you wish.


text:
Q: Emit or Ack timeout handling in Android socket.IO ? When working with socket.io emitted message with callback, if the socket disconnect before answering (or doesn't answer at all) the callback function hangs up forever.In other situations where network connectivity is low and sockets are emitted but there are no callbacks if the emit was successful.
In these situations i want to implement timeout in emit callback.But there is not timeout for ACK message.
Here my socket emitting code with ACK
    JSONObject obj = new JSONObject();
    try {

        obj.put("device_id", deviceVO.getDeviceId());
        obj.put("device_status", deviceVO.getOldStatus());

    } catch (JSONException e) {
        e.printStackTrace();
    }

   mSocket.emit("socketChangeDevice", obj, new Ack() {
            @Override
            public void call(Object... args) {
                if(args!=null){
                    Ack ack = (Ack) args[args.length - 1];
                    ack.call();
                    Log.d("ACK_SOCKET","isAck : "+ ack);
                }
            }
        });

is there any better way to return a failed callback on client disconnecting ? i need to implement timeout manually ?

A: Timeout ACK with socket emit
My AckWithTimeOut custom Timeout class with implements Ack interface
public class AckWithTimeOut implements Ack {

private Timer timer;
private long timeOut = 0;
private boolean called = false;

public AckWithTimeOut() {
}

public AckWithTimeOut(long timeout_after) {
    if (timeout_after <= 0)
        return;
    this.timeOut = timeout_after;
    startTimer();
}

public void startTimer() {
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            callback("No Ack");
        }
    }, timeOut);
}

public void resetTimer() {
    if (timer != null) {
        timer.cancel();
        startTimer();
    }
}

public void cancelTimer() {
    if (timer != null)
        timer.cancel();
}

void callback(Object... args) {
    if (called) return;
    called = true;
    cancelTimer();
    call(args);
}

@Override
public void call(Object... args) {

}
}

add AckWithTimeOut in socket emit listener
 mSocket.emit("socketChangeDeviceAck", obj, new AckWithTimeOut(5000) {
            @Override
            public void call(Object... args) {
                if(args!=null){
                    if(args[0].toString().equalsIgnoreCase("No Ack")){
                        Log.d("ACK_SOCKET","AckWithTimeOut : "+ args[0].toString());
                    }else if(args[0].toString().equalsIgnoreCase("true")){
                       cancelTimer(); //cancel timer if emit ACK return true
                       Log.d("ACK_SOCKET","AckWithTimeOut : "+ args[0].toString());
                    }
                }
            }
        });

A: Kotlin implementation
class AckWithTimeout(
    private var onSuccess: (args: Array<out Any>) -> Unit,
    private var onTimeout: () -> Unit,
    private val timeoutInMillis: Long
) : Ack {
    private var called = false

    private val timer: Timer = Timer().apply {
        schedule(object : TimerTask() {
            override fun run() {
                if (called) return
                called = true

                onTimeout()
            }
        }, timeoutInMillis)
    }

    override fun call(vararg args: Any) {
        if (called) return
        called = true
        timer.cancel()

        onSuccess(args)
    }
}


text:
Q: Node.js, Express and css, js, image assets I would like to have all javascript, css and images that are sent to the browser to be concatenated, minified and have a md5 cache busting filename.  I've been able to achieve this with packages like connect-assets and others.
However I have not been able to add the md5'ed image filename into the css before it is processed.
I am using Less css templates.
Any pointers to packages that could help me would be great.
eg
image.png is converted to image-455454545.png
css references  background-image: url(image.png) -> should change to image-455454545.png

A: As far as I know, Less doesn't have the ability to utilize user-defined functions. Stylus, however, does. So if you're willing to hop onto an alternate CSS preprocessor, then there is great fun to be had! (Stylus is really very simliar to Less, and it shouldn't take much to switch to it. Plus connect-assets already supports Stylus, so it should plug into your environment easily.)
server.js
var fs = require('fs');
var stylus = require('stylus');

stylus(fs.readFileSync("styles.styl", 'utf8')) //load stylus file
  .define("versionedFile", versionedFile) //add our custom function to the stylus env
  .render(function(err, css){ //render!
    if (err) {
      throw err;
    }

    fs.writeFileSync("styles.css", css); //write the compiled css to a .css file
});

//our custom function
function versionedFile(filename) {
  ... lookup versioned file of filename ...
  return "versionedFilename.png"
}

styles.styl
.image-block {
  background-image: url(versionedFile('unversionedFilename.png')); //this is how we use our custom function
}

Which will compile into:
styles.css
.image-block {
  background-image: url("versionedFilename.png"); //hooray!
}


text:
Q: How to prevent global css style from UI framework in Vue I'm using a UI framework called Element UI and I'm using their tables for my project. I need the body of the tables to have some padding at the top to make room for a filter input that is put at the top before the rows begin. Although, not all tables in my project will have this filter input so not all tables need this padding, my issue is that I'm targeting a class that comes from Element UI (not one that I created myself) and the only file that the code acknowledges this selector is within App.vue. Trying to put this styling in the individual files doesn't work. I'm trying to only remove this padding for one certain file and keep the padding for all others.
App.vue file
.el-table__body {
  padding-top: 48px;
}

A: I have been using element UI for 2 years, and I had the same problem. The thing in Element-UI styles is that they can be styled inside their own component.
Let's say for your case, you can style only the "el-table" by adding "custom class" to it and still can use scoped, but what's inside "el-table__body" cannot be styled when you use scoped.
And if you really want to style, remove "scoped" from "style", like this:
<style>
  .el-table__body{
    padding-top: 200px;
  }
</style>

Note: the above trick will apply the styles to all other tables when you come to this component and then open any other component which has the same "el-table__body" class.
To avoid the effect on other component's tables style, add a custom class name and then target the el-table__body.
For example:
<el-table
      :data="tableData"
      class="stack-table"
      style="width: 100%">
      <el-table-column
        prop="date"
        label="Date"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="Name"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="Address">
      </el-table-column>
    </el-table>

And CSS style target like this:
.stack-table .el-table__body{
   padding-top: 200px;
 }


text:
Q: Web Scraping Youtube URL on Genius with Request I am using request along with cheerio to try to grab the link to a song on genius.com. The URL should be a YouTube link. The problem is that I simply cannot get the 'a' element to return its href attribute. This is my code (cheerio and request are loaded farther up in the script).
request('https://genius.com/Eminem-the-monster-lyrics' , function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(body);
        var url = $('a' , 'div.song_media_controls-provider-icon').attr('href');

    }
    console.log(url);
});

I apologize if its a stupid problem or a stupid post. I'm still learning with all of this. Thank you to anyone for help.

A:

// jQuery cross domain ajax
$.get("https://genius.com/Eminem-the-monster-lyrics").done(function (data) {
    console.log(data);
});

// using XMLHttpRequest
var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
};
xhttp.open("GET", "https://genius.com/Eminem-the-monster-lyrics", true);
xhttp.send();
<!DOCTYPE html>

  <title>NK Chaudhary</title>

Add here genius.com


text: Q: создание dll в codeblocks Всем привет. Создаю dll в codeblocks, имею структуру проекта main.cpp и main.h. После того как делаю build на выходе получаю три файла: .dll .a .def. Всю эту красоту подключаю в Qt. Qt, конечно же, просит подключить еще и header, прописываю ему путь до main.h. В итоге все работает, все хорошо. Но include выглядит - #include "main.h", что не очень красиво. Вопрос-можно ли как то поменять название header, например с main.h на myApi.h, или же как то сразу в codeblocks создать структуру не main.cpp main.h, а скажем myApi.cpp maApi.h? Заранее спасибо.


text:
Q: Ember.js helper with mixed arguments I'm using js-routes for Rails and would like to use this in combination with Ember.js. I wrote a helper to fetch the routes from the global Routes as provided by js-routes, but I can't seem to get it working.
Usage: {{route 'user_path' user.id}}
Expected return: /users/123
Attempt 1:
Ember.Handlebars.registerHelper('route', function(path, id) {
    console.log(path); // returns the path as a string --> OK!
    console.log(id); // returns the string 'user.id' --> Not ok!
    return Routes[path](id);
});

Attempt 2:
Ember.Handlebars.registerBoundHelper('route', function(path, id) {
    console.log(path); // returns undefined --> Not OK!
    console.log(id); // returns 123 --> OK!
    return Routes[path](id);
});

How can I achieve this? Thanks!

A: Never mind, I found it myself:
Ember.Handlebars.registerBoundHelper('route', function(context, options) {
    return Routes[options.hash.path](context.id);
});

Usage: {{route this path='user_path'}}


text:
Q: Decompressing a BLOB from SQLite with Python Using Python 2.7, I am storing web-pages in SQLite into a BLOB type column:
The compression is with zlib, and I'm inserting it as sqlite3.Binary type.
Without compression this works fine:
db_body = sqlite3.Binary(page_body)
dbc.execute("insert into table (content) values ?", db_body)

With compression also works fine:
db_body = sqlite3.Binary(zlib.compress(page_body))
dbc.execute("insert into table (content) values ?", db_body)

The problem comes when I try and retrieve the compressed data. I have tried the following:
dbc.execute("select content from table limit 1")
sql_result =  dbc.fetchone()

page_content = zlib.decompress(sql_result[0])

But the result (page_content) is a str type that's still compressed. There are no errors or exceptions. The content type of sql_result[0] is a Buffer, so the decompress function is changing the data type but not the content.
If I compress and recompress at the same time, without putting it through sqlite, the output is fine:
db_body = sqlite3.Binary(zlib.compress(page_body))
page_content = zlib.decompress(db_body)

So, how do I decompress data that I've inserted and then retrieved from SQLite?

A: Are you sure you need to use sqlite3.Binary?
db = sqlite3.connect('/tmp/mydb')
db.execute('CREATE TABLE tbl (bin_clmn BLOB)')
db.execute('INSERT INTO tbl  VALUES(?)', [buffer(zlib.compress(page_body))])
db.commit()
db.close()

db = sqlite3.connect('/tmp/mydb')
row = db.execute('SELECT * FROM tbl').fetchone()
page_body_decompressed = zlib.decompress(str(row[0]))
print page_body == page_body_decompressed


text:
Q: i am trying to print out this simply equation, but it says float object is not callable I have been trying to print out this very simple equation but I cannot figure out why it will not print?
fc = float(input("first cycle is "))
fp = float(input("first percent is "))

sc = float(input("second cycle is "))
sp = float(input("second percent is "))

tc = float(input("third cycle is "))
tp = float(input("third percent is "))

mem = float(input("the memory is "))

first_part = (fc * fp + (sc(1-fp)))

print(first_part)

It gives me the error "TypeError: 'float' object is not callable"

A: The * multiplication operator cannot be omitted as it can in an algebraic equation. The interpreter thinks sc(1-fp) is a function call.
first_part = (fc * fp + (sc * (1-fp)))


text:
Q: Search for a specific term in a Lucene index I'm trying to conduct a search on a Lucene index with some specific words that I know are indexed but the result is not very good.
How do I perform a query to a specific term ("129202")? I've tried adding the plus sign at the beginning of the string but it did not work.
My query:
QueryParser q = new QueryParser(Version.LUCENE_42, "tags", new SimpleAnalyzer(Version.LUCENE_42));
Query query = q.parse("sapatilha feminina ramarim 129202 cinza");

Below is a document (xml) indexed that I want to get
<?xml version="1.0" encoding="UTF-8"?>
<product>
 <tags>
   <tag>Sapatilha Pedras Preto</tag>
   <tag>ramarin</tag>
   <tag>ramarin 129202</tag>
   <tag>preto</tag>
 </tags>
 <id>71</id>
 <url>http://www.dafiti.com.br/Sapatilha-Pedras-Preto-1135428.html</url>
</product>

A: SimpleAnalyzer, the analyzer you are using to query (and I assume to index), uses a LetterTokenizer, which, according to documentation:

...defines tokens as maximal strings of adjacent letters, as defined by java.lang.Character.isLetter()

Which is to say, not numbers.  Numbers will be lost entirely by this analyzer.  I recommend you look into a different one, such as StandardAnalyzer or WhitespaceAnalyzer.

To demonstrate:
StringReader reader = new StringReader("ramarim 129202 cinza");
LetterTokenizer stream = new LetterTokenizer(Version.LUCENE_42, reader);
stream.setReader(reader);
stream.reset();
while(stream.incrementToken()) {
    System.out.println(stream.reflectAsString(false));
}
stream.close();

Outputs:
term=ramarim,bytes=[72 61 6d 61 72 69 6d],startOffset=19,endOffset=26
term=cinza,bytes=[63 69 6e 7a 61],startOffset=34,endOffset=39

Substituting in StandardTokenizer (which is used by StandardAnalyzer) will get you:
term=ramarim,bytes=[72 61 6d 61 72 69 6d],startOffset=19,endOffset=26,positionIncrement=1,type=<ALPHANUM>
term=129202,bytes=[31 32 39 32 30 32],startOffset=27,endOffset=33,positionIncrement=1,type=<NUM>
term=cinza,bytes=[63 69 6e 7a 61],startOffset=34,endOffset=39,positionIncrement=1,type=<ALPHANUM>