text:
Q: Forcing InProgress state machines to always resolve I am trying to model executions of concurrent AWS Lambda functions to look for bugs around timing. In my model, once a Lambda is triggered, it should always end up in either a Complete or Failed state.  The problem is, I can't figure out how to tell Alloy to throw out any state sequence where Lambdas are still InProgress in the final state.
Here is what I have.  In the actual model, there would be side effects of the state transitions which I would want to make assertions about. Basically "once every lambda is complete or failed, X should be impossible".
abstract sig State {}
sig InProgress, Complete, Failed extends State {}

var sig Lambda {
   var state: one State,
} {
  this in Lambda'
}

pred complete[l:Lambda] {
   l.state' in Complete + Failed
}

pred can_step[l:Lambda] {
  l.state = InProgress
}

pred wait[l:Lambda] {
 l.state' = l.state
}

pred step_lambdas[] {
  all l: Lambda {
     can_step[l] implies (complete[l] or wait[l]) else wait[l]
  }
  lone l: Lambda | complete[l] // only let one lambda complete at at time
}

pred trigger_lambda[] {
  one l: Lambda' | Lambda' = Lambda + l' and l.state' = InProgress
}

pred do_nothing[] {
  Lambda != none
  Lambda = Lambda'
}

fact {
  Lambda = none
  always trigger_lambda or do_nothing
  always step_lambdas
}

check {
  eventually {
    some Lambda
    no l: Lambda | can_step[l]
  }
}

Update #1: I tried changing the check statement to the below. I believe it should show me a violation with t0, t1, t2 where at t2 there is a Lambda with state = Error.  Instead, it shows me a violation with t0, t1 where at t1 there is a Lambda with state = InProgress.  I don't see how this violates the check.
...

check {
  some Lambda
  (all l:Lambda |  not can_step[l]) implies all l:Lambda | l.state = Complete
}

A: I figured it out.  I need to express the check in the form "All lambdas must always be able to step or be in a completed state."
check {
  always all l:Lambda | can_step[l] or l.state in Complete
}

Complete model which finds a counterexample where a lambda ends in Failed state.
abstract sig State {}
sig InProgress, Complete, Failed extends State {}

var sig Lambda {
   var state: one State,
} {
  this in Lambda'
}

pred complete[l:Lambda] {
   l.state' in Complete + Failed
}

pred can_step[l:Lambda] {
  l.state = InProgress
}

pred wait[l:Lambda] {
 l.state' = l.state
}

pred step_lambdas[] {
  all l: Lambda {
     can_step[l] implies (complete[l] or wait[l]) else wait[l]
  }
  lone l: Lambda | complete[l] // only let one lambda complete at at time
}

pred trigger_lambda[] {
  one l: Lambda' | Lambda' = Lambda + l' and l.state' = InProgress
}

pred do_nothing[] {
  Lambda != none
  Lambda = Lambda'
}

fact {
  Lambda = none
  always trigger_lambda or do_nothing
  always step_lambdas
}

check {
  always all l:Lambda | can_step[l] or l.state in Complete
}


text:
Q: read data using shared preferences, data always re-render in flutter I tried to read data using shared preferences and return my widget using FutureBuilder, but the problem is... when I click another tab screen and then back again to my home tab screen, the data inside widget always rerender.. is there a way so that my data always stick in my widget whenever I click another tab and back again to my home tab?
here is the code
class _SecondPageState extends State<SecondPage>
    with AutomaticKeepAliveClientMixin<SecondPage> {
  Future<int> _getUsername;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    _getUsername = SharedPreferences.getInstance().then((prefs) {
      return prefs.getInt("username");
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getUsername,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            print("loading");
            return Text("Loading username...");
// how to prevent this condition so that my data always stick in my widget without rerender
          }

          final username = snapshot.data.toString();

          return Container(
            child: Text("Hello $username"),
          );
        });
  }
}

A: You can copy paste run full code below
You can use AutomaticKeepAliveClientMixin
code snippet
class _Page3State extends State<Page3>
    with AutomaticKeepAliveClientMixin<Page3> {
  ...

  @override
  bool get wantKeepAlive => true;

 FutureBuilder(
        future: _getUsername,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            print("loading");
            return Text("Loading username...");

Working demo, you can see console output only print one loading

Output
I/flutter ( 8528): loading

full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MainPersistentTabBar(),
    );
  }
}

class MainPersistentTabBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            isScrollable: true,
            tabs: [
              Tab(
                icon: Icon(Icons.directions_car),
                text: "Non persistent",
              ),
              Tab(icon: Icon(Icons.directions_transit), text: "Persistent"),
              Tab(icon: Icon(Icons.directions_railway), text: "Test 1"),
              Tab(icon: Icon(Icons.directions_subway), text: "Test 2"),
            ],
          ),
          title: Text('Persistent Tab Demo'),
        ),
        body: TabBarView(
          children: [
            Page1(),
            Page2(),
            Page3(),
            Text('Page 4'),
          ],
        ),
      ),
    );
  }
}

class Page3 extends StatefulWidget {
  @override
  _Page3State createState() => _Page3State();
}

class _Page3State extends State<Page3>
    with AutomaticKeepAliveClientMixin<Page3> {
  Future<int> _getUsername;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    _getUsername = SharedPreferences.getInstance().then((prefs) {
      return prefs.getInt("username");
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getUsername,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            print("loading");
            return Text("Loading username...");
// how to prevent this condition so that my data always stick in my widget without rerender
          }

          final username = snapshot.data.toString();

          return Container(
            child: Text("Hello $username"),
          );
        });
  }
}

class Page1 extends StatefulWidget {
  @override
  _Page1State createState() => _Page1State();
}

class _Page1State extends State<Page1> {
  var list = List();

  _loadList() async {
    final response =
        await http.get("https://jsonplaceholder.typicode.com/posts/");
    if (response.statusCode == 200) {
      await new Future.delayed(const Duration(seconds: 1));
      if (mounted) {
        setState(() {
          list = json.decode(response.body) as List;
        });
      }
    } else {
      throw Exception('Failed to load posts');
    }
  }

  @override
  void initState() {
    _loadList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (BuildContext context, int index) {
        final data = list[index];
        return ListTile(
          contentPadding: EdgeInsets.all(10.0),
          title: Text(data['title']),
          subtitle: Text(
            data['body'],
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        );
      },
    );
  }
}

class Page2 extends StatefulWidget {
  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2>
    with AutomaticKeepAliveClientMixin<Page2> {
  var list = List();

  _loadList() async {
    final response =
        await http.get("https://jsonplaceholder.typicode.com/photos/");
    if (response.statusCode == 200) {
      await new Future.delayed(const Duration(seconds: 1));
      if (mounted) {
        setState(() {
          list = json.decode(response.body) as List;
        });
      }
    } else {
      throw Exception('Failed to load posts');
    }
  }

  @override
  void initState() {
    _loadList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: ListView.builder(
        itemCount: list.length,
        itemBuilder: (BuildContext context, int index) {
          final data = list[index];
          return ListTile(
            contentPadding: EdgeInsets.all(10.0),
            title: Text(data['title']),
            trailing: Image.network(
              data['thumbnailUrl'],
              height: 20.0,
              width: 20.0,
            ),
          );
        },
      ),
    );
  }

  // TODO: implement wantKeepAlive
  @override
  bool get wantKeepAlive => true;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compare timestamp in sql server Given the following table, how can I select the most recent timestamp from a given user?
Here is my table:

For instance, if USERID 5, I want to compare every USERID 5 timestamp and return the most recent timestamp.

A: If you want the latest timestamp for a user you can use the max function:
select userid, max(checktime)
from your_table
group by userid
where userid = 5

If you remove the where clause you'll get a list of all userid with their latest checktime.

A: Not sure if I understand correctly?
Maybe it is just as simple as that?
SELECT MAX(CHECKTIME) FROM Table WHERE UserID = 5

If not, you could google for OVER clause.


text:
Q: SSH: use specific key when logging in In /home/petri/.ssh/ I have my private key called petri. When I try to connect to my server using ssh, it does not accept my private key. Running -v learns that it is not trying my key petry, but just the non-existent id_rsa and id_dsa:
$ssh server
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering public key: petri@office
debug1: Authentications that can continue: publickey
debug1: Offering public key: petri@office
debug1: Authentications that can continue: publickey
debug1: Offering public key: petri@office
debug1: Authentications that can continue: publickey
debug1: Offering public key: petri@office
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/petri/.ssh/id_rsa
debug1: Trying private key: /home/petri/.ssh/id_dsa
debug1: No more authentication methods to try.
Permission denied (publickey).

The odd thing is that things were fine before. Anyway, how do I tell SSH to use my petri key and quite trying the non-existent standard keys?
NOTE: my .ssh folder is chmod 700 and the petri file is 600, that is not the problem.

A: Try this:
ssh -i /path/to/petri

A: Two ways:

*

*Specify the key in your ssh command, something like "ssh -i ~/.ssh/petri server.example.com"

*Create a .ssh/config file with something like:

Host *
IdentityFile /home/petri/.ssh/petri

For more options, do a "man ssh_config" or "man ssh", depending on which you want to do.


text:
Q: Contact Form Not Flagging Errors PHP I'm trying to create a contact form for a website, but it's not handling errors correctly. When an invalid email address is entered or a field is left blank, it is still trying to send the email instead of showing the error message. I'm not sure what I need to do to fix this. If no errors occur, it should send the contact form out and send a confirmation email to the address listed in the form.
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Leah Stephens</title>

  <link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" type="text/css" href="../css/contact-styles.css">

Contact Me

    <form action="mail.php" method="POST">

        <input type="text" name="name" id="name" placeholder="Who Are You?"/>
        Name
        <?php if(isset($errors['name'])) { echo $errors['name']; } ?>

        <input type="text" name="email" id="email" placeholder="name@email.com"/>
        Email
        <?php if(isset($errors['email'])) { echo $errors['email']; } ?>

        <textarea name="message" id="msg" rows="4" placeholder="Your message goes here..."/></textarea>
        Msg
        <?php if(isset($errors['message'])) { echo $errors['message']; } ?>

      <input class="button" type="submit" name="submit" value="Send"/>
    </form>

$myEmail = "example@email.net";
        $errors=[];
        if(isset($_POST['submit'])){
            $name = $_POST['name'];
            $email = $_POST['email'];
            $message = $_POST['message'];

            if (!isset($_POST['name']) || empty($_POST['name'])){
                    $error['name'] = 'Please enter your name';
            }

            if (!isset($_POST['email']) || empty($_POST['email']) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
                    $error['email'] = 'Please enter a valid email address';
            }

            if (!isset($_POST['message']) || empty($_POST['message'])){
                    $error['message'] = 'Please enter your message';
            }

            if(empty($errors)){
                $to = $myEmail;
                $subject = "Contact Form Submission: $name";
                $body = "From: $name\n Email: $email\n Message:\n $message";
                $header = "From: $myEmail\n";
                $header .= "Reply-To: $email";

                $confirmSubject = "Contact Form Confirmation";
                $confirmBody = "Hi!\n Thank you for reaching out. I\'ll do my best to get back to you within the next 48 hours. Have a great day!";
                $confirmHeader = "From: $email\n";
                $confirmHeader .= "Reply-To: $myEmail";

                mail($to, $subject, $body);
                mail($email, $confirmSubject, $confirmBody);
                header('Location: ../index.html');
            }
        }

A: See that you have not initialised the $error['email'] OR other similar variables before you have used them. You are initialising them later in the next page. You will definitely not get the error message you are intending to display.
A solution could be, instead of linking your form to mail.php , set action="" and write the php code for mail.php on the original page itself.
And, checkout for $error spelling, you have spelled it $errors


text:
Q: expl3: Expand every item once when adding to a clist I want to add items to a clist and expand every item once. But the (to my eyes) natural \clist_set:No didn't work as expected as it expanded only the first item.
\documentclass{article}
\usepackage{expl3}

\begin{document}
\ExplSyntaxOn
\def\testa{blub}
\def\testb{blabla}
\clist_set:No\mylist{\testa,\testb}
\clist_show:N\mylist
\ExplSyntaxOff
\end{document}

 The comma list \mylist contains the items (without outer braces):
>  {blub}
>  {\testb }.

So what is the correct way to do this? Does one really have to use some loop?

A: The o variant just expands the first token after the brace.
You have to add the items one by one:
\clist_new:N \l_ulrike_mylist_clist

\clist_map_inline:nn { \testa , \testb }
 {
  \clist_put_right:No \l_ulrike_mylist_clist { #1 }
 }

Of course you can build your syntactic sugar for this.
\cs_new_protected:Nn \ulrike_clist_set_exp:Nn
 {
  \clist_clear:N #1
  \clist_map_inline:nn { #2 }
   {
    \clist_put_right:No #1 { ##1 }
   }
 }


text:
Q: Is this function decreasing at its points of discontinuity? I have a real valued function $V (t)$. It is continuous at all points except a countable of number of points $t_k $ at which it has jump discontunities. Now this sequence $\{t_k\} $ is strictly increasing. And $V (t) $ is right continuous at all these points such that $V (t_k)\leq V (t_k^-) $ for all $k\in\mathbb {N}.$ Then can i say that $V (t_k)\leq V (t_{k-1}) $ for all $k\in\mathbb{N}?$ The reasons for this intuition are  $V (t) $ is continuous at all points except $t_k,$ the left limit of $V (t)$ at $t_k $ is greater than $V (t_k)$ and $t_{k-1} $ lies to left of $t_k $?

A: Your intuition fails. A simple counter-example is $V(x)=x^{2}-[x]$ with $t_k=k$ for all $k$. In this case $V(t_2) >V(t_1)$.


text:
Q: Using variables returned from infinite loop function in another file I know the title may sound a bit confusing but here is my struggle:
I have two separate files, one is only for gathering data and converting (data_.py) it and the second is main program file (main_.py). The core function in data_.py looks like this (it is simplified ofc):
def some_function():
    #here some python magic happens
  while True:
    #more magic
    return var1, var2, var3

variables are updated every few seconds. Now Im trying to use them in main_.py, so far I have this:
import data_

var1, var2, var3 = data_.some_function()

and when I print my variables everything works, but of course they are imported only once and not updated after.
I've tried doing this:
import data_

while True:
    var1, var2, var3 = data_.some_function()
    print(var1, var2, var3)

to update them as frequently as possible, yet they aren't updating for some reason.
Is there a way to achieve this while keeping function in separate files?

A: The functionality you are looking for is generator. Below is sudo code for your case
you define you function like this. you gather and convert data and when a chunk of data is ready to be processed you give that to other code calling this function. But this is not parallel processing. your some_function() pauses until that data is being processed.
def some_function():
    #here some python magic happens
    while True:
        #more magic
        yield var1, var2, var3

then you use this function like below. the loop continues until while loop on some_function is not finished
for var1,var2,var3 in some_function():
    print(var1, var2, var3)

Working Example
def some_function():
    for x1, x2 in zip(range(1000),range(0,2000,2)):
        yield x1,x2

for x1,x2 in some_function():
    print(x1,x2)


text:
Q: property not found + ajax I'm trying to use primefaces component called rating inside a datatable.
<p:column headerText="Minha Dificuldade" syle="text-align: center; width: 100px">

                <p:rating readonly="false" stars="10"   value="#{cadastroDificuldadeBean.calculaMinhaDificuldade(jogo)}" >

                    <f:param name="jogoId" value="#{jogo.id}" />
                     <p:ajax event="rate" listener="#{cadastroDificuldadeBean.onrate}"  />
                </p:rating>

</p:column>

On page load my column is visible with p:rating calculated (method with parameter). When I click on star to rating an ajax call is submitted (event = "rate") and a throw is shown  Property 'calculaMinhaDificuldade' not found on type 'my class'.
Any ideas?


text:
Q: Spring Security Win Auth example is not authenticating properly - says null keytab file when it is clearly being passed in and acknowledged I have downloaded and tried testing the sec-server-win-auth sample app for Spring Security Extensions.  I performed the following steps:

*

*download and build the spring-security-Kerberos-master project.

*pulled out the sec-server-win-auth-1.0.0.BUILD-SNAPSHOT.jar into a
folder on PROD server.

*create a new application.yml in the same folder with my custom
information

*create a tomcat.keytab on my test domain controller, named DC.

*copy the tomcat.keytab file to my PROD server.

*run java -jar sec-server-win-auth-1.0.0.BUILD-SNAPSHOT.jar

*On a separate client,CLIENT1, open IE and go to http://PROD:8080/
At this point, I see the request for the Kerberos negotiate header and the response with the header.  It says it is valid and it tries to authenticate it, but I get the following error. "unable to obtain password from user"
This error is coming from the Krb5LoginModule.  There is a hint to the issue above this error that says the key for the principal is not available in the keytab file.  The principal is available, it is just getting null for my keytab file.
Debug is  true storeKey true useTicketCache false useKeyTab true doNotPrompt true ticketCache is null isInitiator true KeyTab is null     refreshKrb5Config is false principal is HTTP/DC.domain.local@DOMAI
N.LOCAL tryFirstPass is false useFirstPass is false storePass is false  clearPass is false
Key for the principal HTTP/DC.domain.local@DOMAIN.LOCAL not available in default key tab
                [Krb5LoginModule] authentication failed
Unable to obtain password from user

If I look further up in the logging stream, I can see that the keytab file is being passed in correctly from the application.yml and being loaded.
useKeyTab=true, keyTab=c:/kerberos/tomcat.keytab, debug=true, doNotPrompt=true}
Debug is  true storeKey true useTicketCache false useKeyTab true doNotPrompt true ticketCache is null isInitiator false KeyTab is c:/kerberos/tomcat.keytab refreshKrb5Config is false principal is HTTP
/DC.domain.local@DOMAIN.LOCAL tryFirstPass is false useFirstPass is false storePass is false clearPass is false
principal is HTTP/DC.domain.local@DOMAIN.LOCAL
Will use keytab
Commit Succeeded

I am not sure why my keytab is coming through as null further down the line.  Can anyone shed some light on this?
INFO 4564 --- [           main] demo.app.Application                     : Starting Application v1.0.0.BUILD-SNAPSHOT on PROD with PID 4564 (C:\kerberos\sec-server-win-auth-1.
0.0.BUILD-SNAPSHOT.jar started by tc01 in c:\kerberos)
INFO 4564 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5
6459b78: startup date [Fri Mar 27 23 EDT 2015]; root of context hierarchy
INFO 4564 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scop
e=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$White
labelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/Error
MvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=
false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName
=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
INFO 4564 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [c
lass org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c6bd8b6a] is not eligible for getting processed by all BeanPostProcessors (for example:
not eligible for auto-proxying)
INFO 4564 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionAttributeSource' of type [class org.springframework.transaction.annotation.Annotati
onTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO 4564 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionInterceptor' of type [class org.springframework.transaction.interceptor.Transaction
Interceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO 4564 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springfr
amework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO 4564 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
INFO 4564 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
INFO 4564 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.15
INFO 4564 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
INFO 4564 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2543 ms
WARN 4564 --- [ost-startStop-1] o.s.s.e.k.SunJaasKerberosTicketValidator : Initial Keytab location is:file:/c:/kerberos/tomcat.keytab
WARN 4564 --- [ost-startStop-1] o.s.s.e.k.SunJaasKerberosTicketValidator : Your keytab starts with file:.  Stripping it from path for Java 7 compatibility. TP
WARN 4564 --- [ost-startStop-1] o.s.s.e.k.SunJaasKerberosTicketValidator : Loading Keytab file from the following path: c:/kerberos/tomcat.keytab
WARN 4564 --- [ost-startStop-1] o.s.s.e.k.SunJaasKerberosTicketValidator : loginConfig data is:{isInitiator=false, storeKey=true, principal=HTTP/DC.domain.local@DOMAIN.LOCAL,
useKeyTab=true, keyTab=c:/kerberos/tomcat.keytab, debug=true, doNotPrompt=true}
Debug is  true storeKey true useTicketCache false useKeyTab true doNotPrompt true ticketCache is null isInitiator false KeyTab is c:/kerberos/tomcat.keytab refreshKrb5Config is false principal is HTTP
/DC.domain.local@DOMAIN.LOCAL tryFirstPass is false useFirstPass is false storePass is false clearPass is false
principal is HTTP/DC.domain.local@DOMAIN.LOCAL
Will use keytab
Commit Succeeded

INFO 4564 --- [ost-startStop-1] o.s.s.e.k.c.KerberosLdapContextSource    :  URL 'ldap://DC.DOMAIN.LOCAL/', root DN is ''
DEBUG 4564 --- [ost-startStop-1] o.s.l.c.support.AbstractContextSource    : AuthenticationSource not set - using default implementation
INFO 4564 --- [ost-startStop-1] o.s.l.c.support.AbstractContextSource    : Property 'userDn' not set - anonymous context will be used for read-write operations
DEBUG 4564 --- [ost-startStop-1] o.s.l.c.support.AbstractContextSource    : Using LDAP pooling.
DEBUG 4564 --- [ost-startStop-1] o.s.l.c.support.AbstractContextSource    : Trying provider Urls: ldap://DC.DOMAIN.LOCAL/
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for org.springframework.security.config.annotation
.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@4f38d17a
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for org.springframework.security.config.annotation
.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@1b40c938
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for org.springframework.security.config.annotation
.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@3a5a8982
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/logout', POST]
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for org.springframework.security.config.annotation
.web.configurers.PermitAllSupport$ExactUrlRequestMatcher@cbbe2cf
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/']
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/home']
DEBUG 4564 --- [ost-startStop-1] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'authenticated', for org.springframework.security.web.util.matc
her.AnyRequestMatcher@1
DEBUG 4564 --- [ost-startStop-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes
DEBUG 4564 --- [ost-startStop-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes
INFO 4564 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.sprin
gframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5c5a072a, org.springframework.security.web.context.SecurityContextPersistenceFilter@71142e50, org.springframework.securit
y.web.header.HeaderWriterFilter@709820cd, org.springframework.security.web.csrf.CsrfFilter@17fdb097, org.springframework.security.web.authentication.logout.LogoutFilter@653c5652, org.springframework.s
ecurity.web.authentication.UsernamePasswordAuthenticationFilter@6a5b07f2, org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter@1a8c85c4, org.springframework.securi
ty.web.savedrequest.RequestCacheAwareFilter@4c3d80e9, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@11e86f65, org.springframework.security.web.authentication.Anon
ymousAuthenticationFilter@7fa21479, org.springframework.security.web.session.SessionManagementFilter@40d2c946, org.springframework.security.web.access.ExceptionTranslationFilter@72b368f3, org.springfr
amework.security.web.access.intercept.FilterSecurityInterceptor@1ed5eb39]
INFO 4564 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
INFO 4564 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
INFO 4564 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'springSecurityFilterChain' to: [/*]
INFO 4564 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'spnegoAuthenticationProcessingFilter' to: [/*]
INFO 4564 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
DEBUG 4564 --- [ost-startStop-1] k.w.SpnegoAuthenticationProcessingFilter : Initializing filter 'spnegoAuthenticationProcessingFilter'
DEBUG 4564 --- [ost-startStop-1] k.w.SpnegoAuthenticationProcessingFilter : Filter 'spnegoAuthenticationProcessingFilter' configured successfully
DEBUG 4564 --- [ost-startStop-1] o.s.security.web.FilterChainProxy        : Initializing filter 'springSecurityFilterChain'
DEBUG 4564 --- [ost-startStop-1] o.s.security.web.FilterChainProxy        : Filter 'springSecurityFilterChain' configured successfully
INFO 4564 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWeb
ApplicationContext@56459b78: startup date [Fri Mar 27 23 EDT 2015]; root of context hierarchy
INFO 4564 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public or
g.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
INFO 4564 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto
public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
INFO 4564 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/hello] onto handler of type [class org.springframework.web.servlet.mvc.Parameteriz
ableViewController]
INFO 4564 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/home] onto handler of type [class org.springframework.web.servlet.mvc.Parameteriza
bleViewController]
INFO 4564 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/login] onto handler of type [class org.springframework.web.servlet.mvc.Parameteriz
ableViewController]
INFO 4564 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Root mapping to handler of type [class org.springframework.web.servlet.mvc.ParameterizableViewContro
ller]
INFO 4564 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceH
ttpRequestHandler]
INFO 4564 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.R
esourceHttpRequestHandler]
INFO 4564 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resour
ce.ResourceHttpRequestHandler]
INFO 4564 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
INFO 4564 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
INFO 4564 --- [           main] demo.app.Application                     : Started Application in 5.523 seconds (JVM running for 6.365)
INFO 4564 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
INFO 4564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
INFO 4564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 32 ms
DEBUG 4564 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /hello at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFil
ter'
DEBUG 4564 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /hello at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFil
ter'
DEBUG 4564 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
DEBUG 4564 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
DEBUG 4564 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /hello at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG 4564 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web
.header.writers.HstsHeaderWriter$SecureRequestMatcher@33baf8cf
DEBUG 4564 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /hello at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG 4564 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /hello at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG 4564 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /hello' doesn't match 'POST /logout
DEBUG 4564 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /hello at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticatio
nFilter'
DEBUG 4564 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /hello' doesn't match 'POST /login
DEBUG 4564 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /hello at position 7 of 13 in additional filter chain; firing Filter: 'SpnegoAuthenticationProcessin
gFilter'
DEBUG 4564 --- [nio-8080-exec-1] k.w.SpnegoAuthenticationProcessingFilter : Received Negotiate Header for request http://prod:8080/hello: Negotiate YIIGPwYGKwYBBQUCoIIGMzCCBi+g
MDAuBgkqhkiC9xIBAgIGCSqGSIb3EgECAgYKKwYBBAGCNwICHgYKKwYBBAGCNwICCqKCBfkEggX1YIIF8QYJKoZIhvcSAQICAQBuggXgMIIF3KADAgEFoQMCAQ6iBwMFACAAAACjggRkYYIEYDCCBFygAwIBBaEOGwxET01BSU4uTE9DQUyiJDAioAMCAQKhGzAZGwRI
VFRQGxFwcm9kLmRvbWFpbi5sb2NhbKOCBB0wggQZoAMCARehAwIBBqKCBAsEggQHvjMpkhlvwPjCmBCH09gyPQoTR4eydq69R6YizJKFZcN8BmEW0p1lS2So0FGxZflvRALL0Ev2+ME0Jub6QJ3bEDyr2XsRWeDViJbFIM5BDLc0F5qKdIj65Nw/ltB7fr/aWSOwpI/b
a1vQzUeLEnRzBAbkN23r+SETz7Yjgygof3BMr6DjmHWPWtogOchkkqCtz4o5WFXWpbWDKtXLKhV2BzHHE7aMVhGhLokMhn1cP3YI/0k7R/9zoILt53PIaK05MWF3k6mdPSFCkMd+BAkpVEIYQ8sSC/83UtsXU7ndGNfQuq5096nlsx2hP7Mk3qR/vGha2KO82DcEFSB0
lnRNel5wXw3wAfjzp3D2p62a/cnc9/ZqzMBfqjgZbDg9uBT0O41rGgHZX+acRvudcZBk2MQbWg9BSrthSZYDFgoS1gsTDusEsBpQc42mKHRTboMHpTRB9hoF3BD+MJeaTHAj2r0puLNJlATOMtqvFEJ+FQBN1yJikiFhG8OdBpahGAll9oVhThtwVj7M8weygDFDagCj
6lqIMKtpacaDEPmk2dmRNYPi64/tT6lx5fGmcxoL+Z3gIK5+oLlv6EnfR5PT6lKErgzbtuYc+gHMzZuztKNIEqFk6pjeXXnOKDB2P3XOyeP6rbdvnZ5MTJDhlVOsrOjh2giYTgjVj8Z+U0dJlkK0V3XHkz5VVg3IQobdyhxXxbkPBvXqOvaeDB+abQvnq1VIap5P7xGi
G3MUBMFBBVKdyVyGRcYnr6qp458GsOxZ06pGUE8pWiu+1vh3uT9qYSG0JJKULQvZLPEdKyaK2Dck4etgYuLk5odaT2bBDTqW2DA3NKxZpmCicTtHtfyJGMthp74uvpnD0iif+4S94pa7CkPwWv0jk8aOiQ3QHOZ7M2uGix7OCS2KHraVOD7BocqhgksTgAL/VLdKtjSy
saEkp3pSlkDLNnn9DwsYtno7trIDRIF1K0v8N0BdM8D7DS+J2KY7X4xs7giUYSPZjwflyoRruSrhRSnuiEv9RrIpZT6uhIMmz+2QOiKKqQBTiyEo27u+ztCjakX+qencMx6hxr7CogP28fQWNKISI2sRpgEhn7X/eVijqmnuDkBVGTgYkv7nTD6PWP6rhsaMoMvBIKwr
55ga1Tq0RRwpAUHO3+k7bqqsMuqoTouVN9pmP7xFPOwU7nP7oTApypbegtPVsxGrOeADpPcYNX3rxH1mq6N4gs5+BKhHa63ddbFcLbjb2GKcT5VrY4OLjVuCwEO1X5GSQwbhvXXu+lf1SWlc0Uvapu7CyU0fgLFan6jbTUaj4n7k1jz+RyFo2BSg2AWSgVCP3b/13F9b
DqgpEyVDh0507PxH3KNU7eB8pXht1eS9tTghAzGkggFdMIIBWaADAgEXooIBUASCAUy3vlYBZVSaqNUbw7VGO3YQlDV+Iw3+WnAnwcEXkt34PI95jOk3+Z/uHd6h2dAYo2qNHmXwX0S/p4BVnyEak5azsDxPbQKCKS6rzfYQmgSMx9PT9NYKR8rVyEHAjgW2/ajkSS8s
AnDNfsbkmKGKrKukEDAoJ7ij+S5f3HQ6NMeu+pF54ZFQ403Gby/cPFfQ6Jl96p1dsiF3v2p6AB7F5xQV6rd4G5R+cEqK/g77VQV7U0Jfj2qWgTXDwgjHuzuRFzdlNIMp+CBR0uyqH1c2nVugmkZMqwbBXULSQgGIKF6Vfo3WMACThjm0oUV0Xqz2/MCNgD7SfjEVIc7w
xWH+aUjBSGKWcxe+tUsULa0saYBXxI6MKJVM/tuyj6vAXFTTaGFWEJlWaPGe3TVaaCx7u3Dz2ih0SUtaBQlf1kvHwclHUe89BSVLYATXTV5dFA==
DEBUG 4564 --- [nio-8080-exec-1] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.extensions.kerberos.KerberosServiceAuthent
icationProvider
DEBUG 4564 --- [nio-8080-exec-1] .k.KerberosServiceAuthenticationProvider : Try to validate Kerberos Token
DEBUG 4564 --- [nio-8080-exec-1] .k.KerberosServiceAuthenticationProvider : Succesfully validated spectrum@DOMAIN.LOCAL
DEBUG 4564 --- [nio-8080-exec-1] o.s.s.l.s.FilterBasedLdapUserSearch      : Searching for user 'spectrum@DOMAIN.LOCAL', with user search [ searchFilter: '(| (userPrincipalName=
{0}) (sAMAccountName={0}))', searchBase: 'CN=Users,DC=domain,DC=local', scope: subtree, searchTimeLimit: 0, derefLinkFlag: false ]
Debug is  true storeKey true useTicketCache false useKeyTab true doNotPrompt true ticketCache is null isInitiator true KeyTab is null refreshKrb5Config is false principal is HTTP/DC.domain.local@DOMAI
N.LOCAL tryFirstPass is false useFirstPass is false storePass is false clearPass is false
Key for the principal HTTP/DC.domain.local@DOMAIN.LOCAL not available in default key tab
                [Krb5LoginModule] authentication failed
Unable to obtain password from user

DEBUG 4564 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG 4564 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
ERROR 4564 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception

org.springframework.ldap.AuthenticationException: Unable to obtain password from user
; nested exception is javax.naming.AuthenticationException: Unable to obtain password from user
 [Root exception is javax.security.auth.login.LoginException: Unable to obtain password from user
]
        at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:182)
        at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:285)
        at org.springframework.ldap.core.support.AbstractContextSource.doGetContext(AbstractContextSource.java:119)
        at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:138)
        at org.springframework.ldap.core.LdapTemplate.executeReadOnly(LdapTemplate.java:791)
        at org.springframework.security.ldap.SpringSecurityLdapTemplate.searchForSingleEntry(SpringSecurityLdapTemplate.java:194)
        at org.springframework.security.ldap.search.FilterBasedLdapUserSearch.searchForUser(FilterBasedLdapUserSearch.java:116)
        at org.springframework.security.ldap.userdetails.LdapUserDetailsService.loadUserByUsername(LdapUserDetailsService.java:38)
        at org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider.authenticate(KerberosServiceAuthenticationProvider.java:69)
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
        at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:446)
        at org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter.doFilter(SpnegoAuthenticationProcessingFilter.java:145)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
        at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
<1 - snipped ->
        at java.lang.Thread.run(Unknown Source)
Caused by: javax.naming.AuthenticationException: Unable to obtain password from user

        at org.springframework.security.extensions.kerberos.client.KerberosLdapContextSource.login(KerberosLdapContextSource.java:143)
        at org.springframework.security.extensions.kerberos.client.KerberosLdapContextSource.getDirContextInstance(KerberosLdapContextSource.java:102)
        at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:273)
        ... 51 common frames omitted
Caused by: javax.security.auth.login.LoginException: Unable to obtain password from user

        at com.sun.security.auth.module.Krb5LoginModule.promptForPass(Unknown Source)
        at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(Unknown Source)
        at com.sun.security.auth.module.Krb5LoginModule.login(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at javax.security.auth.login.LoginContext.invoke(Unknown Source)
        at javax.security.auth.login.LoginContext.access$000(Unknown Source)
        at javax.security.auth.login.LoginContext$4.run(Unknown Source)
        at javax.security.auth.login.LoginContext$4.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.login.LoginContext.invokePriv(Unknown Source)
        at javax.security.auth.login.LoginContext.login(Unknown Source)
        at org.springframework.security.extensions.kerberos.client.KerberosLdapContextSource.login(KerberosLdapContextSource.java:139)
        ... 53 common frames omitted

A: I see what's going wrong here which is my mistake.SunJaasKrb5LoginConfig in WebSecurityConfig is not created as bean so afterPropertiesSet() is not called, thus causing what you just reported.

*

*In WebSecurityConfig.kerberosLdapContextSource() call loginConfig.afterPropertiesSet() manually.

*Or create SunJaasKrb5LoginConfig as bean in a normal spring way and let framework to call its afterPropertiesSet().
This slipped from my radar because I had to use -Djava.security.krb5.conf=/path/to/krb5.ini in my tests due to my complex krb setup and I had a path to keytab file there.
I did a fix with https://github.com/spring-projects/spring-security-kerberos/commit/f354bc29f2c6558456cfc7fbfc84d0c1b6fd0606, let us know if this fixes your issue.


text:
Q: Custom Dialog not displaying - Android I'm trying to pop up a custom dialog when I click on a button but it won't pop up at all. my app is basically a calendar and I'm going to use sqlite to add/hold appointments and stuff to a date in the calendar using the dialog, which is where the appointment details will be specified.
The code I'm using for this is the following:
public void onClick(View v) {
        // TODO Auto-generated method stub
        //long a = calendar.getDate();
        switch(v.getId()){
        case R.id.createButton:
            openCreateAppointmentDialog();
            break;
        }
    }

    private void openCreateAppointmentDialog(){
        Context mContext = getApplicationContext();
        Dialog createAppmntDialog = new Dialog(mContext);

        createAppmntDialog.setContentView(R.layout.create);
        createAppmntDialog.setTitle(R.string.createTitle);

        appointmentTitle = (EditText) createAppmntDialog.findViewById(R.id.titleTextBox);
        appointmentTitle.setText("hello");

        appointmentTime = (EditText) createAppmntDialog.findViewById(R.id.timeTextBox);

        appointmentDetails = (EditText) createAppmntDialog.findViewById(R.id.detailsTextBox);

        saveAppointment = (Button) createAppmntDialog.findViewById(R.id.saveButton);
        saveAppointment.setOnClickListener(this);
    }

What am I doing wrong?

A: Call the show() method for your dialog.
createAppmntDialog.show(); //when you want the dialog to appear on the screen


text:
Q: Search parameter "bounding_box" matches fewer tweets over time in Tweepy in python I am using Tweepy to scrape the API for tweets mapped to particular cities that contain specific keywords. I am then conducting statistical analysis to see where and when keyword mentions in these cities spike. So it's really important that my Python program is turning up the entire population of tweets I am looking for. I have run into a problem, however, that makes my analysis difficult to do.
My program has two queries: One fetches me the number of tweets from 2015 until now that are mapped to a bounding box enclosing a given city and contain my desired keyword. The second query is just a search that fetches me the total number of tweets from 2015 until now that are mapped to the bounding box. From there, I organize the data and run some functions to calculate keyword frequency over time in each city. Here's the code for the queries:
client = tweepy.Client(bearer_token="REDACTED",
                          consumer_secret=SecretKey, access_token=AccessToken, access_token_secret=AccessTokenSecret, wait_on_rate_limit=True)

# search query
query = 'KEYWORD bounding_box:[-87.296643 14.018294 -87.116257 14.164161]'

start_time = '2015-01-01T00:00:00Z'

end_time = '2022-08-01T00:00:00Z'

#make a list of tweets

KeywordTG=[]

for tweet in tweepy.Paginator(client.get_all_tweets_count, query=query,
                              start_time=start_time, end_time=end_time, granularity="day").flatten(limit=5000):
    KeywordTG.append(tweet)

SECOND QUERY:

    client = tweepy.Client(bearer_token="REDACTED",
                      consumer_secret=SecretKey, access_token=AccessToken, access_token_secret=AccessTokenSecret, wait_on_rate_limit=True)

# search query

query = 'bounding_box:[-87.296643 14.018294 -87.116257 14.164161]'

start_time = '2015-01-01T00:00:00Z'

end_time = '2022-08-01T00:00:00Z'

#make a list of tweets

AllTweets=[]

for tweet in tweepy.Paginator(client.get_all_tweets_count, query=query,
                              start_time=start_time, end_time=end_time, granularity="day").flatten(limit=5000):
    AllTweets.append(tweet)

I am finding that for two of the cities I am studying – Tegucigalpa, Honduras and Guatemala City, Guatemala – the second query (which gets me total number of tweets) is turning up lower numbers of tweets over time. So while the first few months of 2015 turn up over 100,000 total tweets per month, by summer 2022 that number is down to a little over 1,000 per month. What's perplexing is that this is not a problem for my query in San Salvador, El Salvador. I am using the same exact code for my query (although of course with a different bounding box), and the total number of tweets mapping to El Salvador does not decline over time.
I know that the bounding_box parameter matches tweets that a) have user-provided exact coordinates falling within the box or b) a user-provided location whose coordinates fall within the box. Is this issue I'm running into a problem with the bounding_box parameter? Is it reflective of the fact that Twitter phased out geotagging? Or might there be some local phenomenon in Guatemala City and Tegucigalpa, wherein Twitter users began to stop providing information about their location? I have also deduced that the number of tweets that match has:geo has declined over time in Guatemala City and Tegucigalpa, but not in El Salvador. Very weird.
Any help would be greatly appreciated, as my statistical analysis is much less valid if this problem remains.


text:
Q: Issue with Integer.parseInt As I run this program, when the string "How are you today?" is inputted into the console, instead of being able to type in the Key Matrix into the console after that, the code seems to skip straight to test.process(); which gives me these errors:
Exception in thread "main" java.lang.NumberFormatException: For input string: " are you today?"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at EncoderAdd.stringtoKey(EncoderAdd.java:24)
at EncoderAdd.process(EncoderAdd.java:93)
at Runner.main(Runner.java:19)

The methods that the errors point to are here:
System.out.println("Type message to be encoded here:");
            String encode = in.next();
            if (encode.length() > 0){
                System.out.println("Type key matrix here (Like: k1, k2, k3,  k4):");
                String kmatrix = in.nextLine();
                System.out.println("");
                EncoderAdd test = new EncoderAdd(encode, kmatrix);
                test.process();
            }

public void stringtoKey(){
    String[] temp = mat.split(",");
    for (int i = 0; i < temp.length; i++){
        keyMat[i] = Integer.parseInt(temp[i]);
    }
}

public void process(){
    stringtoKey();
    stringtoInt();
    addkeytoInt();
    intArrtoFinal();
}

How do I fix the errors that are occurring?
Thank you!

A: Don't mix next() (consumes up to space) and nextLine(). I think the easiest fix is something like
String encode = in.nextLine();

In your posted code next() gets "How", and that leaves " are you today?" for the next call to nextLine().


text:
Q: java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory - Related to Appium

java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory

    at io.appium.java_client.service.local.AppiumDriverLocalService.<clinit>(AppiumDriverLocalService.java:57)
    at BaseTest.globalSetup(basetest.java:14)
    at androidtest.globalSetup(androidtest.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
    at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:385)
    at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:321)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:317)
    at org.testng.SuiteRunner.run(SuiteRunner.java:276)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
    at org.testng.TestNG.runSuites(TestNG.java:1063)
    at org.testng.TestNG.run(TestNG.java:1031)
    at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
    at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:109)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 21 more

Below is what i have where the code fails at globalSetUp()

Below is also relevant code

and Appium server says

Hello all, trying to get appium working for the first time as a novice, would like to know what i can do over at pom.xml or what can i do to resolve this problem.
Thanks!

A: Add a SLF4J implementation:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.30</version>
</dependency>


text:
Q: how to display data in a angularjs form when two checkboxes are checked? I have a form which contains 4 checkboxes -

■ angularjs ■ jquery ■ ruby ■ Do nothing

In my controller there is a $watch service that is keeping track of the checkbox that is getting clicked.
 $scope.$watch("formData.displayOption", function(displayOption) {
        if(displayOption) {
          var value1 = displayOption.angularJs,
              value2 = displayOption.jquery,
              value3 = displayOption.ruby,
              value4 = displayOption.doNothing;

          console.log(value1, value2, value3, value4);

          $scope.pages = null;
          $scope.message = null;

          if (value1 === true ) {
            $scope.pages = groupOne;
          } else if (value2 === true) {
            $scope.pages = groupTwo;
          } else if (value3 === true) {
            $scope.pages = groupThree;
          } else {
            $scope.message = 'No Options';
          }
        }
      }, true);

and the groupOne,groupTwo,groupThree that i am assigning to $scope.pages is
  var groupOne = [
    { name: 'js'},
    { name: 'angjs'},
    { name: 'angularjs'}
  ];

  var groupTwo = [
    { name: 'jquery'},
    { name: 'jquery-ui'}
  ];
  var groupThree = [
    { name: 'Ruby'}
  ];

So when angularjs is checked -> groupOne is displayed similarly for jquery->groupTwo & ruby->groupThree
What i am trying to do is when two checkboxes are ticked i want to display both the data corresponding to the checked box and similarly when the checkbox is unchecked i want the data to disappear.
Like if ✓ angularjs and ✓ jquery then the displaying data should be

*

*js

*angjs

*angularjs

*jquery

*jquery-ui

PLUNKER LINK

A: You can use concat to append each selected item into $scope.pages. Change your if-else block in the watch to:
if (value1 === true ) {
    $scope.pages = groupOne;
} if (value2 === true) {
    $scope.pages = $scope.pages.concat(groupTwo);
} if (value3 === true) {
    $scope.pages = $scope.pages.concat(groupThree);
} if(!value1 && !value2 && !value3) {
    $scope.message = 'No Options';
}

Updated the plunker here.
EDIT:
Also, instead of $scope.pages = null; have $scope.pages = []; in your watch.


text:
Q: NSURLCache not used by NSURLConnection / AFNetworkingOperation When I start a request with the NSURLRequestReturnCacheDataElseLoad policy I expect to get the result from the NSURLCache if any, no matter how old it is. However, the system always tries to reach the server the request points to and returns an error if the server doesn't answer.
I use the UIImageView category of AFNetworking for the request.
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
__weak __typeof(self) weakSelf = self;
NSLog(@"[%@] %@", request.URL, [[NSURLCache sharedURLCache] cachedResponseForRequest:request]); // this returns an instance of NSCachedURLResponse!
[self setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
    __typeof(weakSelf) self = weakSelf;
    self.image = image;
} failure:NULL];

This will not set the image even if asking the NSURLCache directly will return a valid NSCachedURLResponse.
The app is running on iOS6 only, so there should be no problems with on-disk cache as far as I know?!
Any help is appreciated! Thanks!

A: This is a know issue. Please refer this discussion on AFNetworking github page for a workaround.


text:
Q: Are there limit problems that cannot be solved? This could mean any of the following:
the limit is unsolvable by algebraic means or by hand (rationalizing or limit laws or squeeze theorem)
the limit is unknown
inspired by:
http://socrates.bmcc.cuny.edu/math/Mzyman/CalcLab2-303.pdf

A: Let $a_n$ be the number of times the digit $9$ appears in the first $n$ digits of the decimal expansion of $\pi$. What is
$$
\lim_{n\to\infty}\frac{a_n}{n}?
$$

A: If you mean "solve a limit" by calculating the specific value of it, the answer is yes; and there are perhaps a lot more limits than you can calculate by algebraic means.
Consider the following infinite series when $s$ is positive
$$ \zeta(s) = \sum_{n=1}^{\infty}\frac{1}{n^s} $$
We know that $\zeta(1)$ diverges. How about other values of s? They are not easily calculable; most of them requires advanced knowledge in mathematics. For example, $\zeta(2)$ equals $\frac{\pi}{6}$, while the limit itself suggests no connection with $pi$. This surprising result can be proved by multiple methods, the one I know requires some knowledge in Fourier analysis. Until now, we have for even integers $2n$,
$$\zeta (2n)={\frac {(-1)^{n+1}B_{2n}(2\pi )^{2n}}{2(2n)!}} $$
But no general expression has been yet found for odd, or even rational numbers.
Many mathematicians were devoted to study $\zeta(s)$, which is related to the famous unsolved mathematical problem, the Riemann Hypothesis.


text:
Q: How-to check if user is logged in asp.net and depending on if they are logged in display a certain page? I have a very basic understanding of ASP.NET and I am trying to do the following. I have a home page that is set-up to be a login page. If you could just picture a username and password box that is the extent of that home page. Once the user is logged in they will go to a different page let's say the account page. However, when the user clicks the logo at the top left hand it takes them to the home page again but it shows the username and password boxes again ready to be filled.
The user status at the top of my page still shows that the user is logged in. What I am trying to do is add a piece of code that will change the link of the logo to display the account page once they are logged in and not the login page.
I don't know if this can be done through the web.config file since I read a different article that has something similar to this or if this code can be put directly next to the code where my logo link (default.aspx) sits.
Many thanks in advance!

A: Research the Membership Provider.
It's an industry standard in ASP.NET session management.  It will manage all of your pages and allow you to customize pages, menus, etc. based on roles and permissions.  Don't reinvent the wheel if you have the oppertunity to use it.
Straight from MSDN:

ASP.NET membership supports facilities
  for:
Creating new users and passwords.
Storing membership information (user
  names, passwords, and supporting data)
  in Microsoft SQL Server, Active
  Directory, or an alternative data
  store.
Authenticating users who visit your
  site. You can authenticate users
  programmatically, or you can use the
  ASP.NET login controls to create a
  complete authentication system that
  requires little or no code.
Managing passwords, which includes
  creating, changing, and resetting them
  . Depending on membership options you
  choose, the membership system can also
  provide an automated password-reset
  system that takes a user-supplied
  question and response.
Exposing a unique identification for
  authenticated users that you can use
  in your own applications and that also
  integrates with the ASP.NET
  personalization and role-management
  (authorization) systems.
Specifying a custom membership
  provider, which allows you to
  substitute your own code to manage
  membership and maintain membership
  data in a custom data store


text:
Q: How do I get Windows 7 to recognize my second graphics card? Really hope someone can help--
I recently purchased a second EVGA Geforce 660 to run in SLI mode on my PC, but no matter what, I can't seem to get the PC to recognize it.
My Specs:

*

*(2) EVGA GeForce 660 cards (the first one was previously installed and works fine

*Intel core i7

*32 Gb ram

*Windows 7 Ultimate 64bit

*Gigabyte GA-Z77X-UD3H motherboard (latest Bios installed)

*1000w power supply that is marketed as "SLI ready"

What I have verified:

*

*SLI bridge is plugged in (does it matter which end connects to which card?)

*First card is in PCI-16 slot, per Gigabyte instructions

*Second card is in PCI-8 slot per Gigabyte instructions HOWEVER the GeForce 660 literature says that the second card should go in a second PCI-16 slot which I do not have available.

*Only one card shows up in device manager under "Display Adapters"

*The fan on the second card is working so it looks like it is getting power

*Card is seated snugly in the slot

What I have tried

*

*I have updated the BIOS

*I have updated to the latest (not BETA) GeForce drivers.

*I have tried rebooting a bunch of times.

*I have tried banging my head against the wall and cussing out loud (didn't help)

Any thoughts?  Do I need to do something special in the BIOS?  Any help is appreciated.


text:
Q: Is it possible to work with git or something similar and not need to have the whole repository saved onto computer? Looking for a way to file share with version control between a lot of people on the same network. We are looking at using git, but we are wondering if there is any way of not having to download and contain the whole repository on your computer. The files shared will include regular text files, but also binary files such as zipped folders and another type our company uses. I know git isn't the best with binary files as it needs some workarounds to properly diff binary files. Just asking for any tips on using git to satisfy the problems above and making it easy to learn for others, or if there are any other similar ways of achieving these goals. Thanks .

A:
if there is any way of not having to download and contain the whole repository on your computer

That can be interpreted as:

*

*not having the full history (git shallow clone)

*not having the full content (git sparse checkout)

So it is possible, but again, git is a source control system best to manage... sources.


text:
Q: Change the behaviour in Spring Cloud Stream. Make header matcher case sensitive I need my custom 'Id' kafka header and don't want the 'id' header from the Spring Kafka Streams.
protected static class SimplePatternBasedHeaderMatcher uses toLowerCase() logic in public boolean matchHeader method.
So in the end I got both headers: 'Id' (my header) and 'id' (provided by Spring Cloud Stream).
How to override this behaviour via yaml properties if I don't need caseInsensitive header matcher ?

A: You can't do it just in YAML, you would have to create a custom header mapper bean and provide it's name in the YAML.
https://docs.spring.io/spring-cloud-stream-binder-kafka/docs/3.1.3/reference/html/spring-cloud-stream-binder-kafka.html#_kafka_binder_properties

spring.cloud.stream.kafka.binder.headerMapperBeanName

The bean name of a KafkaHeaderMapper used for mapping spring-messaging headers to and from Kafka headers.


text:
Q: Select one row from first table then join multiple I have the following tables,
clients
client_id | client_name
2         | client 1
3         | client 2
4         | client 3

press releases
press_release_id | date                  | title                 | client_id
1                | 2012-10-16 00:00:00   | new press release     | 3
2                | 2012-10-16 00:00:00   | worlwide news         | 2

press release content
press_release_id | content | translation
1                | content | en
2                | content | fr

I want to write a query that basically selects the latest press release for each client. The list will only return 1 client for each press release
Thanks a million

A: Try this:
SELECT
  c.client_name,
  pr.date,
  pr.title,
  pc.content,
  pc.translation
FROM clients c
INNER JOIN pressreleases pr ON c.client_id = pr.client_id
INNER JOIN
(
   SELECT
     press_release_id, MAX(date) LatestDate
   FROM pressreleases
   GROUP BY press_relaese_id
) pl ON pr.press_release_id = pl.press_release_id AND pr.date = pl.latestdate
INNER JOIN press releasecontent pc ON pr.press_release_id = pc.press_release_id

A: SELECT  a.*, b.*, d.*
FROM    clients a
        INNER JOIN pressReleases b
            ON a.client_ID = b.client_ID
        INNER JOIN
        (
            SELECT client_ID, MAX(date) maxDate
            FROM pressReleases
            GROUP BY client_ID
        ) c ON b.date = c.mAxDate AND
                b.client_ID = c.client_ID
        INNER JOIN pressReleaseContent d
            ON b.press_release_id = d.press_release_id

*

*SQLFiddle Demo (schema may be different but they have he same thought)

*Previous Answer (browse for maximum record for each entry)


text:
Q: Display multiple lists in SenchaTouch2 I have some JSON data, something like this
category:Fruits
 item:Banana
 item:Apple
 item:Peach
category:Vegetables
 item:Cucumber
 item:Tomato

And for this data I want to display 2 lists with vbox layout, like this
|  Friuts  |   Vegetables  |
----------------------------
|  Banana  |   Cucumber    |
|   Apple  |    Tomato     |
|   Peach  |               |

Of course, the data is getting from the server and lists count and items can vary.

A: I hope you meant HBOX layout here. Just access the JSON data by an Ajax request, access individual list and use setData() function of List to populate the lists with individual category data.


text:
Q: Change color of svg image used as cursor Is there a way to change the fill color of the path of an svg image used as a cursor (like so: cursor: url(cur/play.svg), auto;)?
I don't know the color before i hover the element so it has to be a CSS or a JS solution (i can't just make another svg in advance).

A: No that isn't possible. The CSS cursor rule loads an external resource and can't pass a parameter, nor can an SVG read the color underneath it.
Make a good cursor with a color contrasting fill and line and it should be visible everywhere.

A: If you have option to generate SVG file then it's possible.
Theme Option or something has changed color of cursor then Option will generate your assets SVG regenerate to your own color. Then if you refresh the front then cursor color will be changed.
That's the only way.


text:
Q: Переконвертировать List в объект, используя Java Stream API Имеется ArrayList c такими вот значениями:
{"*","12","24","52","*","35","3","*","3"}

Мне нужно переконвертировать этот лист, чтобы получился массив объектов такого вида ( разделитель *):
{{"12","24","52"},{"35","3"},{"3"}}

Написал эту реализацию не на стримах.
Подскажите, есть ли возможность сделать это на стримах?

A: Можно реализовать примерно следующим способом в два этапа - сначала разобрать исходный поток по спискам (и если под объектом подразумевается список списков, то на этом и остановиться), а потом сконвертировать списки в массивы:
List<String> list = Arrays.asList("*", "12", "24", "52", "*", "35", "3", "*", "3");

List<List<String>> lists = list.stream().collect(
    ArrayList::new,
    (l, s) -> {
        if (s.equals("*"))
            l.add(new ArrayList<>());
        else
            l.get(l.size() - 1).add(s);
    },
    ArrayList::addAll
);

String[][] strings = lists.stream()
    .map(l -> l.toArray(new String[l.size()]))
    .toArray(String[][]::new);

System.out.println(Arrays.deepToString(strings));

// out: [[12, 24, 52], [35, 3], [3]]

Только зачем?


text:
Q: Eventarc Audit Log Scope Limited to Current Project In GCP, I have a log sink which centralizes logs onto a GCP Project. I also have an EventArc trigger that listens for Cloud Resource Manager events, specifically the createProject method

Are Eventarc triggers limited to only the current projects logs? Or can it access all logs from all logs bucket in a GCP Project
The logs show up in Cloud Logging (only when I set the scope to include all buckets and not limit it to the current project), however no Eventarc triggers are generated off of this.

Is this a limitation of Eventarc or am I missing something here?

A: Since the createProject method is among the very first logs that gets generated in a newly created project, EventArc triggers will NOT pick them up since the trigger would have to be created after the project has been created.
Triggers might take a few minutes to become active before they can process logs.
In my case, I was able to create a Logs Router at an organization / folder level to overcome this issue, the Logs Router would include all child elements and would capture specific logs from the Cloud Resource Manager.


text:
Q: Using java scanner Im sorry if this seems newbish, but i know we all gotta start some where.. its stopping me from putting the users data after dessert , well before it...this is an edit question
package scanners;
import java.util.Scanner;
public class usingscanners {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    String userName;
    int age;
    String dessert;

    System.out.println("Hi What is your name? ");

     userName = sc.nextLine();

    System.out.println ("How are you doing, " + userName + "?");
    System.out.println ("What is you age, " + userName + "?");

    age = sc.nextInt();

    System.out.println ("Hello, " + userName +  " you are " + age);

    System.out.println ("ok, " + userName + " .Your are " + age + "." + " What is your favorite dessert?");

    dessert = sc.nextLine();

    System.out.println (" Hello, " + userName + "You are " + age + " and your favorite dessert is " + dessert);

}

}

A: age is an integer, use age = sc.nextInt();


text:
Q: in r dplyr select the first observation by group and create a list I would like to select the first observation be group and create a list column.
For example:
df <- structure(list(Grp = c("A", "A", "A", "B", "B"), col1 = c(1,
2, 3, 70, 80), col2 = c(4, 5, 6, 100, 110)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -5L))

I would like to create a column whose first element is c(1,4) and second element is c(70, 100).
I tried:
df %>% group_by(Grp) %>% mutate(L = list(slice(1)))

But got an error.

A: A possible solution:
library(dplyr)

df %>%
  group_by(Grp) %>% mutate(L = list(c(first(col1), first(col2)))) %>%
  ungroup

#> # A tibble: 5 × 4
#>   Grp    col1  col2 L
#>   <chr> <dbl> <dbl> <list>
#> 1 A         1     4 <dbl [2]>
#> 2 A         2     5 <dbl [2]>
#> 3 A         3     6 <dbl [2]>
#> 4 B        70   100 <dbl [2]>
#> 5 B        80   110 <dbl [2]>

A: We could use the index:
library(dplyr)

df %>%
  group_by(Grp) %>%
  mutate(New_col = list(c(col1[1], col2[1]))) %>%
  ungroup()

  Grp    col1  col2 New_col
  <chr> <dbl> <dbl> <list>
1 A         1     4 <dbl [2]>
2 A         2     5 <dbl [2]>
3 A         3     6 <dbl [2]>
4 B        70   100 <dbl [2]>
5 B        80   110 <dbl [2]>

OR maybe:
df %>%
  group_by(Grp) %>%
  mutate(New_col = toString(c(col1[1], col2[1]))) %>%
  ungroup()

  Grp    col1  col2 New_col
  <chr> <dbl> <dbl> <chr>
1 A         1     4 1, 4
2 A         2     5 1, 4
3 A         3     6 1, 4
4 B        70   100 70, 100
5 B        80   110 70, 100

A: You may use slice as -
library(dplyr)

df %>%
  group_by(Grp) %>%
  mutate(L = list(slice(cur_data(), 1))) %>%
  ungroup

#  Grp    col1  col2 L
#  <chr> <dbl> <dbl> <list>
#1 A         1     4 <tibble [1 × 2]>
#2 A         2     5 <tibble [1 × 2]>
#3 A         3     6 <tibble [1 × 2]>
#4 B        70   100 <tibble [1 × 2]>
#5 B        80   110 <tibble [1 × 2]>

As slice returns a dataframe/tibble it is being saved in L column as list.


text:
Q: Is it possible to sibling upwards in 2022? Referring to this Stackover question from 2009 (Is there a "previous sibling" selector?), it seems that it was not possible then.
Here are two small examples that illustrate the problem

*

*both elements touched by the CSS are under the triggering element.

*In example two one Element is above the triggering element and the other remains below it. As a result, the sibling selector does not affect the element on top.

Example one

.toggle-switch {
  padding:50px;
}
#nocheck {
  margin-bottom: 2px;
}

#chkTest:checked ~ #check { color: green; }
#chkTest:checked ~ #nocheck { color: black; }
#check { color: black; }
#nocheck { color: blue; }

      <input type="checkbox" id="chkTest" name="chkTest">

ENABLE

DISABLE

Example 2

.toggle-switch {
  padding:50px;
}
#nocheck {
  margin-bottom: 2px;
}

#chkTest:checked ~ #check { color: green; }
#chkTest:checked ~ #nocheck { color: black; }
#check { color: black; }
#nocheck { color: blue; }

ENABLE

      <input type="checkbox" id="chkTest" name="chkTest">

DISABLE

A: It's the same issue as with a parent selector, CSS can only see DOWN the DOM not back up. As in it can only see future siblings, children, children of children etc.
Safari I think has implemented the :has() pseudo class in one of their dev versions but they are a small browser and Chrome has yet to implement anything.
You might get duped as a few questions on here, this is probably a useful one:
Is there a CSS parent selector?
Kevin Powell has a great video
https://www.youtube.com/watch?v=2-xdcDsqsAs


text:
Q: Pytest: create SparkSession I need to test my Spark project using pytest and I dont understand how to create a Spark Session. I did some research and came up with:
import pytest
import unittest
from pyspark.sql import SparkSession

@pytest.fixture(scope="session")
def spark_session():
    spark = SparkSession.builder.master("local[*]").appName("test").getOrCreate()
    return spark

class Testdb2connection(unittest.TestCase):
    @pytest.mark.usefixtures("spark_session")
    def test_connectdb2(self):
       with self.assertRaises(ValueError):
          return spark_session.format('jdbc')\
          ...

However, when running the test, I get:

'AttributeError: 'function' Object has no attribute 'format'

What am I doing wrong?

A: Looking at Mixing pytest fixtures into unittest.TestCase subclasses using marks, you can define the spark_session with scope class and add the spark session into cls attribute of the request context to be able to use it as attribute in the class using that fixture.
Try with the following modified code:
import pytest
import unittest
from pyspark.sql import SparkSession

@pytest.fixture(scope='class')
def spark_session(request):
    spark = SparkSession.builder.master("local[*]").appName("test").getOrCreate()

    request.addfinalizer(lambda: spark.stop()) # to teardown the session after test

    request.cls.spark = spark

@pytest.mark.usefixtures("spark_session")
class Testdb2connection(unittest.TestCase):

    def test_connectdb2(self):
        assert isinstance(self.spark, SparkSession)

Running the test:
pytest ./mytest.py

.                                        [100%]
1 passed in 4.12s


text:
Q: Postgres using debezium Creation of replication slot failed I configured debezium  with postgres as the below code, when i started my spring boot application a get an error Creation of replication slot failed
@Bean
public io.debezium.config.Configuration connector() {
    return io.debezium.config.Configuration.create()
            .with(EmbeddedEngine.CONNECTOR_CLASS, PostgresConnector.class)
            .with(EmbeddedEngine.OFFSET_STORAGE,  FileOffsetBackingStore.class)
            .with(EmbeddedEngine.OFFSET_STORAGE_FILE_FILENAME, "offset.dat")
            .with(EmbeddedEngine.OFFSET_FLUSH_INTERVAL_MS, 60000)
            .with("name", "test-postgres-connector")
            .with(RelationalDatabaseConnectorConfig.SERVER_NAME, "172.26.113.123:5455-test")
            .with(RelationalDatabaseConnectorConfig.HOSTNAME, "172.26.113.123")
            .with(RelationalDatabaseConnectorConfig.PORT, "5455")
            .with(RelationalDatabaseConnectorConfig.USER, "test")
            .with(RelationalDatabaseConnectorConfig.PASSWORD, "test")
            .with(RelationalDatabaseConnectorConfig.DATABASE_NAME, "test")
            .with(RelationalDatabaseConnectorConfig.TABLE_INCLUDE_LIST, "question").build();
}

2021-04-02 12:58:56.817 ERROR 14672 --- [pool-5-thread-1] io.debezium.embedded.EmbeddedEngine      : Unable to initialize and start connector's task class 'io.debezium.connector.postgresql.PostgresConnectorTask' with config: {name=student-postgres-connector, connector.class=io.debezium.connector.postgresql.PostgresConnector, database.port=5455, offset.storage=org.apache.kafka.connect.storage.FileOffsetBackingStore, table.include.list=question, database.user=pfe, database.hostname=172.26.113.123, offset.storage.file.filename=offset.dat, database.password=********, offset.flush.interval.ms=60000, database.server.name=172.26.113.123:5455-pfe, database.dbname=pfe}

io.debezium.DebeziumException: Creation of replication slot failed
    at io.debezium.connector.postgresql.PostgresConnectorTask.start(PostgresConnectorTask.java:134) ~[debezium-connector-postgres-1.4.2.Final.jar:1.4.2.Final]
    at io.debezium.connector.common.BaseSourceTask.start(BaseSourceTask.java:106) ~[debezium-core-1.4.2.Final.jar:1.4.2.Final]
    at io.debezium.embedded.EmbeddedEngine.run(EmbeddedEngine.java:758) ~[debezium-embedded-1.4.2.Final.jar:1.4.2.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_232]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_232]
    at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_232]
Caused by: org.postgresql.util.PSQLException: ERROR: logical decoding requires wal_level >= logical
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:307) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:293) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:270) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:266) ~[postgresql-42.2.5.jar:42.2.5]
    at io.debezium.connector.postgresql.connection.PostgresReplicationConnection.createReplicationSlot(PostgresReplicationConnection.java:352) ~[debezium-connector-postgres-1.4.2.Final.jar:1.4.2.Final]
    at io.debezium.connector.postgresql.PostgresConnectorTask.start(PostgresConnectorTask.java:127) ~[debezium-connector-postgres-1.4.2.Final.jar:1.4.2.Final]
    ... 5 common frames omitted

A: Looks like you postgres instance uses a wal_level other than logical.
Debezium requires wal_level logical:
https://www.postgresql.org/docs/9.6/runtime-config-wal.html
Take a look inside the postgres connector at the class:
io.debezium.connector.postgresql.PostgresConnector.java


text:
Q: GUI file compressors What GUI file compressors are available for Ubuntu ?
I prefer one that offers LZMA2 to speed up file compression since I have multiple cores.
Thanks.

A: File Roller is Ubuntu's default application for handling the creation, modification and extraction of archives.
To launch it by itself, press Alt+F2 and type file-roller.
The following archive formats are well supported, and installed by default in File Roller:
tar - gzip - bzip - bzip2 - LZMA - zip - jar - iso


text:
Q: How to include a PHP page to another page's div? I want that only my website's content change and the header and footer to be in a fixed position. I read very much about it, but I can't find a solution.
I've made an include() for the header and footer, and the site's content comes into a
.
But I can't handle the PHP codes inside the div. I have a login system and when I include the PHP file, before and after login contents can be seen at the same time.
What's wrong with my code?
index.php

<?php include("header.php"); ?>

<?php include("footer.php"); ?>

change.php
<?php
header("Content-Type: text/plan; charset=utf-8");
$page = '';
$pg = isset($_GET['menuID']) ? $_GET['menuID'] : 'h10';
switch ($pg) {
  case "h10":
    $page = 'about.php';
    break;
  case "h11":
    $page = 'contact.php';
    break;
  default:
    $page = about.php';
}
echo file_get_contents($page);
?>

A: change echo file_get_contents($page); to include $page;


text:
Q: postgrator return invalid pattern errror I have tried to setup a data migration service using postgrator version 7.1.0. I have the following code
import Postgrator from "postgrator";
import pg from "pg";
import { dirname } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));

async function doMigration() {
  // Create a client of your choice
  const client = new pg.Client({
    host: "0.0.0.1",
    port: 9075,
    database: "test",
    user: "test",
    password: "!testPwd",
  });

  try {
    // Establish a database connection
    await client.connect();

    // Create postgrator instance
    const postgrator = new Postgrator({
    migrationDirectory: __dirname + '/migration-scripts',
    driver: "pg",
    database: "test",
    schemaTable: "migration_version",
    execQuery: (query) => client.query(query),
    });

    await postgrator.migrate();
    console.log("schema migration completed successfully")
  } catch (error) {
    console.error(error);
  }

  // Once done migrating, close your connection.
  await client.end();
}
doMigration();

But I got an error when running the above code
TypeError: invalid pattern


text:
Q: Calculate DC motor frequency I am driving a DC motor with H-Bridge Mosfet using PWM.
The problem is I don't know exactly which frequency should I use.
1- Do the DC Motors have a very specific frequency for their best performance at all or they have a range of the frequencies they are able to work with?
2- What happen if I work with a DC Motor with Higher or Lower frequency that it can work with? Am I damaging that?
(Because I have done that and with higher frequency my Motor make a strange noise like zzzz and with lower frequency it is shaking)

A: *

*The PWM frequency supplied to a (presumably) brushed DC motor needs to be high enough that the combination of mechanical inertia and inductance of the coils is sufficient to smooth out the mechanical impulses of each pulse. This minimum would differ from motor to motor. Too low a frequency, and the motor motion will be perceived as a series of jerks, or a rattle.

*The frequency needs to be not so high that the switching device (MOSFET, other) and connecting wiring do not waste significant power in switching losses. Too high a frequency, and the efficiency will drop. This maximum would differ depending on the switching mechanism, the length of wires to the motor, the drive voltage (higher voltage = slew-rate limitations), shielding, perhaps some other factors too.

*The frequency should, if possible, avoid the audio spectrum: below 20 Hz (not a good idea except for really massive motors) or above 20 KHz, so that the magnetostrictive vibration in windings or sympathetic vibration in the mechanical rotor, will not be heard by humans.

*In addition to all of this, a specific motor + load + mounting combination will have a resonant frequency at a given temperature. While this is likely to be not as high as the 20 KHz+ applied for typical motor PWM, certain types of rigid mounting can indeed reach ultrasonic resonant frequencies. If the PWM frequency matches the resonant frequency, resonant oscillations can cause the motor to vibrate uncontrollably. This is why rubber / nylon / elastomer buffers are commonly applied for motor mountings.
This last issue is somewhat self-curing though, since after a bit of resonant oscillation the mounting tends to give / wear, even if it is rigid metallic mounting, and this changes the resonant frequency.

A: At minimum, you need to use a frequency so that the motor "sees" the average and doesn't react to individual pulses.  That is usually a few 100 Hz.
However, there are other effects that the motor doesn't care about but you might.  Individual sections of wire in the windings may vibrate slightly with the PWM frequency, which causes audible whine.  This is why a lot of motors are driven at around 25 kHz PWM, since that is above most people's hearing.  25 kHz means 40 µs pulses, which is still long enough that switching losses are small for most well designed circuits.


text:
Q: Pass reactives to flexdashboard I have a large Shiny app, and I would like to provide the possibility to export a flexdashboard report. Thus, I added a downloadHandler which passes certain params to the flexdashboard. The flexdashboard itself should work without being deployed on a server, thus I do not use the runtime: shiny option.
How can I pass reactive values to the flexdashboard? If I do something like params <- list(y = test()), the report creation breaks.
Relevant part of server.R:
test <- reactive({
    [[SOME STUFF]]
})

output$report <- downloadHandler(
  # For PDF output, change this to "report.pdf"
  filename = "report.html",
  content = function(file) {

    # Copy the report file to a temporary directory before processing it, in
    # case we don't have write permissions to the current working dir (which
    # can happen when deployed).
    tempReport <- file.path(tempdir(), "report.Rmd")
    file.copy("report.Rmd", tempReport, overwrite = TRUE)

    # Set up parameters to pass to Rmd document
    params <- list(y = test())

    # Knit the document, passing in the `params` list, and eval it in a
    # child of the global environment (this isolates the code in the document
    # from the code in this app).
    rmarkdown::render(tempReport, output_file = file,
                      params = params,
                      envir = new.env(parent = globalenv())
    )
  }
)

Relevant parts of report.Rmd:
---
title: "Row Orientation"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
params:
  y: NA
---

```{r setup, include=FALSE}
library(flexdashboard)
library(ggiraph)
library(ggplot2)
library(magrittr)
```
Row
-------------------------------------

### Chart 1

```{r}
ggplot(params$y)
```

A: I figured out what was the issue: The reactive I wanted to pass to flexdashboard was not properly created at the time of report creation, and this caused the report creation to break...
Passing reactives works exactly the same way as reporting data.frames:
params <- list(y = test())


text:
Q: C# loops: iterating through an array If I have a loop such as below:
foreach (string pass in new string[] { "pass1", "pass2", "pass3" })
{
 x = pass; //etc
}

does the anonymous string array get created once initially, or recreated once for each pass?
I believe the former, but collegues are convinced this is a bug waiting to happen because they say every iteration of the foreach loop results in a new string array being created.
The VS Disassembly code suggests I am right, but I want to be sure.
The reason we are looking at this is to try to understand a mysterious bug that reports that a collection has been changed whilst iterating over it.

A: If you look in ILSpy, this code is translated into something like
string[] array = new string[]
{
    "pass1",
    "pass2",
    "pass3"
};
for (int i = 0; i < array.Length; i++)
{
    string pass = array[i];
}

so yes, the array is only created once.
However, the best reference to convince your colleagues is probably section 8.8.4 of the C# specification, which will tell you essentially what LazyBerezovsky's answer does.

A: According to Eric Lippert blog and specification, foreach loop is a syntactic sugar for:
{
  IEnumerator<string> e = ((IEnumerable<string>)new string[] { "pass1", "pass2", "pass3" }).GetEnumerator();
   try
   {
     string pass; // OUTSIDE THE ACTUAL LOOP
      while(e.MoveNext())
      {
        pass = (string)e.Current;
        x = pass;
      }
   }
   finally
   {
      if (e != null) ((IDisposable)e).Dispose();
   }
}

As you can see, enumerator is created before loop.
@Rawling correctly pointed, that array treated a little different by compiler. Foreach loop is optimized into for loop with arrays. According to The Internals of C# foreach your code for C# 5 will look like:
string[] tempArray;
string[] array = new string[] { "pass1", "pass2", "pass3" };
tempArray = array;

for (string counter = 0; counter < tempArray.Length; counter++)
{
    string pass = tempArray[counter];
    x = pass;
}

Initialization also happens only once.

A: It is created only once initially.
I tried the suggestion by Ofer Zelig (from the comments)
foreach (DateTime pass in new DateTime[] { DateTime.Now, DateTime.Now, DateTime.Now })
{
    int x = pass.Second; //etc
}

And placed a breakpoint. It will give the same seconds for all 3 iterations even if you wait between iterations.

A: You could test it (plenty of ways to do so, but this is one option):
string pass4 = "pass4";
foreach (string pass in new string[] { "pass1", "pass2", "pass3", pass4 })
{
    pass4="pass5 - oops";
    x = pass; //etc
}

Then see what comes out.
You'll find you're right - its only executed the one time.

A: The example below should answer the question if the array is recreated or not.
        int i = 0;
        int last = 0;

        foreach (int pass in new int[] { i++, i++, i++, i++, i++, i++, i++ })
        {
            if (pass != last)
            {
                throw new Exception("Array is reintialized!");
            }
            last++;
        }

        if (i > 7)
        {
            throw new Exception("Array is reintialized!");
        }


text:
Q: Homology, Cohomology, Euler Number for Non Orientable Manifolds In what follows, by cohomology I will refer to de Rham cohomology. Every manifold $M^m$ of dimension $m$ is assumed to be compact.
For orientable manifold I know the following results

*

*From Poincaré duality: $H_k(M,\mathbb{R}) \simeq H^k(M)$;

*Betti number $b_n$ is the dimension of the torsion-free part of the $n$th homology group and so, also the dimension of $n$th cohomology group;

*Euler characteristic is the alterned sum of the betti numbers:
$$
χ(M)= ∑_{i=0}^m (-1)^ib_i= ∑_{i=0}(-1)^i\dim H^i(M).
$$
I know also that Poincaré duality does not hold, at least in its original version, for non oriented manifold, as well as other results that for orientable manifold are taken for granted. My questions are:

*

*What is the relation between $H^i(M)$ and $H_i(M,\mathbb{R})$ (the last being the torsion-free part of $H(M,\mathbb{Z})$ as a group. By knowing one of the two what can I infer for the other?

*As a consequence, Betti number, defined by the dimension of the torsion-free part of the homology, can also be thought as the dimension of cohomology?

*Is it still true that the alternate sum of dimension of cohomology group yield the Euler characteristic?

I spot these points, computing the $\mathbb{Z}$-Homology, Cohomology, and Euler characteristic of Klein Bottle, Real Projective Plane and Möbius strip, and all these "conjectures" are verified, but I expect that this cannot be the general case.
I found that on books while for the oriented case the web of results is pretty clear, for non oriented cases is not like that. Could you also give me some reference (possibly not too technical since I'm a physicist)?

A: This is more a comment that a answer but it's a bit too long for a comment.
Poincaré duality holds for compact non-oriented manifold,  if you take your coefficient to be $\mathbb Z/2 \mathbb Z$.
This is not very satisfying, and you can improve it with local coefficient. This is not very intuitive but it works. This is called "twisted Poincaré duality". Abstractly, they are defined in the following way : if $M$ is a $\pi = \pi_1(X)$-module, then the homology with local coefficient $M$ is defined as the homology of the complex $ C_n(\tilde X) \otimes_{\mathbb Z \pi} M$. For non-oriented manifold you have a very adapted local system which is simply $\mathbb Z$ as a group, the structure of $\pi$-module given by $\gamma.1 = 1$ if going around $\gamma$ preserves orientation and $-1$ else. We call $\mathbb Z_w$ this local system.
Now (twisted) Poincaré duality can be stated the following way : we have an isomorphism $H^i(X, \mathbb Z) \cong H_{n-i}(X, \mathbb Z_w)$ and $H^i(X, \mathbb Z_w) \cong H_{n-i}(X, \mathbb Z)$ which related homology with local coefficient and cohomology with integer coefficient (and vice-versa). This is the version of Davis and Kirk, page 102.
For having a feeling about all this, you can compute the homology with local coefficient for $\mathbb RP^2$ and verifying this coincide with the cohomology of $\mathbb RP^2$.
Standard references about this are the book of Hatcher, the book of Davis and Kirk. They are probably lectures notes online for more precise statements or improvement of these theorem.