text:
Q: Modelling a time series with the "optimal" combination of N proxy series I have a time series T.
I also a universe U of time series  such that A, B, C ... Q are time series that belong to the universe U.
My problem decomposes into the following sub tasks:

*

*Find a subset of N time series from universe U. Denote this subset S

*Find an optimal scaling (a scalar matrix) to be applied to each of the time series selected in S such that:
i. a new optimal time series O is created from the combination of the time series in S
ii. O closely "tracks" T - i.e. O is highly cointegrated with T
I am thinking of implementing this in R. Can anyone please point me in the right direction of implementing tasks 1 and 2?
Edit
Note: T and the set of time series in U are all non-stationary.


text:
Q: Rails: Scope an entire model I am imagining something similar to this:
class User < ApplicationRecord

    default_scope -> { where(public: true) }

end

Now whenever the User model gets accessed it should always append where(public: true) to querys. So all would end up being all.where(public: true).
I'm trying to put something like this into the ApplicationRecord class to override behavior on all inheriting models, thus manually overriding is not an option for me.

A: If the default_scope remains same for all inheriting models, then you can consider putting that in a custom model and let all other models inheriting from that model
class CustomModel < ApplicationRecord
  default_scope -> { where(public: true) }
end

And let other models inherit from that custom model like so
class A < CustomModel
end

A: If all your models have public as a property, then you can add the default_scope on all the models by adding it to app/models/application_record.rb;
However, having a default_scope of where(public: true) is a little bit tricky here cause you won't be able to access the data not_public data unless you use the unscoped method: User.unscoped.
That being said, it's better if you add a scope scope :public, -> () { where(public: true) } and call it whenever you want to make sure that your user is public:
User.public.find_by(email: 'xxxxx')

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to parse string into GADT I am trying trying to implement Combinatory Logic in Haskell, and I would like to write to parser for the language. I am having trouble getting a parser to work via Parsec. The basic problem is that I need a way to ensure that the objects returned by the parser are well typed. Does anyone have any creative ideas on how to do this?
{-# Language GeneralizedNewtypeDeriving #-}

import qualified Data.Map as Map
import qualified Text.ParserCombinators.Parsec as P
import Text.Parsec.Token (parens)
import Text.ParserCombinators.Parsec ((<|>))
import Control.Applicative ((<$>), (<*>), (*>), (<*))

data CTree = CApp CTree CTree | CNode String deriving (Eq, Read)
instance Show CTree where
    show c@(CApp x y) = showL c
        where showL (CApp x' y')= "(" ++ showL x' ++ " " ++ showR y' ++ ")"
              showL (CNode s) = s
              showR (CApp x' y') = "(" ++ showL x' ++ " " ++ showR y' ++ ")"
              showR (CNode s) = s

    show (CNode s) = s

-- | Parser
parseC :: String -> Maybe CTree
parseC s = extract$ P.parse expr "combinator_string" s
           where extract (Right r) = Just r
                 extract (Left e) = Nothing

expr :: P.CharParser () CTree
expr = P.try (CApp <$> (CApp <$> term <*> term) <*> expr)
       <|> P.try (CApp <$> term <*> term)
       <|> term

term = P.spaces *> (node <|> P.string "(" *> expr <* P.string ")")

node :: P.CharParser () CTree
node = CNode <$> (P.many1 $ P.noneOf "() ")

eval (CApp (CNode "I") x) = x
eval (CApp (CApp (CApp (CNode "S") f) g) x) =
    (CApp (CApp f x) (CApp g x))
eval (CApp (CApp (CApp (CNode "B") f) g) x) =
    (CApp f (CApp g x))
eval (CApp (CApp (CApp (CNode "C") f) g) x) =
    (CApp (CApp f x) g)
eval x = x

A: I'm a strong advocate of parsing to an monotyped representation, and then applying a typechecking/elaboration phase to convert that into the typed (GADT) representation.  The best tutorial on the general idea is probably from Lennart Augustsson's llvm based compiler
A representation for the SKI calculus might look like
data TyComb t where
  TyS   :: TyComb ((a -> b -> c) -> (a -> b) -> a -> c)
  TyK   :: TyComb (a -> b -> a)
  TyI   :: TyComb (a -> a)
  TyApp :: TyComb (a -> b) -> TyComb a -> TyComb b

evalTyComb :: TyComb t -> t
evalTyComb TyS         = \x y z -> (x z) (y z)
evalTyComb TyK         = const
evalTyComb TyI         = id
evalTyComb (TyApp a b) = (evalTyComb a) (evalTyComb b)


text:
Q: How to place multiple span text inline with SVG image inside an anchor? This is a noob question, and I spent 2 hrs solving this already. I have an anchor which has SVG and two span text inline. What I'm going to do is inline all the span text with SVG, but I have never reached it. I only made the first span inline with SVG, however for the second span I don't know how to place it under the first span. Can you guys help? :D
Anyway I did:

*

*Making multiple lines of text inline with an image but It inline 1 span only.

/* Title and Subtitle logo */
    svg {
            filter: url(#Slogo)
          }

          .logoIcon {
            vertical-align: top;
          }

    @media (max-width: 600px) {
      a.navbar-brand span.head-title {
        font-size: 16px;
        font-weight: bolder;
        vertical-align: top;
      }

    a.navbar-brand span.head-title::after {
    content: '\A';
    white-space: pre;
    }

      a.navbar-brand span.head-subtitle {
        font-size: 10px;
        font-weight: 400;
      }
    }

    @media (min-width: 600px) {
      a.navbar-brand span.head-title {
        font-size: 20px;
        font-weight: bolder;
        vertical-align: top;
      }
 a.navbar-brand span.head-title::after {
    content: '\A';
    white-space: pre;
}
      a.navbar-brand span.head-subtitle {
        font-size: 14px;
        font-weight: 400;
      }
    }
          <a class="navbar-brand" style="margin-top:0" rel="tooltip" title="Brand" data-placement="bottom" href="<?= base_url() ?>">
            <svg xmlns=" http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="35pt" height="35pt" class="logoIcon" viewBox="0 0 150 150" version="1.2">
              <defs>
                <filter id="Slogo">
                  <feColorMatrix type="matrix" values="0 1 0 0 0
              0 1 0 0 0
              0 1 0 0 0
              0 1 0 1 0 " />
                </filter>
                <g>
                  <symbol overflow="visible" id="glyph0-0">
                    <path style="stroke:none;" d="M 12.609375 -95.546875 L 67.578125 -95.546875 L 67.578125 0 L 12.609375 0 Z M 19.40625 -6.796875 L 60.78125 -6.796875 L 60.78125 -88.75 L 19.40625 -88.75 Z M 19.40625 -6.796875 " />
                  </symbol>
                  <symbol overflow="visible" id="glyph0-1">
                    <path style="stroke:none;" d="M 68.421875 -26.53125 C 68.421875 -17.90625 65.316406 -11.109375 59.109375 -6.140625 C 52.898438 -1.171875 44.265625 1.3125 33.203125 1.3125 C 23.003906 1.3125 13.984375 -0.601562 6.140625 -4.4375 L 6.140625 -23.265625 C 12.585938 -20.390625 18.046875 -18.363281 22.515625 -17.1875 C 26.984375 -16.007812 31.066406 -15.421875 34.765625 -15.421875 C 39.210938 -15.421875 42.625 -16.269531 45 -17.96875 C 47.375 -19.664062 48.5625 -22.191406 48.5625 -25.546875 C 48.5625 -27.421875 48.035156 -29.085938 46.984375 -30.546875 C 45.941406 -32.003906 44.40625 -33.410156 42.375 -34.765625 C 40.351562 -36.117188 36.226562 -38.273438 30 -41.234375 C 24.15625 -43.984375 19.773438 -46.617188 16.859375 -49.140625 C 13.941406 -51.671875 11.609375 -54.613281 9.859375 -57.96875 C 8.117188 -61.320312 7.25 -65.242188 7.25 -69.734375 C 7.25 -78.179688 10.113281 -84.820312 15.84375 -89.65625 C 21.570312 -94.5 29.492188 -96.921875 39.609375 -96.921875 C 44.566406 -96.921875 49.300781 -96.332031 53.8125 -95.15625 C 58.320312 -93.976562 63.039062 -92.320312 67.96875 -90.1875 L 61.4375 -74.4375 C 56.332031 -76.53125 52.113281 -77.988281 48.78125 -78.8125 C 45.445312 -79.644531 42.171875 -80.0625 38.953125 -80.0625 C 35.117188 -80.0625 32.175781 -79.164062 30.125 -77.375 C 28.082031 -75.59375 27.0625 -73.265625 27.0625 -70.390625 C 27.0625 -68.597656 27.472656 -67.035156 28.296875 -65.703125 C 29.128906 -64.378906 30.445312 -63.097656 32.25 -61.859375 C 34.0625 -60.617188 38.34375 -58.382812 45.09375 -55.15625 C 54.019531 -50.882812 60.140625 -46.601562 63.453125 -42.3125 C 66.765625 -38.019531 68.421875 -32.757812 68.421875 -26.53125 Z M 68.421875 -26.53125 " />
                  </symbol>
                </g>
              </defs>
              <g id="surface1">
                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(87.059021%,67.059326%,53.729248%);fill-opacity:1;" d="M 139.300781 149.542969 L 10.386719 149.542969 C 5.078125 149.542969 0.75 145.21875 0.75 139.90625 L 0.75 10.992188 C 0.75 5.683594 5.078125 1.355469 10.386719 1.355469 L 139.300781 1.355469 C 144.613281 1.355469 148.9375 5.683594 148.9375 10.992188 L 148.9375 139.90625 C 148.9375 145.21875 144.613281 149.542969 139.300781 149.542969 Z M 139.300781 149.542969 " />
                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 130.820312 72.535156 L 97.136719 42.921875 L 98.167969 87.742188 L 109.066406 77.109375 L 118.664062 97.703125 L 125.257812 94.609375 L 115.660156 74.058594 Z M 130.820312 72.535156 " />
                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 118.664062 99.273438 C 118.488281 99.273438 118.308594 99.230469 118.128906 99.183594 C 117.722656 99.050781 117.410156 98.738281 117.230469 98.378906 L 108.574219 79.800781 L 99.289062 88.867188 C 98.84375 89.3125 98.167969 89.449219 97.585938 89.179688 C 97.003906 88.957031 96.644531 88.371094 96.601562 87.742188 L 95.566406 42.964844 C 95.566406 42.335938 95.925781 41.753906 96.464844 41.484375 C 97.046875 41.214844 97.722656 41.351562 98.167969 41.753906 L 131.851562 71.367188 C 132.300781 71.769531 132.480469 72.445312 132.300781 73.027344 C 132.121094 73.609375 131.582031 74.058594 130.953125 74.105469 L 117.992188 75.359375 L 126.648438 93.933594 C 127.007812 94.742188 126.695312 95.640625 125.886719 96 L 119.292969 99.09375 C 119.113281 99.230469 118.890625 99.273438 118.664062 99.273438 Z M 109.066406 75.539062 C 109.15625 75.539062 109.246094 75.539062 109.335938 75.585938 C 109.832031 75.675781 110.277344 75.988281 110.457031 76.480469 L 119.382812 95.640625 L 123.152344 93.890625 L 114.226562 74.6875 C 114 74.238281 114.046875 73.699219 114.269531 73.25 C 114.496094 72.800781 114.988281 72.535156 115.480469 72.445312 L 127.050781 71.277344 L 98.796875 46.421875 L 99.648438 84.066406 L 107.945312 75.941406 C 108.261719 75.71875 108.664062 75.539062 109.066406 75.539062 Z M 109.066406 75.539062 " />
                <g style="fill:rgb(100%,100%,100%);fill-opacity:1;">
                  <use xlink:href="#glyph0-1" x="14.848997" y="122.254314" />
                </g>
              </g>
            </svg>
            Brand Title
            Brand Subtitle


text:
Q: Jena TDB in Python? Is it possible to run a Jena TDB database from a Python app to store a large amount of RDF data? What would be a native alternative in Python?

A: An alternative is to use a SPARQL endpoint such as Apache Jena's Fuseki and just use an HTTP client from Python or any other language.
To read more about Fuseki, look here:

*

*http://incubator.apache.org/jena/documentation/serving_data/

A: http://code.google.com/p/python-graphite/ A Python package that make it possible to use Jena in Python

A: An alternative is to run the python code under Jython not the normal C based Python run time.
Jython converts python code to the JVM language. It cannot therefore call python extensions that use C but it can call all Java classes including the Jena TDB and all pure python modules.


text:
Q: Why didn't Voldemort hide a Horcrux in the Chamber of Secrets? I know that Voldemort thought that he was the only one to find the Room of Requirement...

As for the school: He alone knew where in Hogwarts he had stowed the Horcrux, because he alone had plumbed the deepest secrets of that place...

but why didn't he use the Chamber of Secrets instead?  It is both grandiose and more secure, requiring Parseltongue to enter and yet again underscoring his claim as the Heir of Slytherin, like the diary.

Harry: "The diary wasn't that special."
  Dumbledore: "The diary, as you have said yourself, was proof that he was the Heir of Slytherin; I am sure that Voldemort considered it of stupendous importance."
  — Harry Potter and the Half-Blood Prince, Chapter 23: Horcruxes

Is there any mention of why he didn't hide the Horcrux in the Chamber instead of the Room of Requirement?

A: I'm not aware of any mention of it in the book, but my guess is:

*

*He had already hidden one Horcrux in Hogwarts - Rowena Ravenclaw's Diadem hidden in Room of Requirements. It was safe to not keep two Horcruxes in school.

*Remember that basilisks fangs were able to destroy Horcruxes. Maybe he thought that the Chamber was not a safe place with Basilisk in it.

A: Well, mostly because he wanted the Chamber opened. He wanted to get someone into that place, he wanted to give them the diary that would take them into it.

'[...] What intrigued and alarmed me most was that that diary had been intended as a weapon as much as a safeguard.'
'I still don't understand,' said Harry.
'Well, it worked as a Horcrux is supposed to work - in other words, the fragment of soul concealed inside it was kept safe and had undoubtedly played its part in preventing the death of its owner. But there could be no doubt that Riddle really wanted that diary read, wanted the piece of his soul to inhabit or possess somebody else, so that Slytherin's monster would be unleashed again.'
'Well, he didn't want his hard work to be wasted,' said Harry. 'He wanted people to know he was Slytherin's heir, because he couldn't take credit at the time.'
'Quite correct,' said Dumbledore, nodding.
Harry Potter and the Half-Blood Prince - p.468 - Bloomsbury - Chapter 23, Horcruxes

It's not much of a hiding place, if you yourself are going to give some future student the keys.
Second, you need to appreciate that Voldemort is convinced that he alone knows of the Room of Hidden Things. He is the heir of Slytherin, he believes Hogwarts is his birthright and that he alone knows its secrets, that to him alone has Hogwarts revealed its secrets. He is arrogant enough to believe that nobody else could have found the Room of Hidden Things and isolated enough never to have heard others mention it.

As for the school: he alone knew where in Hogwarts he had stowed the Horcrux, because he alone had plumbed the deepest secrets of that place ...
Harry Potter and the Deathly Hallows - p.444 - Bloomsbury - Chapter 27, The Final Hiding Place

Again:

Tom Riddle, who confided in no one and operated alone, might have been arrogant enough to assume that he, and only he, had penetrated the deepest mysteries of Hogwarts Castle. Of course, Dumbledore and Flitwick, those model pupils, had never set foot in that particular place, but he, Harry, had strayed off the beaten track in his time at school - here at last was a secret he and Voldemort knew, that Dumbledore had never discovered -
Harry Potter and the Deathly Hallows - pp.498-9 - Bloomsbury - Chapter 31, The Battle of Hogwarts

Finally, it seems to me that it may never have occurred to him to do so. That Chamber was great-great-great-...-great granddad Salazar's place. It had his statue, it housed his monster and it was about his plans for the school. Voldemort was proud of his ancestry and keen to reopen the Chamber and realise his great ancestor's plans. But it may not have occurred to him as the right place for his Horcruxes.
And hey, with Voldemort in charge and Hogwarts as it should be, the Chamber of Secrets would have no need of secrecy. He might even want to open the place up. Voldemort made his Horcruxes in order to realise plans for the wizarding world and Hogwarts school.

A: well, he thought he was the only one who knew about room of requirement. where as chamber of secrets is history(though a myth) and any parseltongue like him could reach it who could pose a threat to his horcrux. Oh wait! I just had an idea, voldemort will only think only he knew about ROQ if there was nothing else hidden there unlike when harry found the room. so does that mean nobody before him found it or if it was made for him? or maybe he made it! ok ill stop the silly questions. so my point is, its safer to hide in a place which nobody knows it exists than a place known to all however mythically or difficult to reach.


text:
Q: TypeError: SSLCommerzPayment is not a constructor I am trying to access SSLCommerz transaction api for payment gateway integration, but on api call I am getting this error.
TypeError: SSLCommerzPayment is not a constructor
      at D:\BlockChain\21.06.2022_PaymentGateway\secondPart\src\pages\app.js:58:24
      at Layer.handle [as handle_request] (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\layer.js:95:5)
      at next (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\route.js:144:13)
      at Route.dispatch (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\route.js:114:3)
      at Layer.handle [as handle_request] (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\layer.js:95:5)
      at D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\index.js:284:15
      at Function.process_params (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\index.js:346:12)
      at next (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\index.js:280:10)
      at jsonParser (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\body-parser\lib\types\json.js:110:7)
      at Layer.handle [as handle_request] (D:\BlockChain\21.06.2022_PaymentGateway\secondPart\node_modules\express\lib\router\layer.js:95:5)

How to solve the problem?

A: I solved the problem by changing package for SSLCommerz. I used sslcommerz-lts package and then the constructor don't show the error.
npm i sslcommerz-lts

const express = require('express')
const app = express()

const SSLCommerzPayment = require('sslcommerz-lts')
const store_id = '<your_store_id>'
const store_passwd = '<your_store_password>'
const is_live = false //true for live, false for sandbox

const port = 3030

//sslcommerz init
app.get('/create-session', (req, res) => {
    const data = {
        total_amount: 100,
        currency: 'BDT',
        tran_id: 'REF123', // use unique tran_id for each api call
        success_url: 'http://localhost:3030/success',
        fail_url: 'http://localhost:3030/fail',
        cancel_url: 'http://localhost:3030/cancel',
        shipping_method: 'Courier',
        product_name: 'Computer.',
        product_category: 'Electronic',
        product_profile: 'general',
        cus_name: 'Customer Name',
        cus_email: 'customer@example.com',
        cus_add1: 'Dhaka',
        cus_add2: 'Dhaka',
        cus_city: 'Dhaka',
        cus_state: 'Dhaka',
        cus_postcode: '1000',
        cus_country: 'Bangladesh',
        cus_phone: '01711111111',
        cus_fax: '01711111111',
        ship_name: 'Customer Name',
        ship_add1: 'Dhaka',
        ship_add2: 'Dhaka',
        ship_city: 'Dhaka',
        ship_state: 'Dhaka',
        ship_postcode: 1000,
        ship_country: 'Bangladesh',
    };
    const sslcz = new SSLCommerzPayment(store_id, store_passwd, is_live)
    sslcz.init(data).then(apiResponse => {
        // Redirect the user to payment gateway
        let GatewayPageURL = apiResponse.GatewayPageURL
        res.redirect(GatewayPageURL)
        console.log('Redirecting to: ', GatewayPageURL)
    });
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

Then I run in command prompt 'node index.js'
I got the output.

A: Change the
import {SSLPayment}

to
import * as SSLCommerzPayment from 'sslcommerz-lts';

and it will work


text:
Q: Do you still need to check the parent / child pipelines to determine whether to create ICrmService or CrmService in 2015? We currently use MS Dynamics CRM V4 and are in the process of upgrading to 2015. I've got the task of updating some of our plugins.
1 of the things I've come across that is a little confusing is whether I still need to do some sort of check on the stage of the pipeline to determine if it's a parent or child. As I understand it the parent and child pipelines have been merged into 1 as of 2011, so how should the following code be altered?
public CrmServiceProxy(IPluginExecutionContext context, Guid userId)
{
    if (context.InvocationSource == MessageInvocationSource.Parent)
    {
        iCrmService = context.CreateCrmService(userId);
    }
    else
    {
        try
        {
            RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
            string crmUrl = regkey.GetValue("ServerUrl").ToString();
            string crmServiceUrl = string.Concat(crmUrl, "/2007/crmservice.asmx");
            crmService = CreateCrmService(crmServiceUrl, context, userId);
        }
        catch (Exception)
        {
            throw new InvalidPluginExecutionException("Unable to create CrmServiceProxy - the service URL cannot be read from the Registry");
        }
    }
}

I've made a start like this:
private readonly IOrganizationService iCrmService;
private IOrganizationServiceFactory serviceFactory;

public CrmServiceProxy(IServiceProvider serviceProvider, Guid userId)
{
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

    serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

    if (context.Stage == 10) //10 should indicate it's the parent
    {
        iCrmService = serviceFactory.CreateOrganizationService(context.UserId);
    }
    else
    {
        try
        {
            RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
            string crmUrl = regkey.GetValue("ServerUrl").ToString();
            string crmServiceUrl = string.Concat(crmUrl, "/2007/crmservice.asmx");
            iCrmService = serviceFactory.CreateOrganizationService(crmServiceUrl, context, userId); //doesn't work, just something I was trying
        }
        catch (Exception)
        {
            throw new InvalidPluginExecutionException("Unable to create CrmServiceProxy - the service URL cannot be read from the Registry");
        }
    }
}

So, I understand that previously in V4 you needed to use CrmService for child pipelines and ICrmService for parent ones, hence the if statement to determine which pipeline it came from. However, do I still need to do this kind of check or can I just do away with the whole if statement and just create the service using ICrmService?

A: Actually Parent and Child pipelines were not merged. They still exist in Dynamics CRM 2011. I guess Microsoft simplified the model to prevent confusion. Also, in CRM 4.0 the child pipeline did not support free access to the CRM service; hence the different ways of creating ICrmService instances.
E.g. when an AssignRequest is issued, the following plugin steps are invoked:

*

*Validate Assign

*PreOperate Assign

*PreOperate Update

*(Platform operations)

*PostOperate Update

*PostOperate Assign

*Async Update

*Async Assign

Steps 3 and 5 are actually child pipeline steps; they both have a parent context belonging to the Assign message.

A: You need to rewrite also the class declaration, here an example you can use:
namespace PluginNamespace
{
    public class MyPluginClass : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            // ...
        }
    }
}


text:
Q: Spring Boot Project throwing "At least 1 bean exception" I'm not able to run my project. Getting NoBeanFoundException repeatedly.The exception is: No qualifying bean of type 'com.example.Model.Movie' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} The link for the repo is https://github.com/RaviShekhawat/BMSBackend

A: Your Movie class isn't a spring bean, so you won't be able to @Autowire it into the MovieController.
As your Movie is an @Entity it doesn't make sense to have it as a spring bean. Spring beans are usually singletons that have no state and hang around for the life of the application. Your movie does have state, and I assume should only hang around for individual requests.
I'm not sure what you're trying to do with the Movie movie field in the MovieController. But you don't really want to have it as a field. Most of the methods in your controller work how I'd expect in that they retrieve data from the database and return it to the caller, or take data from the caller and pass it to the database.
The first method...
    @Autowired
    Movie movie;

    @RequestMapping(value="/GetReactions", method= RequestMethod.GET)
    public Integer getReactions() {

       return movie.getNo_of_reviews();

    }

Looks like you're trying to save some state in the controller between calls. Don't do this.


text:
Q: Minimize Function does not give a solution I would be tremendously grateful for help with this one:
I wrote a function that, for a given frequency distribution (observed data) that i call fbar, and a probability distribution function of the Laplace family with parameters mu and sigma, minimizes the Kullback-Leibler divergence.
Then I use Minimize[] to find the KBD minimizing parameters mu and sigma.
When I did this for a very small (fake) dataset and a simple exponential function, the minimization gives a numerical value.
However, for the more complicated Laplace distribution and the larger dataset (200 entries), it only gives me {mu, sigma} as output, which is rather useless.
I attach the code, I am pretty sure, I did something wrong.
Laplace PDF:
laplace[x_, mu_, sigma_] := 1/(2*sigma) E^(-Abs[x - mu]/sigma)

KB Divergence:
KLlaplace[x_, mu_, sigma_] :=  Sum[If[fbar[[i]] == 0, 0,
     laplace[x[[i]], mu, sigma] * Log[laplace[x[[i]], mu, sigma] fbar[[i]]]], {i, 1, 200}]

Minimization:
Minimize[KLlaplace[x, mu, sigma], {mu, sigma}]

Edit: x is just an interval between -.99 and 1 with 200 bins, so Laplace[ ] calculates the PDF for the corresponding bins. I am afraid, I would not know how to attach the fbar dataset. It is a list of 200 values, corresponding frequencies to 200 bins of the same domain.

A: Following @J.M. 's suggestion about the LaplaceDistribution[] and modifying your definition of the Kullback-Leibler divergence...
(* Generate data from a Laplace distribution *)
SeedRandom[12345];
n = 1000;
y = RandomVariate[LaplaceDistribution[0, 0.16], n];

(* Put into bins *)
x = Table[i/100, {i, -99, 100}];
(* Proportion of observations in each bin *)
fbar = BinCounts[y, {-99/100, 1, 1/100}]/n;

(* Function that gives Kullback-Leibler divergence of Laplace distribution
 with binned version of observed distribution *)
kl[mu_, sigma_] :=
 Sum[If[fbar[[i]] == 0, 0,
   fbar[[i]] (Log[fbar[[i]]] -
      Log[CDF[LaplaceDistribution[mu, sigma], x[[i + 1]]] -
        CDF[LaplaceDistribution[mu, sigma], x[[i]]]])],
   {i, Length[fbar]}]

(* Find mu and sigma that minimize Kullback-Leibler divergence statistic *)
FindMinimum[kl[mu, sigma], {{mu, 0}, {sigma, 0.15}}]
(* {0.10119387738464815,{mu -> 0.0018434507409612973, sigma -> 0.1505939050029673}} *)

(* Maximum likelihood estimation on original data *)
FindDistributionParameters[y, LaplaceDistribution[mu, sigma]]
(* {mu -> 0.0013829360457713437, sigma -> 0.15054298262072455} *)

Update:  Minimizing the Kullback-Leibler divergence between the observed data and a specific distributional form is the same as performing maximum likelihood (Choi, date unknown).  So if all you have is the binned data (rather than the raw data), the maximum likelihood estimates can be obtained a little bit more directly with the following:
FindMaximum[
 Sum[fbar[[i]] Log[CDF[LaplaceDistribution[mu, sigma], x[[i + 1]]] -
     CDF[LaplaceDistribution[mu, sigma], x[[i]]]],
  {i, Length[fbar]}], {{mu, 0}, {sigma, 0.15}}]
(* {-4.405331024529697, {mu -> 0.0018434507409612552, sigma -> 0.15059390500296513}} *)


text:
Q: What is the default XSLT transformer used in spring integration xml? Using Spring Integration XML 3.0.0.RELEASE I have a XSLT transformer as such:
<int-xml:xslt-transformer id="tm100Totm120aTransformation"
    xsl-resource="classpath:xsd/mailxml/xslt/tm120b_to_tm140a.xsl"
    result-transformer="resultToString"
    input-channel="validatedtm100Message"
    output-channel="validatedtm120aMessage"/>

Without specifying the transformer-factory-class attribute, how does Spring determine which TransformerFactory is actually used?
The JavaDoc for TransformerFactory.newInstance() states:

Obtain a new instance of a TransformerFactory. This static method creates a new factory instance This method uses the following ordered lookup procedure to determine the TransformerFactory implementation class to load:

*

*Use the javax.xml.transform.TransformerFactory system property.

*Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JAXP implementation and it's values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.

*Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.transform.TransformerFactory in jars available to the runtime.

*Platform default TransformerFactory instance.

  Once an application has obtained a reference to a TransformerFactory it can use the factory to configure and obtain transformer instances.

Does Spring follow this procedure? I can't seem to find the details of how Spring does this in the Spring docs.
P.S.
Upon debug inspection it appears my application is using com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl as the implementation. My understanding is that Xalan is included with the JRE (I'm using Java 1.6); is it reasonable to assume then that I am using the Platform default TransformerFactory?

A: It's possible to do a run using -Djaxp.debug=true and confirm what is going on via the logs.
The bootstrap process of finding a  XSLT implementation is part of Xalan and it's design of separating the API from the multiple possible implementations.
As such this is not part of Spring but of Xalan, and spring uses it indirectly by calling the transformer factory method you mentioned.
The fact that the package name of the implementation chosen contains internal means that the default implementation shipped with the JVM was chosen, which is the last option in the bootstrap process.


text:
Q: Delete all scheduled task in Sidekiq I am working with rails and have the bunch of schedule tasks running on sidekiq, and anyway I want to delete all of that tasks from schedule list. I was wonder whether is there any command with rails I can run to clear all those stuff ?

A: There is. Given that your queue is called "my_queue":
require 'sidekiq/api'
Sidekiq::ScheduledSet.new("my_queue").clear

Check out Sidekiq API.

A: The accepted answer didn't work for me. What I did to clear the queue was:
Sidekiq::ScheduledSet.new.clear

If you need clearing the scheduled queue, you might need also clearing other queues:
Sidekiq::RetrySet.new.clear
Sidekiq::Queue.new("your_queue_name").clear
Sidekiq::Queue.all.each(&:clear)

A: Neither of the listed solutions worked for me so I had to shut down redis-server and sidekiq and delete the dump.rdb file. Keep in mind, doing this will delete all queues, all the retries, and the lists of processed, failed and dead jobs.


text:
Q: Cesaro mean of Cesaro means Is it possible to construct a bounded positive sequence $a_i$, ($0 < a_i < K < \infty$) such that the limit of its Cesaro mean does not exist but the limit of the Cesaro mean of its Cesaro means does exist?
That is a sequence $a_i$ s.t. :
$$ \nexists \lim_{n \to \infty} \frac{\sum_{i=1}^n a_i}{n} $$ but
$$ \exists \lim_{N \to \infty} \frac{\sum_{n=1}^N\frac{\sum_{i=1}^n a_i}{n}}{N} $$

A: Of course. Such a sequence can be constructed forcing
$$(-1)^n= \frac{1}{n}\sum_{k=1}^n a_k$$
so that you have $a_1=-1$, and $a_n = n(-1)^n - (a_1 + \dots +a_{n-1})$: this gives you a way to compute $\{ a_n \}_{n=1}^{\infty}$ recursively.
Obviously, if $\{ i_n \}_{n=1}^{\infty}$ is any sequence having no limit as $n \to \infty$, you can construct another sequence $\{ x_n \}_{n=1}^{\infty}$forcing
$$i_n= \frac{1}{n}\sum_{k=1}^n x_k$$
In particular, you can use your previously defined $\{ a_n \}_n$ to define another $\{ a_n' \}_n$, and then $\{ a_n'' \}_n$, and so on. This allows to construct sequences such that the Cesaro mean of the Cesaro mean of the Cesaro mean of ... etcetera does not exist.

A: Consider the sequence $a:=(a_{n})_{n\in\mathbb{N}_{\geq 1}}$ given by
$$a_{n} = \begin{cases}
\;\;1 &\text{ for } 2^{k}\leq n < 2^{k+1}, k \text{ even} \\
-1 &\text{ for } 2^{k}\leq n < 2^{k+1}, k \text{ odd.} \\
\end{cases}$$
(Hanul Jeon gave this as an example in: Bounded sequence with divergent Cesaro means) Define the Cesàro mean  $C(a):=(c_{n})_{n\in\mathbb{N}_{\geq 1}}$:
$$c_{n}:= \frac{1}{n}\sum_{k=1}^{n} a_{k} $$
Then via the geometric series we have
$$c_{2^{n}-1}=\frac{1}{2^{n}-1}\sum_{k=1}^{2^{n}-1} a_{k} = \frac{1}{2^{n}-1}\sum_{k=0}^{n-1} (-2)^{k}=\frac{(-2)^{n}-1}{(-3)\cdot(2^{n}-1)}.$$
As noted in the previous post, this is a divergent subsequence of C(a) and thus, the Cesàro mean diverges also. I would suspect that the Cesàro mean of the Cesàro mean $C^{2}(a)$ converges to zero (since $C(a)$ "oscillates smoothly" between $\frac{1}{3}$ and $-\frac{1}{3}$), but I might be wrong and I don't have time for a proof right now. Maybe you can try yourself. I'd be interested!
EDIT: The requirement that the sequence be positive is unnecessary because if it's bounded by $K$ you can always just add $K$ to every member of the sequence and the Cesàro mean of $a$ will be $C(a)+K$. But still, it remains to be proved that for the above sequence $C^{2}(a)\to 0$.

A: It is not possible. See lemme 1 of this paper, for example.
https://www.cambridge.org/core/services/aop-cambridge-core/content/view/CBA14D5A57E031A20E90BD2537BAD498/S0008414X00024378a.pdf/examples_for_the_theory_of_infinite_iteration_of_summability_methods.pdf


text:
Q: R markdown: Error in FUN(X[[i]], …): cannot coerce type 'symbol' to vector of type 'double' Even though I can run my code without a problem, when I was trying to knit the markdown file into HTML, these two simple lines of code give me this error:

R markdown: Error in FUN(X[[i]], …): cannot coerce type 'symbol' to vector of type 'double' Calls:  ... WithVisible -> eval -> eval -> data.frame -> apply Execution halted

sapply(data, levels)
numdata <- data.frame(lapply(data, as.numeric))

Does anyone know why it happens and how to solve it? I would be very grateful for your help

A: Thanks @Allan and @quickreaction. The data was given in a Rdata file. So when I opened it, it loads into my Global Environment. It doesn't satisfy the condition that "markdown document is a standalone self-referential code environment"
I solved it by including
write.csv(data,'data.csv')
data<-read.csv('data.csv')


text:
Q: Tensorflow android demo got error. Fail to connect to camera service I tried to run Tensorflow demo for android.
(https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android)
my phone is 22 API level.
I run the demo followed by the instruction. I got fail to connect to camera service error.
I am new to android. How to solve this problem? Give me any clue to solve it.
This error i get
12 - 20 16: 29: 20.150 7901 - 7901 / org.tensorflow.demo E / AndroidRuntime: FATAL EXCEPTION: main
Process: org.tensorflow.demo, PID: 7901
java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera. < init > (Camera.java: 497)
at android.hardware.Camera.open(Camera.java: 342)
at org.tensorflow.demo.LegacyCameraConnectionFragment$1.onSurfaceTextureAvailable(LegacyCameraConnectionFragment.java: 80)
at android.view.TextureView.getHardwareLayer(TextureView.java: 370)
at android.view.View.updateDisplayListIfDirty(View.java: 14144)
at android.view.View.getDisplayList(View.java: 14189)
at android.view.View.draw(View.java: 14959)
at android.view.ViewGroup.drawChild(ViewGroup.java: 3405)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java: 3198)
at android.view.View.updateDisplayListIfDirty(View.java: 14162)
at android.view.View.getDisplayList(View.java: 14189)
at android.view.View.draw(View.java: 14959)
at android.view.ViewGroup.drawChild(ViewGroup.java: 3405)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java: 3198)
at android.view.View.draw(View.java: 15234)
at android.widget.FrameLayout.draw(FrameLayout.java: 598)
at android.view.View.updateDisplayListIfDirty(View.java: 14167)
at android.view.View.getDisplayList(View.java: 14189)
at android.view.View.draw(View.java: 14959)
at android.view.ViewGroup.drawChild(ViewGroup.java: 3405)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java: 3198)
at android.view.View.updateDisplayListIfDirty(View.java: 14162)
at android.view.View.getDisplayList(View.java: 14189)
at android.view.View.draw(View.java: 14959)
at android.view.ViewGroup.drawChild(ViewGroup.java: 3405)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java: 3198)
at android.view.View.updateDisplayListIfDirty(View.java: 14162)
at android.view.View.getDisplayList(View.java: 14189)
at android.view.View.draw(View.java: 14959)
at android.view.ViewGroup.drawChild(ViewGroup.java: 3405)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java: 3198)
at android.view.View.draw(View.java: 15234)
at android.widget.FrameLayout.draw(FrameLayout.java: 598)
at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java: 2650)
at android.view.View.updateDisplayListIfDirty(View.java: 14167)
at android.view.View.getDisplayList(View.java: 14189)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java: 273)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java: 279)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java: 318)
at android.view.ViewRootImpl.draw(ViewRootImpl.java: 2530)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java: 2352)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java: 1982)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java: 1061)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java: 5885)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java: 767)
at android.view.Choreographer.doCallbacks(Choreographer.java: 580)
at android.view.Choreographer.doFrame(Choreographer.java: 550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java: 753)
at android.os.Handler.handleCallback(Handler.java: 739)
at android.os.Handler.dispatchMessage(Handler.java: 95)
at android.os.Looper.loop(Looper.java: 135)
at android.app.ActivityThread.main(ActivityThread.java: 5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java: 372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 698)

A: You might need to request the permission at runtime. See docs for more information on this topic. Requesting runtime permissions is required when targeting Android 6.0 or later.


text:
Q: Regex Capture first slug in the URL don't capture if it have more that one slug/path I want to capture the first slug in the URL only if the URL has one slug, and ignore if it has more than one slug or section in the URL. For example:
https://example.com/path/some-slug-with-numbers-int ✅

example.com/path/some-slug-with-numbers-int/ ✅

example.com/path/some-slug-with-numbers-int/external/slug ❌ // ignore and don't capture

Trailing slash and no HTTP protocol is allowed.
My regex: https://regex101.com/r/0JYHMM/1/

preg_match('/example\.com\/path\/(.*?)(\/|$)(?!\w)/', $input, $match);

if (!empty($match)) {
    $slug = $match[1];
    // $slug == 'some-slug-with-numbers-int'
}

It should capture the first and second URLs I posted, but my regex captures all  of them.

A: Capture everything that doesn't include a slash, and allow it only to have an optional trailing slash before the end of the string.
Regex
/example\.com\/path\/([^\/]+)\/?$/

https://regex101.com/r/K75aDD/1

Edit: As user3783243 mentioned, it's generally easier to use a different delimiter for your regex if it's related to paths with lots of slashes, so you don't have to escape them all. Convention is often to use a hash # or tilde ~ in these situations.
#example\.com/path/([^/]+)/?$#


text:
Q: script for root `PATH` changes and reflect it permanently across reboots I have a script which does some basic root PATH integrity check and inputs a line in ~/.bash_profile to source my script, so that changes my script made in root's PATH is permanent across restarts:
cat path_clean
#!/bin/bash

OLD_PATH=`echo $PATH`

OIFS=$IFS
IFS=:
for path in ${OLD_PATH}; do
    [ -d "${path}" ] || continue
    paths=( "${paths[@]}" "${path}" )
done

while read -r stat owner path; do
    [ "${owner}${stat:5:1}${stat:8:1}" = 'root--' ] || continue
    newpath="${newpath}:${path}"
done < <(stat -c "%A:%U:%n" "${paths[@]}" 2>/dev/null)

IFS=${OIFS}

NEW_PATH=${newpath#:}
export PATH=${NEW_PATH}
egrep "^[ ]*if.*fi;" ~/.bash_profile &> /dev/null
if [ $? -ne 0 ];
then
   echo 'if [ -f /root/path_clean ]; then source /root/path_clean; fi;' >>     ~/.bash_profile
fi

Everything runs as expected when I run the script first time like this:
./path_clean
. ~/.bash_profile

But the script has one issue. If I do . ~/.bash_profile multiple times, then I see the value in PATH variable repeating itself every time.
For example before execution of script my PATH is:
[root@labeir1 ~]# echo $PATH
    /usr/bin/X11:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin

Now after running . ~/.bash_profile first time, all is ok:
[root@labeir1 ~]# ./path_clean
[root@labeir1 ~]# echo $PATH <--still same as original `PATH`, which is ok
   /usr/bin/X11:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/root/bin
[root@labeir1 ~]# . ~/.bash_profile <--now sourcing `.bash_profile`1st time
[root@labeir1 ~]# echo $PATH <--my script has changed `PATH` fine.
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin
[root@labeir1 ~]# . ~/.bash_profile
[root@labeir1 ~]# echo $PATH <-- problem starts
    /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin
[root@labeir1 ~]# . ~/.bash_profile
[root@labeir1 ~]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ulticom/diameter/bin:/apps/omni/bin

Please suggest what changes to make in the script in order to make it work fine and eradicate this problem.

A: My guess is that you need to clear newpath before using it. Otherwise, it will hold the value left by the last source command.


text:
Q: React Native: Get position updates for every one second At the moment, I have this current code, which works but not most of the time. I sometimes get delays and does not update at all. I am aiming to get a real time position updates. The way I have done it is by having setInterval() function, and I have used inside componentDidMount().
I have tried to have navigator.geolocation.watchPosition but didn't work. Maybe I am using it in the wrong way.
componentDidMount() {
      this.state.interval = setInterval(() => {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            console.log("Pos: "+position.coords.speed);
            this.setState({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              speed: position.coords.speed,
              error: null,
            });
          },
          (error) => this.setState({ error: error.message }),
          { enableHighAccuracy: true, maximumAge: 0},
          );
      },1000);
    }

A: I solved it by updating state at every x second:
import { Platform, View, StyleSheet, Text } from 'react-native';
import Constants from 'expo-constants';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';

export default class App extends Component {

  state = {
    location: null,
    errorMessage: null,
  };

    _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      this.setState({
        errorMessage: 'Permission to access location was denied',
      });
    }

    let location = await Location.getCurrentPositionAsync({});

    this.setState({ location });
};

  componentDidMount() {
    if (Platform.OS === 'android' && !Constants.isDevice) {
      this.setState({
        errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!',
      });
    } else {
      setInterval(this._getLocationAsync.bind(this),2000);
    }
  }

  render () {
    let text = 'Waiting..';
    if (this.state.errorMessage) {
      text = this.state.errorMessage;
    } else if (this.state.location) {
      text = JSON.stringify(this.state.location);
    }

     return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>{text}</Text>
      </View>
    );
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    textAlign: 'center',
  },
});


text:
Q: How do you print/output returned Raw text from a React Module function(Get Call Log)? I'm creating a react native android application to access and print out an android phone/tablet's call logs in a sectionlist for the day/date (eg. Yesterday; 26/07/17; 25/07/17 etc);but I am stuck at the actual printing out of the string of call logs in the react class - when invoking the method from the module. Apparently react methods can only "return" void.
I tried to use promises but got stuck with async and await. I can't use npm 5(node which has async and await) because I created a project using "react native init" for the physical device testing; and npm is not supported/stable(shown on terminal). I used "sudo npm install -g npm@latest-4" so I could use init .
I tried installing async and await manually using "npm install async --save" and "npm install asyncawait". When I ran later it made no difference.
I really just want to output the call details as a sectionlist on the screen of my physical android device.
I've tried google; but maybe my keywords were not good enough; so I got little help. It would also be nice if you could give me an indication of whether a .xml file is needed and if so; how it would look. I've posted my code for the java native module method and the Class where I import the module from a helper .js class. I apologise for the commented code; I tried many methods to print.
The latest error I was getting; when I could actually toast the ' tag' was "undefined is not an object (evaluating 'n.data.length')". This after resolving "expected a component class got object" and "undefined is not a function".
React js class below:
import React, { Component } from 'react';
import { NativeModules, AppRegistry, SectionList, StyleSheet, Text, View, WebView } from 'react-native';
import { StackNavigator, } from 'react-navigation';
import CallLogAndroid from './RctActivity';

export default class SectionListBasics extends Component {
static navigationOptions = { title: 'Your Call Logs', };
//  CallLog = () =>{
//     const Cllog= CallLogAndroid.getCallDetails();
//     console.log(Cllog+"");
//     return Cllog+"";
// };

// async function getCallLog() {
//     try {
//       var CallDetails = await CallLogAndroid.getCallDetails(100, 100);
//       console.log(CallDetails);
//       return CallDetails;
//     }
//     catch (e) {
//       console.error(e);
//     }
// }
componentWillMount() {
   const log = CallLogAndroid.getCallDetails().then(function(value) {
    console.log(value); // "Success"
  }, function(value) {
    // not called
  });
}
render() {

// const divStyle = {
//   WebkitTransition: 'all', // note the capital 'W' here
//   msTransition: 'all' // 'ms' is the only lowercase vendor prefix
// };

// var thenProm = resolvedProm.then(function(value){
//   console.log("this gets called after the end of the main stack. the value received and returned is: " + value);
//   return value;
// });
console.log(this.log+"");
//getCallLog();
return (
  <View style={styles.container}>
     <SectionList
      sections={[
        {title: 'Today', data: [ 'pete'{/*this.log*/}] },
        {/* <WebView source={{html: CallLogAndroid.getCallDetails()}} /> */},
        {title: 'Yesterday', data: ['Jackson']},
        {title: 'Date: 1', data: ['water']},
        {title: 'Date: 2', data: ['dance']},
        {title: 'Date: 3', data: ['rain']},
        {title: 'Date: 4', data: ['Mum']},
        {title: 'Date: 5', data: ['Dad']},
      ]}
      renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
      renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
    />
    {/* <Text>
    console.log(CallLogAndroid.getCallDetails().toString());

    </Text> */}
  </View>
 );
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22
},
sectionHeader: {
paddingTop: 2,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 2,
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'rgba(247,247,247,1.0)',
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})

// skip this line if using Create React Native App
//AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics);

Here is the java class:
package com.workingapp;

import android.widget.Toast;

//to create react bridge
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.bridge.Promise;

//android tools imports
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.database.Cursor;   //import cursor to parse call logs
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.os.Bundle;
import android.text.Html;   //import html to  make *online query to content provider
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import android.widget.ImageView;
import android.view.Gravity;   //import gravity to centre layout
import android.view.ViewGroup;
import android.view.LayoutInflater;

import java.util.Map;
import java.net.*;  //import uri - a Uniform Resource Identifier (URI) is a string of characters used to identify a resource. Such identification enables interaction with representations of the resource over a network
import java.util.Date;
import android.widget.TextView;
import java.util.HashMap;

//Customised versions of loader imported
import android.support.v4.app.FragmentActivity;
//import android.support.v4.app.LoaderManager;
//import android.support.v4.content.Loader;

//Specific imports for inflator in toast
import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class CallLogModule extends ReactContextBaseJavaModule implements LoaderManager.LoaderCallbacks<Cursor>{
    public static final String REACT_CLASS = "CallLogAndroid";
    private static final String E_LAYOUT_ERROR = "E_LAYOUT_ERROR";
    ReactApplicationContext reactContext;
    private static HashMap<String, String> rowDataCall;
    private static final String TAG = "CallLog";
    private static final int URL_LOADER = 1;

    private static TextView callLogsTextView;

    // @Override
    // public void onCreate(Bundle savedInstanceState) {
    //     super.onCreate(savedInstanceState);
    //     Log.d(TAG, "onCreate()");

    //     setContentView(R.layout.main);
    //     initialize();
    // }

    /**Constructor */
    public CallLogModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext= reactContext;
        //(Activity)reactContext.setContentView(R.layout.module_layout);
    }

    /**Loads all calls */
    @Override
    @ReactMethod
    public Loader onCreateLoader(int loaderID, Bundle args) {

    Log.d(TAG, "onCreateLoader() >> loaderID : " + loaderID);

    switch (loaderID) {
        case URL_LOADER:
        // Returns a new CursorLoader
        return new CursorLoader(
        reactContext,   // Parent activity context
        CallLog.Calls.CONTENT_URI,        // Table to query
        null,     // Projection to return
        null,            // No selection clause
        null,            // No selection arguments
        null             // Default sort order
        );

        default:
        return null;
        }
    }

    /**On completing load, return/output formatted string*/
    @Override
    @ReactMethod
    public void onLoadFinished(Loader loader, Cursor managedCursor) {
        Log.d(TAG, "onLoadFinished()");

        StringBuilder sb = new StringBuilder();

        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);

        sb.append("
Call Log Details
");
        sb.append("\n");
        sb.append("\n");

        sb.append("
");

        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            //Date callDayTime = new Date(Long.valueOf(callDate));
            Date callDayTime= null;
            if( (!callDate.trim().equals("") ) && (callDate != null)) {
                callDayTime = new Date(Long.valueOf(callDate));  //if value of long is null
            }
            String callDuration = managedCursor.getString(duration);
            String dir = null;

            int callTypeCode = Integer.parseInt(callType);
            switch (callTypeCode) {
                case CallLog.Calls.OUTGOING_TYPE:
                    dir = "Outgoing";
                    break;

                case CallLog.Calls.INCOMING_TYPE:
                    dir = "Incoming";
                    break;

                case CallLog.Calls.MISSED_TYPE:
                    dir = "Missed";
                    break;
            }

            sb.append("
")
                    .append("Phone Number: 	")
                    .append("")
                    .append(phNumber)
                    .append("	");
            sb.append("
");
            sb.append("
");
            sb.append("
")
                    .append("Call Type:	")
                    .append("")
                    .append(dir)
                    .append("	");
            sb.append("
");
            sb.append("
");
            sb.append("
")
                    .append("Date & Time:	")
                    .append("")
                    .append(callDayTime)
                    .append("	");
            sb.append("
");
            sb.append("
");
            sb.append("
")
                    .append("Call Duration (Seconds):	")
                    .append("")
                    .append(callDuration)
                    .append("	");
            sb.append("
");
            sb.append("
");
            sb.append("
");
        }
        sb.append("
");

        managedCursor.close();

        callLogsTextView.setText(Html.fromHtml(sb.toString()),TextView.BufferType.SPANNABLE);
    }

    @Override
    @ReactMethod
    public void onLoaderReset(Loader<Cursor> loader) {
        Log.d(TAG, "onLoaderReset()");
        // do nothing
    }

    /**Method to obtain name of the class */
    @Override
    public String getName() {
        return REACT_CLASS;
    }

    /**Method to get entire call log */
    // @ReactMethod
    // public void getCallLog(String phone,int duration) {
    //     //Checking if permission was denied
    //     if (ActivityCompat.checkSelfPermission(getCurrentActivity(), Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED){
    //         ActivityCompat.requestPermissions(getCurrentActivity(), new String[]{Manifest.permission.READ_CALL_LOG}, 101);
    //     }

    //     //uses a cursor to get all calls
    //    else{
    //         Uri allCalls = Uri.parse("content://call_log/calls");
    //         Cursor c = managedQuery(allCalls, null, null, null, null);

    //         //separates calls according to number; name; duration and Call type
    //         String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for  number
    //         String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
    //         String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
    //         int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out-going.

    //         //Print calls in a certain format

    //     }
    // }

    /**Method to get full list of call logs */
    @ReactMethod
    private void getCallDetails(Promise promise) {

            try{

            StringBuffer sb = new StringBuffer();
            Uri contacts = CallLog.Calls.CONTENT_URI;
            Cursor managedCursor = (reactContext.getCurrentActivity()).getContentResolver().query(contacts, null, null, null, null);
            int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
            int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
            int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
            int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
            //sb.append("Call Details :");

            sb.append("
Call Log Details
");  //tried to print out with react syntax contrary to code commented below
            sb.append("\n");
            sb.append("\n");

            sb.append("
");

            while (managedCursor.moveToNext()) {

                rowDataCall = new HashMap<String, String>();

                String phNumber = managedCursor.getString(number);
                String callType = managedCursor.getString(type);
                String callDate = managedCursor.getString(date);
                String callDayTime = new Date(Long.valueOf(callDate)).toString();
                // long timestamp = convertDateToTimestamp(callDayTime);
                String callDuration = managedCursor.getString(duration);
                String dir = null;
                int dircode = Integer.parseInt(callType);
                switch (dircode) {
                case CallLog.Calls.OUTGOING_TYPE:
                    dir = "OUTGOING";
                    break;

                case CallLog.Calls.INCOMING_TYPE:
                    dir = "INCOMING";
                    break;

                case CallLog.Calls.MISSED_TYPE:
                    dir = "MISSED";
                    break;
                }
                // sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
                // sb.append("\n----------------------------------");

                sb.append("
")
                        .append("Phone Number: 	")
                        .append("")
                        .append(phNumber)
                        .append("	");
                sb.append("
");
                sb.append("
");
                sb.append("
")
                        .append("Call Type:	")
                        .append("")
                        .append(dir)
                        .append("	");
                sb.append("
");
                sb.append("
");
                sb.append("
")
                        .append("Date & Time:	")
                        .append("")
                        .append(callDayTime)
                        .append("	");
                sb.append("
");
                sb.append("
");
                sb.append("
")
                        .append("Call Duration (Seconds):	")
                        .append("")
                        .append(callDuration)
                        .append("	");
                sb.append("
");
                sb.append("
");
                sb.append("
");
            }
            sb.append("
");

            managedCursor.close();
            String clLog=sb.toString();

            promise.resolve(clLog);
            }

            catch (IllegalViewOperationException e) { promise.reject(E_LAYOUT_ERROR, e); }
            //System.out.println(sb.toString());
            // callLogsTextView.setText(Html.fromHtml(sb.toString()));
            // WebView webview = new WebView(reactContext.getCurrentActivity());
            // webview.loadData(sb.toString(), "text/html", "utf-8");
            //Toast.makeText(reactContext, sb.toString(), Toast.LENGTH_LONG).show();

//            LayoutInflater inflater = reactContext.getCurrentActivity().getLayoutInflater();
//            View layout = inflater.inflate(R.layout.module_layout,
//                    (ViewGroup) reactContext.getCurrentActivity().findViewById(R.id.custom_toast_container));
//
//            ImageView image = (ImageView) layout.findViewById(R.id.image);
//            image.setImageResource(R.drawable.android);
//            TextView text = (TextView) layout.findViewById(R.id.text);
//            text.setText(sb.toString());
//
//            Toast toast = new Toast(reactContext.getCurrentActivity());
//            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
//            toast.setDuration(Toast.LENGTH_LONG);
//            toast.setView(layout);
//            toast.show();
    }
}

A: I figured it out. I was mixing up promises and callback code.
I used promises again and it worked.
const log = CallLogAndroid.getCallDetails().then(function(value) {
    console.log(value);
".then(function(..." is used to resolve a call back. It was not supposed to be added and an async function had to be used. With promises; just calling the function should return the data.


text:
Q: How the behavior is when assign an array to a scalar in perl? My code is
my $r = ['111','222','aaa','bbb'];
print $r;
my $s = ('111','222','aaa','bbb');
print $s;

The first print I can understand, $r would be a ref and print gives me something like "ARRAY(0x44444444)".
But I can not understand why the second example, print $s gives me the last element, bbb, why ?

A: The function of the comma operator , depends on the context. There is list context and scalar context to consider.
In list context, the comma operator separates items in a list. An assignment imposes list context on the right hand side if the left side is an array or is enclosed in parens:
my ($s) = (1, 2, 3);  #=> $s = 1, rest discarded
(my $s) = (1, 2, 3);  # the same
my @arr = (1, 2, 3);  #=> @arr = (1, 2, 3)

In scalar context Perl expects us to provide a single value. The comma operator then works just like in C or other languages: all expressions are evaluated and their value discarded. Only the last value is kept:
my $s = (1, 2, 3);  #=> $s = 3, previous items discarded

See also: the Comma Operator in perldoc perlop
Note that the parens (...) do not create an array. They are only used to control precedence. In $s = (1, 2, 3) the arrays are needed because $s = 1, 2, 3 would be parsed as ($s = 1), 2, 3.


text:
Q: How to enable session and set session timeout in Spring Security I am new to Spring Security and I am working on a login, logout, and session timeout feature. I have configured my code by referring to this document. My code looks below:
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/admin/**")
        .access("hasRole('ROLE_USER')").and().formLogin()
        .loginPage("/login").failureUrl("/login?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .and().logout().logoutSuccessUrl("/login?logout").and().csrf();
    http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired");
}

Override the class AbstractSecurityWebApplicationInitializer
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    @Override
    public boolean enableHttpSessionEventPublisher() {
        return true;
    }

}

I need clarification on whether I am doing it right, if it looks good, then where I need to setup the session timeout. I am doing it fully based on annotation.

A: Different ways to configure session timeout time(maxInactiveInterval) in spring security.
 1. By addinng session config in web.xml(from raju vaishnav's answer)
 2. By creating implementation of HttpSessionListener and adding it to servlet context.(from munilvc's answer)
3. By registering your custom AuthenticationSuccessHandler in spring security configuration, and setting session maximum inactive interval in onAuthenticationSuccess method.
This implementation has advantages

*

*On login success, You can set different value of maxInactiveInterval for different roles/users.

*On login success, you can set user object in session, hence user object can be accessed in any controller from session.
Disadvantage: You can not set session timeout for ANONYMOUS user(Un-authenticated user)
Create AuthenticationSuccessHandler Handler
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException
    {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (roles.contains("ROLE_ADMIN"))
        {
            request.getSession(false).setMaxInactiveInterval(60);
        }
        else
        {
            request.getSession(false).setMaxInactiveInterval(120);
        }
        //Your login success url goes here, currently login success url="/"
        response.sendRedirect(request.getContextPath());
    }
}

Register success handler
In Java Config way
@Override
protected void configure(final HttpSecurity http) throws Exception
{
    http
        .authorizeRequests()
            .antMatchers("/resources/**", "/login"").permitAll()
            .antMatchers("/app/admin/*").hasRole("ADMIN")
            .antMatchers("/app/user/*", "/").hasAnyRole("ADMIN", "USER")
        .and().exceptionHandling().accessDeniedPage("/403")
        .and().formLogin()
            .loginPage("/login").usernameParameter("userName")
            .passwordParameter("password")
            .successHandler(new MyAuthenticationSuccessHandler())
            .failureUrl("/login?error=true")
        .and().logout()
            .logoutSuccessHandler(new CustomLogoutSuccessHandler())
            .invalidateHttpSession(true)
        .and().csrf().disable();

    http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired=true");
}

In xml config way
<http auto-config="true" use-expressions="true" create-session="ifRequired">
    <csrf disabled="true"/>

    <intercept-url pattern="/resources/**" access="permitAll" />
    <intercept-url pattern="/login" access="permitAll" />

    <intercept-url pattern="/app/admin/*" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />
    <intercept-url pattern="/app/user/*" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />

    <access-denied-handler error-page="/403" />

    <form-login
        login-page="/login"
        authentication-success-handler-ref="authenticationSuccessHandler"
        authentication-failure-url="/login?error=true"
        username-parameter="userName"
        password-parameter="password" />

    <logout invalidate-session="false" success-handler-ref="customLogoutSuccessHandler"/>

    <session-management invalid-session-url="/login?expired=true">
        <concurrency-control max-sessions="1" />
    </session-management>
 </http>

 <beans:bean id="authenticationSuccessHandler" class="com.pvn.mvctiles.configuration.MyAuthenticationSuccessHandler" />

Working code is available in my github repository
Working code is available in two forms
1. XML config way of implementation
2. JAVA config way of implementation
If you want to have automatic logout feature and timer which displays when session is about to expire, if user is filling form but not submitted then user can extend session by clicking on keep session alive button.
If you want to implement auto logout refer stack overflow answer on auto logout on session timeout. Hope this will help.

A: In your application properties use
server.servlet.session.timeout=1m (If a duration suffix is not specified, seconds will be used.)
By default it is 30 minutes.

A: If you are using JavaConfig and do not want to use XML you can create a HttpSessionListener and use getSession().setMaxInactiveInterval(), then in the Initializer add the listener in onStartup():
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("session created");
        event.getSession().setMaxInactiveInterval(15);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
       System.out.println("session destroyed");
    }
}

Then in the Initializer:
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    servletContext.addListener(new SessionListener());
}

A: I was able to solve above issue by adding below config in web.xml only. any better way will be accepted.
 <session-config>
    <session-timeout>20</session-timeout>
</session-config>

A: When using application.properties set property server.session.timeout= value is in seconds.

A: I handled it inside subclass of UsernamePasswordAuthenticationFilter
You can get username by -
obtainUsername(request);

and apply user checks and set time out accordingly, like-
if(username.equalsIgnoreCase("komal-singh-sisodiya@xyz.com"))
        {
        logger.debug("setting timeout 15 min");
        request.getSession(false).setMaxInactiveInterval(15*60);
        }

A: Add the below in application.proprites
server.servlet.session.timeout=

A: this will work:
@EnableJdbcHttpSession(maxInactiveIntervalInSeconds = 84600)


text:
Q: angular 2 show floating div where row clicked I am not looking for expandable row as explained at link Expandable table rows in angular 4 with angular material
All I need is to show a small floating div where i clicked the mouse. (selected a row). I have a sample ready for highlighting selected row and the floating div that right now shows below the table.  Select row show div, select gain hide div. Please help to show where mouse clicked/row selected. Code is at link
https://stackblitz.com/edit/div-on-click

A: I know on this question you mention you are not wanting expandable row... I will go ahead and post the stack blitz example here for your review using expandable row, this uses expandable row which is not what you want but it was created in response to your previous question which was closed as duplicate before I could post it... I just wanted to post here for your review to demonstrate how expandable rows work in your stackblitz example... After review, if this will not meet your requirements please let me know and I will remove.
https://stackblitz.com/edit/div-on-click-qqcdmx?embed=1&file=app/table-basic-example.html
Also, here is stackblitz example of right click context menu in mat-table for your review as well.
https://stackblitz.com/edit/angular-material-context-menu-table?file=app/context-menu-example.html


text:
Q: SSL certificate does not exist or is empty - WAMP When I run httpd -t I'm getting the error that my certificates don't exist - "does not exist or is empty". I've purchased the certificate and they are all setup correctly and I've checked the permissions with another server where it's fine which for both the folder and file are fine. The paths are definitely correct and the files are definitely not empty. I've rebooted the server and I still get the same error. I'm using ** WAMP ** if it makes a difference and help would be great. The question is why can WAMP not find my certificates? I am going to try upgrading to 2.5 (currently running WAMP 2.2) and see if that fixes it.
Unfortunately the latest WAMP still gives the same error.

A: Simple reason this was failing - extensions were turned off on the server so my files were actually certificate.crt.txt!! Hope that helps anyone else who has this issue.

A: Make sure that SELINUX is set as permissive or disabled.
setenforce 0


text:
Q: Does saying "Keep it up" put me in an authoritative position? As a way of congratulating someone on starting a new project, I recently said "Keep it up". The other person said that "keep it up" isn't a phrase one would use outside of work and is mostly used by someone with authority - particularly to show approval.
How does it sound to you - would you say it puts the person saying it as someone with higher authority or not?
Thanks.

A: I share the perspective of the person who gave you that advice. Care should be taken with this expression
I would expect to hear this only from someone with a vested interest in the activity, and who was explicitly in a position to tell me, or invite me to, continue it. Someone who controlled, or at least shared, the decision as to whether I would continue.
If I was providing a service to someone, say pouring them a drink, and I paused to see if they'd had enough, they might say "yes, please, keep it up". Tone of voice would be important; the wrong tone could turn a friendly gesture into an on-demand service.
If the activity in question was entirely my own, say a hobby, or a chore, and someone with no interest in the work said that to me, I'd wonder where that was coming from. Like they think they have a right to order me back to my own work? A better choice would be something like "I don't want to bother you, I'll let you get back to it." You can certainly admire the work they've already done, and you can bolster their perseverance with phrases like "you got this! you can do this!", but "keep it up" crosses the line into directly telling them they must continue, so you should ask yourself, am I in that role.
.

A: To be honest, nobody really minds this kind of vague congratulatory message.  Few people are going to analyse or dissect the grammar or meaning.
However "Keep it up" really means "continue to do as you have been doing, in the face of adversity".  That makes it a strange message to give to someone starting a new project.
It can certainly be used out of a work context, But it does suggest some kind of slightly paternal relationship.  The fact that it is an imperative gives it a slight flavour of superiority. It implies "I have judged your previous efforts to be good and I am instructing you to continue in the same manner", which prompts the question "What gave you the right to judge the previous efforts?"
In such contexts, I usually just go for "good luck" or "best wishes".  These are safe, boring and anodyne. s I said, nobody really analyzes these messages.

A: In my own experience, I use "keep it up" as a short version of "keep up the good work", and I use this not as someone with vested interest, some authority, or anything other than encouragement for the target person to keep doing good work.
It doesn't matter if this is something they are doing at work, for themselves, for their partner/spouse/kids, or whatever, just as long as they enjoy it and are getting what they want from it. They could simply be getting close to paying off a loan and be expressing excitement about how they'll be out from under that debt and stress. Maybe they are boasting about how long they've been without a drink or a smoke.
I'm definitely not stating it as an authoritative demand, but rather as encouragement.
Yes, there are times when a boss/supervisor might say "keep it up" in reference to working towards a goal, a pay raise, a promotion, or something, but that doesn't mean it always has to be used that way.
And yes, there are negative connotations, like David Siegel's answer mentions: "Keep it up, if you want a black eye."

A: "Keep it up" can be used by a boss or other authority figure.  It can also be used in other contexts. It is commonly used by sports fans to or about an athlete after a successful performance. It can be used by peers in a school, work, or sports context to encourage someone. I have had it said to me by a bridge partner after a successful play.
I recall being at a minor league baseball game where home runs were followed by a chant "Keep it up {person}, Keep it up" ({person} being replaced by the hitter's name.)
It can also be used in a negative or threatening sense.

*

*Parent to child: "Keep it up and you'll be in trouble."

*Mobster to informer: "Keep it up and you won't be around long."

A: Rather than "authority", as in "higher position in the workplace hierarchy", I would say the phrases suggests status more subtly. For instance, in your example, saying "keep it up!" suggests that you're in a position to both see for the other person that continued effort is good for them and maybe others, as well as to potentially affirm the other person (as if, for instance, they weren't sure if they should continue). It also suggests a bit of distance -- "keep it up" suggests that the responsibility for that effort rests on the target, not on the speaker. It's a little more encouraging than "you keep doing that!", but it does sort of disinvolve the speaker. For instance, a parent might say that to their child if the child was getting good grades, both exerting authority by telling the child to continue behaving, but also expressing relief from needing to intervene. A boss in the workplace might say these things for the same reasons: they see how their workplace is structured in a way that is privileged compared to the listener, they and others benefit from the effort, and they feel no need to be involved in making that effort the way that the listener is, and they of course may have to genuinely affirm their workers to keep them working.
In a peer conversational setting though, you might say this if your friend was working on a project that you could see was good for them, and that you maybe either have no interest or experience in. It still expresses that the speaker (you) is an outside party with information that is applicable to their situation, even if that information is literally just that the project is a good idea. So "keep it up" definitely isn't necessarily a serious power-move by any means, but it may convey a very slightly elevated status and distance. Many people associate such distance with a workplace dynamic, where workers often have the opportunity to express approval for each others' efforts at distance. But it could be totally appropriate between friends, especially if you're talking about a personal accomplishment that isn't related to you.
I think your friend was maybe being a bit picky when they responded this way!


text:
Q: Setting the authentication forms loginUrl dynamic? I have a ASP.NET MVC site that uses forms authentication with custom AuthorizeAttribute on both actions and controller classes.
I have this in my web.config file :
<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

When the site is in "normal" mode this works fine. The users that needs to login is redirected to this page.
But when I switch to Test mode then all Contollers will be locked and also the AccountController.
I now need to shange the loginUrl when I'm in Test mode to point at a controller action that is not locked and that is special made for the test scenario.
How can I change the loginUrl or is it possible to redirect from the AuthorizeAttribute?

A: What we do is override with a customised Authorize attribute which redirects for the HandleUnauthorizedRequest function like so:
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
    {

        public string LoginController { get; set; }
        public string LoginAction { get; set; }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (string.IsNullOrEmpty(LoginController)&&string.IsNullOrEmpty(LoginAction))
                base.HandleUnauthorizedRequest(filterContext);
                    filterContext.Result =new RedirectToRouteResult(
                                            new RouteValueDictionary(new
                                                                         {
                                                                             controller = LoginController,
                                                                             action = LoginAction,
                                                                             returnUrl = HttpContext.Current.Request.Url
                                                                         }));
        }
    }

This way we can specify the login route for any authorize attribute by assigning the controller and action to go for. Otherwise it behaves like the standard authorize attribute.
You could change this to redirect according to being in test mode or live mode.


text:
Q: Android LinearLayout Spacing I am having problems writing a piece of code for android. I am using the eclipse development environment. What I am trying to accomplish is to have the days of the week evenly spaced out on the first row of a table (with six rows). I can not figure out how to make it so that the words actually spread out, and not just stick together in a group. (yes I have tried using weights). My code is as follows. I apologize in advance for any misspellings in the question or comments in the code.
package A3.cal;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TableLayout;
import android.widget.TableRow;

public class A3Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); //it works dont touch it...
    setContentView(R.layout.main); //old Content View
    MonthView(); //setup the initial view
}

public void MonthView(){
    TableRow[] tableRows = new TableRow[6]; //create table rows for the table
    LinearLayout[] dayHeaderFrames = new LinearLayout[7]; //create the frame layouts for the table headers
    TextView[] days = new TextView[7]; //create new text views array
    days = populateDays(0); //make the textviews say the proper days (this can be faster by manipulating the strings and then adding to textview)
    TableLayout monthView = (TableLayout) findViewById(R.id.monthView); //find month View in the xml file
    LinearLayout headerLayout = new LinearLayout(this); //create the linear layout that will hold the frame layouts for the text views**
    headerLayout.setBackgroundColor(Color.WHITE); //make the linear layouts white
    LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f); //create the layout perameters for childeren

    for(int i = 0; i < 6; i++){ //create the table rows
        tableRows[i] = new TableRow(this); //create the new rows
    }

    tableRows[0].addView(headerLayout); //add the header layout to the first row
    tableRows[0].setBackgroundColor(Color.RED); //set the background table row (only the first one which I am concentrating on) to red
    monthView.setBackgroundColor(Color.BLUE); // make the table blue

    for(int i = 0; i < 7; i++){ //add the headers to the month day header row
        dayHeaderFrames[i] = new LinearLayout(this); //create new frames
        headerLayout.addView(dayHeaderFrames[i], ll); //add the frames to the first row in the table
        dayHeaderFrames[i].addView(days[i]); //add the textview objects to the frames (the text view objects already have the correct text from when populate days was called)
    }

    for(int i = 0; i < 6; i++){ //add the rows to the month view
        monthView.addView(tableRows[i]); //add the new rows to the table
    }
}

public TextView[] populateDays(int startDay){
    TextView[] daysTextViewArr = new TextView[7]; //create a textview array
    String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; //days of the week

    for(int i = 0; i < 7; i++){ //put the days into the order based upon the start day
        daysTextViewArr[i] = new TextView(this); //create a new text view object

        //the following logic puts the days into order
        int day = i + startDay;
        if(day > 6){ //if the day will exceed the array put it back to the begining
            day = day - 7;
        }

        daysTextViewArr[i].setText(days[i]); //set the text in the text view to the propper day
    }

    return daysTextViewArr;
}

}

And the XML Layout in main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<TableLayout
    android:id="@+id/monthView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</TableLayout>

To recap The Code works except for spacing out the linear layouts/textviews
I want to thank you all in advance for helping me out on this (and so many other) issues.
Sincerely,
Reid

A: Solution is simple. You need to use android:stretchColumns attribute.
Translate following example to your code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TableLayout
android:id="@+id/monthView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="0,1,2,3,4,5">

</TableLayout>
</LinearLayout>

Java code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getView();
}

    public TextView[] populateDays(int startDay) {
    TextView[] daysTextViewArr = new TextView[7];
    String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday" };
    for (int i = 0; i < 7; i++) {
        daysTextViewArr[i] = new TextView(this);
        int day = i + startDay;
        if (day > 6) {
            day = day - 7;
        }
        daysTextViewArr[i].setText(days[i]);
    }

    return daysTextViewArr;
}

public void getView() {
    TableRow[] tableRows = new TableRow[6];

    TextView[] days = new TextView[7];
    days = populateDays(0);
    TableLayout monthView = (TableLayout) findViewById(R.id.monthView);
    LinearLayout headerLayout = new LinearLayout(this);
    headerLayout.setBackgroundColor(Color.WHITE);
    LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT, 1f); // create the

    for (int i = 0; i < 6; i++) {
        tableRows[i] = new TableRow(this);

    }
    for (int i = 0; i < 6; i++) {
        tableRows[0].addView(days[i]);
    }

    monthView.setBackgroundColor(Color.BLUE);

    for (int i = 0; i < 6; i++) {
        monthView.addView(tableRows[i]);
    }
}
}

A: do you want like this?
public TextView[] populateDays(int startDay) {

    ...

        for(int i = 0; i < 7; i++){
        ...
        daysTextViewArr[i] = new TextView(this);
        daysTextViewArr[i].setPadding(10, 0, 5, 0);
        ...
        }

    ...


text:
Q: Send broadcast intent from PreferenceScreen? Is it possible to directly send a broadcast intent from a PreferenceScreen?
For example, I would like to do something like the following:
<PreferenceScreen android:title="Enable">
<intent android:action="com.otherapp.ENABLE" />
</PreferenceScreen>

But when I try this, the app FC's w/ ActivityNotFoundException.
BTW, the receiver is simply defined as:
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="com.otherapp.ENABLE" />
</intent-filter>
</receiver>

This broadcast receiver has been tested to work ok, but just not from the PreferenceScreen.
TIA!

A: You can extend Preference to make it send a broadcast when clicked:
public class BroadcastPreference extends Preference implements Preference.OnPreferenceClickListener {
    public BroadcastPreference(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.setOnPreferenceClickListener(this);
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        getContext().sendBroadcast(getIntent());
        return true;
    }
}

Then use your custom preference in the xml file
<com.app.example.BroadcastPreference android:title="Enable">
    <intent android:action="com.otherapp.ENABLE" />
</com.app.example.BroadcastPreference>

A: Preferences send intents to activities, not to broadcast receivers. If you want to send intents to broadcast receivers, create activity that forwards intents to broadcast receivers
public class ForwardingActivity extends Activity {
    @Override
    protected void onStart() {
        super.onStart();
        Intent incomingIntent = getIntent();
        Intent outgoingIntent = new Intent(incomingIntent);
        outgoingIntent.setComponent(null); // unblock recipients
        sendBroadcast(outgoingIntent);
    }
}

with no UI
    <activity
        android:name=".ForwardingActivity "
        android:theme="@android:style/Theme.NoDisplay" >
        <intent-filter>
            <action android:name="com.otherapp.ENABLE" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

A: I think, you should add category android.intent.category.DEFAULT to intent-filter in your manifest.
It should look like this:
<receiver android:name=".Receiver">
    <intent-filter>
        <action android:name="com.otherapp.ENABLE" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>


text:
Q: Visual Studio Error List code URL I created a MSBuild task that reports errors and warnings that correctly get displayed in Visual Studio's Error List window. The strings in the Codes columns are clickable, and when I click on a C# compiler code, like CS0246, I get taken to a bing search for that code. However, when I click on my own code, say ZIV0001, I just get sent to a MSDN url, which redirects to the Visual Studio documentation page on learn.microsoft.com.
How can I make clicks on my error codes go to a web search or a custom URL?