text:
Q: Unhandled Exception: 'package:firebase_auth/src/firebase_auth.dart'   Firebase Phone authentication in flutter,
Phone authentication code was working perfectly for flutter firebase plugins- `firebase_auth: ^0.14.0+5`, `firebase_core: ^0.4.0+9`, `cloud_firestore: ^0.13.0+1

Now updated to- `firebase_auth: ^0.20.0+1`, `firebase_core: ^0.7.0`, `cloud_firestore: ^0.16.0`

its throwing error:

        >     Unhandled Exception: 'package:firebase_auth/src/firebase_auth.dart': Failed assertion: line 633 pos 12: 'codeAutoRetrievalTimeout != null': is not true

My Code

//Firebase Phone auth code
              Future<bool> loginUser(String phone ,BuildContext context) async{
                 FirebaseAuth _auth = FirebaseAuth.instance;
              final prefs = await SharedPreferences.getInstance();
              String name = prefs.getString('roleName');
              final bloc = BlocProvider.of<AppRrgisterationScreenBloc>(context);
              _auth.verifyPhoneNumber(
                  // phoneNumber: phone,
                  phoneNumber: '+91${phone}',
                  timeout: Duration(seconds: 0),
                  verificationCompleted: (AuthCredential credential) async{
                    Navigator.of(context).pop();
                    UserCredential result = await _auth.signInWithCredential(credential);
                    User user = result.user;
                    if(user != null){
                      contactnumberVal=phone;
                      validateAndCreateData(bloc,context);
                    }else{
                      print("Error");
                    }

//This callback would gets called when verification is done automaticlly
                  },
                  verificationFailed: (FirebaseAuthException exception){
                    print(exception);
                  },
                  codeSent: (String verificationId, [int forceResendingToken]){
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (context) {
                          return AlertDialog(
                            title: Text("Please enter the verification code sent to the mobile number and select Confirm",style: TextStyle(
                              fontSize: 16.0,
                            )),
                            content:Form(
                              key: _resetKey,
                              autovalidate: _validate,
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  TextFormField(
                                    keyboardType: TextInputType.number,
                                    controller: verificationcode,
                                  ),
                                ],
                              ),
                            ),
                            actions: <Widget>[
                              showErrorMessageVerificationCode ?
                              Container(
                                  decoration: BoxDecoration(

                                   borderRadius: BorderRadius.circular(80.0)
                                  ),
                                  child: Padding(
                                      padding: EdgeInsets.all(10.0),
                                      child: Text('Code is Requried!',style: TextStyle(color:Color( 0xFFE9140B),fontSize: 16.0),)
                                  )
                              )
                                  : Container(),
                              SizedBox(height: 5.0),
                              FlatButton(
                                child: Text("Cancel"),
                                textColor: Colors.white,
                                color: Color(0xFFE9140B),
                                onPressed:   () => Navigator.pop(context),
                              ),
                              FlatButton(
                                child: Text("Confirm"),
                                textColor: Colors.white,
                                color: Color(0xFFE9140B),
                                onPressed: () async{

                                  final code = verificationcode.text.trim();
                                  AuthCredential credential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: code);

                                   _auth.signInWithCredential();
                                  UserCredential result = await _auth.signInWithCredential(credential).catchError((error) {
                                    print("error");
                                    Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
                                        builder: (context) => MobileAuthFails(names:name,phone:phone,)

                                      ),
                                          ModalRoute.withName(""));

                                  });

  //Role base sign up
                                  User user = result.user;
                                  if(user != null){
                                    contactnumberVal=phone;
                                    SharedPreferences prefs = await SharedPreferences.getInstance();
                                    prefs.setString('reg_number', phone);
                                    prefs.setString('phoneNumber', phone);
                                    validateAndCreateData(bloc,context);

                                    Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
                                        builder: (context) =>
                                            MyAppEligiblity(phone:phone)
                                      // ResetPassword(user: user,)
                                    ),
                                        ModalRoute.withName(""));
                                    prefs.setBool('IsLogin', true);
                                  }
                                  else{
                                    print("error");
                                  }
                                },
                              )

                            ],

                          );
                        }
                    );
                  },

                codeAutoRetrievalTimeout: null,
                  // codeAutoRetrievalTimeout: (String verificationId){
                  //   verificationId = verificationId;
                  //   print(verificationId);
                  //   print("Timout");         }
              );
              }

1.verificationCompleted: Automatic handling of the SMS code on Android devices.
2.verificationFailed: Handle failure events such as invalid phone numbers or whether the SMS quota has been exceeded.
3.codeSent: Handle when a code has been sent to the device from Firebase, used to prompt users to enter the code.
4.codeAutoRetrievalTimeout: Handle a timeout of when automatic SMS code handling fails.

A: You cannot have codeAutoRetrievalTimeout as null. It requires you to pass a function over there. This function is used to perform an action when the Auto code retrieval has timed out. So, if you don't have any use for this function, please put an empty function as follows:
codeAutoRetrievalTimeout: (String verificationId) {}

You can find sample code and other documentation over here it is very helpful.
Also, please ensure that you share your code and error log the next time you have any problems.


text:
Q: Typescript: conditional typecheck with instanceof not working as expected export const initPeer = (t: Chat | Diagnostic, test?: boolean) => {

  // bleep bloop ... code here

  if (test && t instanceof Diagnostic) {
    setupPeerTest(t, p);
  } else if (t instanceof Chat) {
    setupPeer(t, p);
  }
};

this code gives me the TSError. I would have thought that I already forced them to be of one type or another...
src/components/Chat/peer.ts:139:19 - error TS2345: Argument of type 'Chat | Diagnostic' is not assignable to parameter of type 'Diagnostic'.
  Type 'Chat' is missing the following properties from type 'Diagnostic': defaultState, browsers, append, isPassed

139     setupPeerTest(t, p);
                      ~

src/components/Chat/peer.ts:141:15 - error TS2345: Argument of type 'Chat | Diagnostic' is not assignable to parameter of type 'Chat'.
  Type 'Diagnostic' is missing the following properties from type 'Chat': tickTimer, tabDiv, adapter, default, and 28 more.

141     setupPeer(t, p);
                  ~

A:
I would have thought that I already forced them to be of one type or another...

I don't think TypeScript evaluates your logic to that degree. I think you'll need type assertions:
if (test && t instanceof Diagnostic) {
  setupPeerTest(<Diagnostic>t, p);
// -------------^^^^^^^^^^^^
} else if (t instanceof Chat) {
  setupPeer(<Chat>t, p);
// ---------^^^^^^
}

Or
if (test && t instanceof Diagnostic) {
  setupPeerTest(t as Diagnostic, p);
// --------------^^^^^^^^^^^^^^
} else if (t instanceof Chat) {
  setupPeer(t as Chat, p);
// ----------^^^^^^^^
}

Perhaps without the test variable in there it might be able to infer it, but...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting sequential code into parallel I'm trying to understand MapReduce with Spark.
When doing some simple exercises, I have no problems, doing it the sequential way, but when it comes to parallelise my code, I experience difficulties.
Consider the following example:
var = "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts."
k = 10;

for x in range(0, len(var)):
    print(var[0+x:k+x])

It splits a text into shingles of 10 characters (w-shingling).
What would be the right way to "convert" it into parallel code using Spark?
How to code a for loop? Does Spark offer loops anyway?
I just need to understand the whole concept.
PS: I've already read the documentation, I know what RDDs are etc. I just don't know, how to "convert" sequential code into parallel.

A: As you may have read already, Spark has a rich functional API. The RDD operations are classified into transformations and actions, where transformations could be seen as functions that take an RDD and produce an RDD: f(RDD) => RDD and actions as functions that take an RDD and produce some result (Array[T] in case of collect or Unit in case of foreach).
The general idea on how to port a certain algorithm to Spark is to find a way to express said algorithm using the  functional paradigm supported by Spark, by combining transformations and actions to achieve the desired outcome.
Algorithms that depend on a sequence, like the w-shingling above, present a challenge to be parallelized as there's an implicit dependency in the order of the elements that's sometimes difficult to express is such a way that could be operated in different partitions.
In this case, I used indexing as a way to preserve the sequence while making possible to express the algorithm in terms of transformations:
def kShingle(rdd:RDD[Char], n:Int): RDD[Seq[Char]] = {
    def loop(base: RDD[(Long, Seq[Char])], cumm: RDD[(Long, Seq[Char])], i: Int): RDD[Seq[Char]] = {
       if (i<=1) cumm.map(_._2) else {
        val segment =  base.map{case (idx, seq) => (idx-1, seq)}
        loop(segment, cumm.join(segment).map{case (k,(v1,v2)) => (k,v1 ++ v2)}, i-1)
        }
    }
    val seqRdd = rdd.map(char => Seq(char))
    val indexed = seqRdd.zipWithIndex.map(_.swap)

    loop(indexed, indexed, n)
}

Spark-shell Example:
val rdd = sc.parallelize("Floppy Disk")
scala> kShingle(rdd,3).collect
res23: Array[Seq[Char]] = Array(List(F, l, o), List(i, s, k), List(l, o, p), List(o, p, p), List(p, p, y), List(p, y,  ), List(y,  , D), List( , D, i), List(D, i, s))


text:
Q: "Transaction failed" When deploying contract with ob rinkeby I made a project relating to a youtube video and got this issue
When I try to deploy contract ob rinkeby it gives me this error "Error: transaction failed [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ]". I have checked everything many times and it still doesn't work
Part of Javascript file, where is the issue (it stops after "testing 1"
const RandomSVGContract = await ethers.getContractFactory('RandomSVG')
const randomSVG = new ethers.Contract(RandomSVG.address, RandomSVGContract.interface, signer)
let creation_tx = await randomSVG.create({ gasLimit: 7000000, gasPrice: 20000000000, value: '1000000000000000000' })
log(`testing 1`)
let receipt = await creation_tx.wait(1)
log(`testing 2`)
let tokenId = receipt.events[3].topics[2]
log(`testing 3`)
log(`You have made your NFT! This is token number ${tokenId.toString()}`)
log(`Lets wait for the ChainLink node to respond...`)

Solidity function that I try to call
function create() public payable returns (bytes32 requestId) {
    require(msg.value >= price, "need to send more eth");
    requestId = requestRandomness(keyHash, fee);
    requestIdToSender[requestId] = msg.sender;
    uint256 tokenId = tokenCounter;
    requestIdToTokenId[requestId] = tokenId;
    tokenCounter = tokenCounter + 1;
    emit requestedRandomSVG(requestId, tokenId);
}

It's interesting, but it is easily deploying on localnet, but doesn't deploy ob rinkeby


text:
Q: How to pull a git branch without checking it out? I have 2 branches in a repository (release + dev) that I work regularly on. However, when switching between branches it triggers a long build in my project (I'm talking about ~30mins) so I'd rather avoid to switch between them. In order to work in both I created 2 copies of my repository and that works fine.
However, when I want to merge the changes I need to make the release branch active for a moment to pull changes. Then I can switch back to develop, do the merge and commit. However, as I wrote above this switch will cause a long rebuild. Is there another way to pull a branch without first making it active?

A: You can fetch remote changes. This will download all changes from the remote repository but will do nothing more. But if you want to merge branch A into branch B you cannot do that without checking out B before.
git pull is nothing more than a git fetch combined with a git merge

A: If you want to pull a branch in a remote repository, into your current branch, you do not need to switch.
If I understand correctly, you have one repo with release checked out, and another with dev checked out, in which you are working. When you're done with something in dev, you want to merge it in release, without a checkout of release.
I suppose that you have remotes setup in both repos, so that both can refer to each other.
cd to your release repo. Fetch the changes from the dev repo:
git fetch <dev_remote> <branch>

You now have an updated dev branch in your release repo, although you did not need to check it out. Note however that the name of the updated dev branch contains: the name of the remote, a slash, then the name of the branch. It's a remote branch, it shows in two colors in gitk, and as remotes/<remote_name>/<branch> with git branch -a.
Merge the updated branch to your local release branch:
git merge <dev_remote>/<branch>

And there you have it. No checkout, but your release branch in your release repo has merged the content of dev.
This is for the principle. Now you can do this in one step instead:
cd <release_repo> # you are on the release branch
git pull <dev_remote> <branch_name_in_dev_remote>

Your branch in dev_remote will be fetched, and merged into your currently checked out branch in the release repo.

Likewise, you'll want to update your dev repo with the new merge commit in release:
cd <dev_repo> # you are on the dev branch
git pull <release_remote> <branch_name_to_pull>

A: I ended up with another copy of my repository just for merges. Since no build is going on in this folder I can switch between branches without trouble. Once all merges are done and pushed I can then pull them in the individual work folders.


text:
Q: Responsive iFrames with Image Only I'm currently working on a project for a class at school where I'm setting up a webpage to mimic a chatroom. I have a sidebar for users in the chatroom and the chatroom itself, which are both iframes with images contained within them. I want the iframes to be responsive; as the viewport size changes, i'd like the iframe and the image within it to resize as well.
I currently have both iframes floated to the left and added some spacing to make it look more chatroom-esque. I've visited the following link: Scale iFrame css width 100% like an image, however this is different than what I'm trying to do bc their using an embeded video, not a scrolling image. Anyone have a fix for this? I've been messing around with styles... check out the webpage at www.westerosnet.jaylaiche.com.
Additionally, here's HTML and CSS:

        <meta charset=utf-8 />
        <title>Welcome to Westeros.Net</title>
        <link rel="stylesheet" type="text/css" media="screen" href="style.css" />

Welcome to Westeros.net

Your source for virtual strategy, betrayal, and more!

To learn the real events of this scene, click here.

Page created by Jay Laiche for Traci Gardner's ENGL 3844 Remixing A Story.

CSS:
    body {
    background-color: #cccccc;
}

iframe {
    overflow: scroll;
    height: 800px;
    float: left;
    border: 1px dotted #330099;
    position: relative;
    max-width: 100%;
    display: block;
}

#room {
    margin-left: 5%;
    width: 600px;
}

.container {
    margin-left: 10%;
    margin-bottom: 50px;
    max-width: 100%;
    overflow: auto;
    -webkit-overflow-scrolling:touch;
    position: relative;
}


text:
Q: VS 2013 in debug mode opens full screen file browser After normal behaviour so far after a recent Win 10 upgrade earlier today one of my wpf projects has started to open the file browser in full screen mode when running in debug.  The minimise and restore down buttons are missing and it is not possible to change the window size using the resizing handles.
No changes have been made to the code that opens the file browser and it has been running with no issues in this and similar projects.
Of course it doesn't affect the functionality but is a real nuisance as it obscures all other open windows on a large monitor.
So far as I can tell this only happens is VS 2013 in debug mode.


text:
Q: Does this noun phrase denote the result of the verb?
"I think I'll be a clown when I get grown," said Dill.  Jem and
  I stopped in our tracks.  'Yes sir, a clown," he said. "There
  ain't one thing in this world I can do about folks except laugh, so
  I'm gonna join the circus and laugh my head off." (Harper
  Lee, To Kill A Mockingbird)

Is 'my head off' the result of the action of 'laugh'?

A: Laugh my head off is an idiom, and it means "to laugh very loudly and for a long time."

A: As Kiamaluno points out, "Laugh <one's> head off" is an idiom.  It can be grammatically parsed as follows:

I'm gonna… laugh my head off.
  [I am going to]… laugh [so hard that] my head [falls] off [of my body].

"my head" is the direct object of the verb "laugh".  "off" is a preposition, which describes where "my head" goes.


text:
Q: helm sentry created additional load balancer I using Kubernetes on Digitalocean and I have installed nginx-ingress which created an external load balancer. However when I install Sentry using helm https://github.com/helm/charts/tree/master/stable/sentry another load balancer was created. Oddly though sentry is only accessible through the nginx load balancer, i.e if I point my domain to the ip address of the load balancer created in the Sentry install it does load.
I new to kubernetes so pretty sure I've done something wrong when
installing Sentry and assume it will relate to the values I used when installing the chart as it has a Service type of LoadBalancer.
So my question is can I get rid of the loadbalancer created by Sentry and what's the best way to do it with breaking anything.
# Name of the service and what port to expose on the pod
# Don't change these unless you know what you're doing
service:
  name: sentry
  type: LoadBalancer
  externalPort: 9000
  internalPort: 9000
  ## External IP addresses of service
  ## Default: nil
  ##
  # externalIPs:
  # - 192.168.0.1

## Configure ingress resource that allow you to access the
## Sentry installation. Set up the URL
## ref: http://kubernetes.io/docs/user-guide/ingress/
##
ingress:
  enabled: true
  hostname: sentry.mydomain.com

  ## Ingress annotations
  ##
  annotations:
    kubernetes.io/ingress.class: nginx
    certmanager.k8s.io/cluster-issuer: letsencrypt-prod

  ## Ingress TLS configuration
  ## Secrets must be manually created in the namespace
  ##
  tls:
    - secretName: sentry-mydomain-crt
      hosts:
        - sentry.mydomain.com

A: Yes you can set the type of the service in the values file to ClusterIP.
The values file inside the chart defaults to LoadBalancer type (https://github.com/helm/charts/blob/master/stable/sentry/values.yaml) but you can override this by setting it to ClusterIP in your values file that you deploy with or by using '--set service.type=ClusterIP' as a parameter.
Then it will only be exposed through the Ingress and won't have an external LoadBalancer. See Ingress service type
Since you've already installed sentry you will want to find its release name (you'll see it as a prefix on the sentry resources from 'kubectl get' commands like 'kubectl get pod' or from 'helm list'). If you are using it then you'll want to do a 'helm upgrade'. If you aren't using it yet then you could do 'helm delete' on that release and install it again.

A: Use a ClusterIP service type instead of a LoadBalancer one:
service:
  name: sentry
  type: ClusterIP


text:
Q: Why do these values not equal each other? var student = new Object();
student.classes = ["Digital Photography","Chemistry I","Art of Film","Business in Microcomputer Applications","Study Hall","Algebra 2","Careers","Business Math"]

function newStudent(){
    var studentName = document.getElementById("name").value;
    var one = document.getElementById("1").value;
    var two = document.getElementById("2").value;
    var three = document.getElementById("3").value;
    var four = document.getElementById("4").value;
    var five = document.getElementById("5").value;
    var six = document.getElementById("6").value;
    var seven = document.getElementById("7").value;
    var eight = document.getElementById("8").value;
    var newStudent = new Object();
    newStudent.name = studentName;
    newStudent.classes = [one, two, three, four, five, six, seven, eight];
    if(student.classes.slice(0,1) == newStudent.classes.slice(0,1)){
        alert('You share first hour with Student');
    } else {
        alert("You have " + newStudent.classes.slice(0,1) + " instead of " + student.classes.slice(0,1));
    }
}

Why, if I input Digital Photography as newStudent's first class does not show the alert telling the user they share that class?
ignore the sloppy code I was tired and now I am tired and confused.

A: In this case student.classes.slice(0,1) you get array with one element, so to get its element use indexer
...
if(student.classes.slice(0,1)[0] == newStudent.classes.slice(0,1)[0]){
...


text:
Q: Dialogflow: Guide user to a specific flow depending on user's age I am trying out some things with Google Dialogflow. The thing I am basically trying to do is ask the user's age. Based on the age, say greater than 50 OR smaller than 50, I want the user to be guided to a specific question for one of the two age groups.
I was looking on the internet for a hint or suggestion, but I can't find examples other than "Yes","No" type of answers which then guide the user to a specific flow.
I basically need the user to say an age, which can be between 1-50 years, and 50-100 years, and any number belonging to any of the two groups should prompt the user to a specific follow-up question for that age group.
Does any one have a tip? Is this even possible in the generic Google Dialogflow? Or would I need to use a webhook/fullfilment for this?
Thanks and regards

A: The easiest way is to use fulfillment for this sort of thing. Dialogflow Intents are good at capturing what the user has said, and possibly including this as a parameter, but webhooks are best for applying logic and determining output and what context further answers should be considered in.


text:
Q: How to add together numbers from a random number generator I am making a random number generator for school and I have to add the total all together, but the problem is I used a loop so I don't actually have the randomly generated numbers stored anywhere so I'm not quite sure what how to create a total. Like if the random number generator came out with 3 and 3 the total would tell you it was 6. Here's my code:
import java.util.Scanner;
import java.util.Random;

public class Assignment7 {

    public static void main(String[] args) {

        Scanner key = new Scanner(System.in);
        Random rand = new Random();

        int randomNumber = 0;

        System.out.println("Welcome to randomdiceroll.com or something!"
                         + "\nPlease enter how many dice you'd like to roll.");
        int amount = key.nextInt();

        System.out.println("Please enter the range for the di(c)e from 1-?");
        int limit = key.nextInt();

        for(int i = 0; i < amount; i++) {
            randomNumber = rand.nextInt(limit) +1;
            System.out.println(randomNumber);
        }

        int total; //The part I cant figure out

        System.out.println("\nYour total is..." + total + ".");

        key.close();
    }
}

Excuse the horrible formatting, I've tried:
randomNumber * amount

But that obviously didn't work. I'm using Java If I explained this weird I can clarify for sure! I'm sure the answer is insanely simple but I am a beginner and sadly don't know.
Thank you in advance!

A: You could just add the random numbers inside the loop.
int total=0;
for(int i=0; i<amount; i++){
    int randomNumber = rand.nextInt(limit) +1;
    total += randomNumber;
    System.out.println(randomNumber);
}

A: Define the total before the for loop and add every time the random number to the total.
I would do it this way:
import java.util.Scanner;
import java.util.Random;

public class Assignment7 {
  public static void main(String[] args) {
    Scanner key = new Scanner(System.in);
    Random rand = new Random();
    System.out.println("Welcome to randomdiceroll.com or something!"
                         + "\nPlease enter how many dice you'd like to roll.");
    int amount = key.nextInt();

    System.out.println("Please enter the range for the di(c)e from 1-?");
    int limit = key.nextInt();
    int total = 0;
    for(int i = 0; i < amount; i++) {
      randomNumber = rand.nextInt(limit) +1;
      total += randomNumber;
      System.out.println(randomNumber);
    }
    System.out.println("\nYour total is..." + total + ".");
    key.close()
  }
}


text:
Q: Determine clicked object in a scrollView? I have populated a vertical scroll view with a potentially long vertical linear layout consisting of "profiles" present on the device, like so:
for (Profile profile : Profiles) {
    LayoutInflater inflater = getLayoutInflater();
    View profileCard = inflater.inflate(R.layout.selector, null);

    ...

    profileList.addView(profileCard);
}

In the selector layout, I have provided an onClick method: so if you click on one of the profiles, the onClick method gets run. However, I want to specifically select that particular profile: how can I return the value of which element was clicked in the scrollView?

A: Do this way
for (final Profile profile : Profiles) {
            LayoutInflater inflater = getLayoutInflater();
            View profileCard = inflater.inflate(R.layout.selector, null);

            /*
             *your code
             */

            profileCard.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Profile clickdProfile = profile;

                }
            });

            profileList.addView(profileCard);
        }

NOTE : Do not provide onclick in layout file.


text:
Q: Insert query crashes? <?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$title = $_REQUEST['TitleFieldToAdd'];
$thread = $_REQUEST['ThreadFieldToAdd'];
$file_content = file_get_contents($_FILES['files']['tmp_name'][0]);
$file_name = $_FILES['files']['name'][0];
$file_size = $_FILES['files']['size'][0];
$file_type = $_FILES['files']['type'][0];
$date = date("Y-m-d");

if(!$link = new mysqli('localhost', 'root', 'root', 'DBFORTEST'))
{
    printf("Connecting To DB Has Failed. Error Msg: %s", mysql_error($link)); exit;
}
$query = "INSERT INTO  `DBFORTEST`.`News` (`id`, `title`, `thread`, `imageContent`, `imageName`, `imageType`, `imageSize`, `date')
          VALUES (NULL ,  '$title',  '$thread', '$file_content', '$file_name', '$file_type', '$file_size', '$date');";

if ($result = mysqli_query($link, $query)) {
echo("SUCCEEDED");
}else
{
    echo("FAILED");
}
?>

I could create a query with blob information to insert... but it doesn't work :(
It seems like mysqli_query() crashes but I cannot find a reason why this is happening.
Is this because the query is way too long?   Because of blob image info?

A: *

*Try not to use mysql keywords as column names. eg 'date' here

*there is syntax error in your query :
thread, imageContent, imageName, imageType, imageSize, `date'
should be with ` instead of '
 `thread`, `imageContent`, `imageName`, `imageType`, `imageSize`, `date`

A: Missed ` of `date) ?
You can use mysqli_error($link) to see the error message.

A: Might be the missing '  in 'date) VALUES

A: try to change into query:
`date

with
`date`


text:
Q: Scraping an url using BeautifulSoup Hello I am beginner in data scraping.
At this case I want to get an url like "https:// . . ." but the result is a list in link variable that contain of all links in web. Here the code below;
import requests
from bs4 import BeautifulSoup
url = 'https://www.detik.com/search/searchall?query=KPK'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
artikel = soup.findAll('div', {'class' : 'list media_rows list-berita'})
p = 1
link = []
for p in artikel:
     s = p.findAll('a', href=True)['href']
     link.append(s)

the result of the code above is getting error such as
TypeError                                 Traceback (most recent call last)
<ipython-input-141-469cb6eabf70> in <module>
3 link = []
4 for p in artikel:
5         s = p.findAll('a', href=True)['href']
6         link.append(s)
TypeError: list indices must be integers or slices, not str

The result is I want to get all links of https:// . . . in <div class = 'list media_rows list-berita' as a list
Thank you in advance.

A: Code:
import requests
from bs4 import BeautifulSoup

url = 'https://www.detik.com/search/searchall?query=KPK'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
articles = soup.findAll('div', {'class' : 'list media_rows list-berita'})
links = []

for article in articles:

    hrefs = article.find_all('a', href=True)
    for href in hrefs:
        links.append(href['href'])

print(links)

Output:
['https://news.detik.com/kolom/d-5609578/bahaya-laten-narasi-kpk-sudah-mati', 'https://news.detik.com/berita/d-5609585/penyuap-nurdin-abdullah-tawarkan-proyek-sulsel-ke-pengusaha-minta-rp-1-m', 'https://news.detik.com/berita/d-5609537/7-gebrakan-ahok-yang-bikin-geger', 'https://news.detik.com/berita/d-5609423/ppp-minta-bkn-jangan-asal-sebut-twk-kpk-dokumen-rahasia',
'https://news.detik.com/berita/d-5609382/mantan-sekjen-nasdem-gugat-pasal-suap-ke-mk-karena-dinilai-multitafsir', 'https://news.detik.com/berita/d-5609381/kpk-gali-informasi-soal-nurdin-abdullah-beli-tanah-pakai-uang-suap', 'https://news.detik.com/berita/d-5609378/hrs-bandingkan-kasus-dengan-pinangki-ary-askhara-tuntutan-ke-saya-gila', 'https://news.detik.com/detiktv/d-5609348/pimpinan-kpk-akhirnya-penuhi-panggilan-komnas-ham', 'https://news.detik.com/berita/d-5609286/wakil-ketua-kpk-nurul-ghufron-penuhi-panggilan-komnas-ham-soal-polemik-twk']

A: There is only one div with the class list media_rows list-berita. So you can use find instead of findAll

*

*Select the div with class name list media_rows list-berita

*Select all the <a> with findAll from the div. This will give you a list of all <a> tags present inside the div

*Iterate over all the <a> from the above list and extract the href.

Here is a working code.
import requests
from bs4 import BeautifulSoup
url = 'https://www.detik.com/search/searchall?query=KPK'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
artikel = soup.find('div', {'class' : 'list media_rows list-berita'})
a_hrefs = artikel.findAll('a')
link = []
for k in a_hrefs:
     link.append(k['href'])

print(link)


text:
Q: Object of type PngImageFile is not JSON serializable I'm trying to do an image overlay. I'm using satellite data to study a phenomenon over Argentina, but I really wanted to use the interactive map through folium. So far, when creating an image, I'm getting an output. But, when I try to overlay the satellite image on to the base map, I'm getting an error message:

Object of type PngImageFile is not JSON serializable

I don't have a clue of how to fix it.
from PIL import Image

fig.savefig('GS.png', transparent=True)

img = Image.open("GS.png")

import folium
from folium import plugins

m = folium.Map(location=[-31.416016, -64.188929],  tiles = 'Stamen Terrain')

folium.raster_layers.ImageOverlay(img,
                     [[ya.min(), xa.min()], [ya.max(), xa.max()]],
                     opacity=0.5).add_to(mapa)

mapa

A: From the documentation for folium.raster_layers.ImageOverlay, the image parameter must be a "string, file or array-like object":

image (string, file or array-like object) – The data you want to draw
  on the map. * If string, it will be written directly in the output
  file. * If file, it's content will be converted as embedded in the
  output file. * If array-like, it will be converted to PNG base64
  string and embedded in the output.

In your code, you passed a PIL Image.
img = Image.open("GS.png")

and an Image is not JSON serializable.
Try passing the path to the image file instead:
import os
img = os.path.abspath("GS.png")

folium.raster_layers.ImageOverlay(
                     img,
                     [[ya.min(), xa.min()], [ya.max(), xa.max()]],
                     opacity=0.5).add_to(mapa)

Or, if you really need the PIL Image, and since you already have numpy (because it's a dependency of folium), you can also convert the Image to a numpy array before passing to ImageOverlay:
img = Image.open("GS.png")

folium.raster_layers.ImageOverlay(
                     numpy.array(img),
                     [[ya.min(), xa.min()], [ya.max(), xa.max()]],
                     opacity=0.5).add_to(mapa)


text:
Q: @font-face doesn't install the font on the system or in the browser? Is it correct that @font-face doesn't install the font on the system or in the browser?
I guess it's really just a temporarily reference so I can safely reference a licensed font via @font-face?

A: It's not about the installation or caching. It's up to license agreement of the font. You can be still guilty if you use licensed font.

A: No, @font-face doesn't install fonts, it just locates them:
W3C font-face


text:
Q: How to include %20 spaces in Google QR code URL after scanning? I'm trying to generate QR code images that contain Google Maps routes. For example, I have the following Google Maps URL:
$encodedmapsurl = https://www.google.nl/maps/dir/De%20Aar%2018,%208253%20PN%20Dronten/De%20Lepelaar%2012,%208251MT%20Dronten/De%20Lepelaar%201,%208251mt%20Dronten/De%20Aar%2018,%208253%20PN%20Dronten/

And I generate the Google Charts QR code like this:
<img src="https://api.qrserver.com/v1/create-qr-code/?data=$encodedmapsurl&size=150x150" />

I end up with the following QR code:

This is fine, however, when I scan the QR code with a mobile application, the result is:

Notice that the URL itself contains %20 for every space in the URL, but the result (after scanning the QR code) does not. This results in an unclickable URL. This behaviour is weird considering some QR code generators do include the %20 in the URL after scanning, such as this one. Is there any way with the Google Charts QR code API to include the %20's in the URL after scanning it? Alternatively I'm also fine with using another PHP library/API that does the job (I couldn't find one). The result should look like this:

A: Try formally encoding it as a url first:
$encodedmapsurl = "https://www.google.nl/maps/dir/De%20Aar%2018,%208253%20PN%20Dronten/De%20Lepelaar%2012,%208251MT%20Dronten/De%20Lepelaar%201,%208251mt%20Dronten/De%20Aar%2018,%208253%20PN%20Dronten/";
$encodedmapsurl = urlencode($encodedmapsurl);

Also, then try also then sending the encoded url to bitly or similar shortener before generating the qr code.
If that still doesn't work, being in Japan I often find special characters leading to many hard-to-find/fix issues (e.g. a 1-bit "%" vs a 2-bit "%" character).  Try using the charset-source (and charset-target) parameter.

A: Only encode once:
$map_url = 'https://www.google.nl/maps/dir/De+Aar+18,+8253+PN+Dronten,+Netherlands/De+Lepelaar+12,+8251+MT+Dronten,+Netherlands/De+Lepelaar+1,+8251+MT+Dronten,+Netherlands/De+Aar+18,+8253+PN+Dronten,+Netherlands/@52.5308376,5.7062268,14z/data=!3m1!4b1!4m25!4m24!1m5!1m1!1s0x47c62a8ab5ae23a5:0x44f1928143db42a1!2m2!1d5.7085273!2d52.5441879!1m5!1m1!1s0x47c62b202ae17a0f:0x1abd001f5225a013!2m2!1d5.7290961!2d52.5190013!1m5!1m1!1s0x47c62b202fc55b65:0x12f835f420fa2676!2m2!1d5.7298615!2d52.5194267!1m5!1m1!1s0x47c62a8ab5ae23a5:0x44f1928143db42a1!2m2!1d5.7085273!2d52.5441879';
$encoded_url = urlencode( $map_url );


text:
Q: Are there differences in graphics between the Xbox 360 and Xbox One? Is there a noticeable graphics and lag difference between Rise of Tomb Raider on the Xbox 360 in comparison to the Xbox One?
I'd rather not buy an Xbox One if I can just play it on the Xbox 360. My concern is the game will will lag significantly in graphically intensive areas. If I am in an intense combat situation, I do not want to put up with the game lagging while I am being shot at.

A: Looks like it's pretty smooth on 360:
Digital Foundry

This time we have the talented bunch at Nixxes taking point on the Xbox 360 port and the results are remarkable. This is the same game that we enjoyed on Xbox One with nips and tucks made in all of the expected places. It lacks much of the visual panache of the next-gen version, but it's still an attractive title and a worthy sequel. It doesn't feel like an afterthought at all - it's a project that has received a lot of care and attention.
In fact, there is a strong argument that in one sense at least, the
  Xbox 360 game is actually more playable than its current-gen sibling.
  On Xbox One, we complained about input latency and its impact on the
  game experience(...) Moving to Xbox 360, we were stunned to discover
  that this same issue does not exist on Microsoft's older console to
  anything like the same extent.
In fact, Rise of the Tomb Raider feels significantly more responsive
  here on Xbox 360

Looks like you chose the correct game NOT to move into next-gen


text:
Q: Google Sheet: Using drop-down and check-boxes (data type: text & True/False) to filter data firstly thanks in advance.
Before posting this, I've searched and tried a few guides from several sources.  However, was to no success in constructing formula string.  Filtering data in Google sheet (GS) using Query + other functions is something new to me and I'm still learning.
Goal:
Use drop-down and 2 types of check-boxes (data type: text & True/False).  User can select one or more checkboxes to filter data.
Problem:
Was not successful to construct formula string to combine drop-down & check-boxes
My GS example was taken from one of the solution which used a simple formula string for check-boxes (data type: True/False) to create filter and hoping I could developed from it.
My Google sheet link
Thanks again!

A: This seems to do what you've asked for.  Try the following formula in E6 of your results sheet.  Or see my tab Answer-GK, which I added to your sheet.
=iferror(if(or(C5:C13),
            QUERY ('Test string DB'!A3:H12, "Select * WHERE "  &
                           IF(B2="","C <>'' "," C = '"&B2&"'") &
                           IF(C5,   " and D matches '" & B5    & "' ",) &
                           IF(C6,   " and D matches '" & B6    & "' ",) &
                           IF(C7,   " and D matches '" & B7    & "' ",) &
                           IF(C8,   " and E matches '" & B8    & "' ",) &
                           IF(C9,   " and E matches '" & B9    & "' ",) &
                           IF(C10,  " and E matches '" & B10   & "' ",) &
                           IF(C11, " and F=TRUE", )            &
                           IF(C12, " and G=TRUE", )            &
                           IF(C13, " and H=TRUE", )),
            QUERY ('Test string DB'!A3:H12,"select * " & if(B2=""," "," where C = '"&B2&"'") ,0)),
  "No results - Reduce your selected criteria")

Something to note.  Since some of your data elementss have dedicated columns, and others are shared columns, it limits what you can filter.  For example, you can't find a campsite that has a beach AND a lake, since your data only allows you to have one or the other element.
The same for access - it can't be both walking and 4WD.  So if you check two or more tickboxes, for either Features or Accessible By, you get no results.  You don't have this issue with Ammenities, since you have a separate column (data element) for each of shower, toilet, and plugpoint.  I hope this makes sense,  I assume that you may want to expand your data structure to allow multiple elements, as you have for Amenities.  The formula would need to be modified in that case.
But otherwise I think it is working as you intended.
Let us know of any issues with this.
UPDATE:
To perhaps improve the appearance, I modified The "TRUE" values to show as "Y", using hidden columns in J to L, and the following formula in M5.  There are also other ways of doing this.
={"Toilet","Shower","Plugpoint";
  arrayformula(if(J6:L,"Y",""))}

This adds the three header labels, then looks through columns J,K,L for TRUE values, and returns them as "Y"s.

A: I am assuming you intended the the Feature and Accessible check boxes to be inclusive and the Amenities to be exclusive. Here is a working example:
https://docs.google.com/spreadsheets/d/1AqQCKRrhTzJyLWldcpeFAv1o4sLvphv3F52VCgpa4rE/edit?usp=sharing
Here is the formula in E6:
=iferror(QUERY(QUERY('Teststring DB'!A3:H12,"select * where C = """&B2&""" AND (D =  """& if(C5 = true,B5,"")&""" OR D = """& if(C6 = true,B6,"")&""" OR D =  """& if(C7 = true,B7,"")&""") OR (E =  """& if(C8 = true,B8,"")&""" OR E = """& if(C9 = true,B9,"")&""" OR E =  """& if(C10 = true,B10,"")&""") ",0),"select * " & if(C11 = true,"where Col6 = true","")&" " & if(C12 = true,if(C11 = true,"AND Col7 = true","where Col7 = true"),"")&" " & if(C13 = true,if(or(C11 = true,C12 = true),"AND Col8 = true","where Col8 = true"),"")&" ",0),QUERY('Teststring DB'!A3:H12))


text:
Q: Invalid App ID facebook, Omniauth rails 5.2.4 When I sign in my app with facebook I am getting the error "Invalid App ID" even I verified my app id and it is correct.
what am I doing wrong in my code?
Here is my code:
devise.rb
config.omniauth :facebook, 'xxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxx', token_params: { parse: :json }

omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
    provider :developer unless Rails.env.production?
    provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET']
end

routes.rb
Rails.application.routes.draw do

root to: 'surveys#index'
resources :surveys

devise_for :users, controllers: {
    sessions: 'users/sessions',
    confirmations: 'confirmations',
    omniauth_callbacks: "users/omniauth_callbacks"
}
end

omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def failure
    redirect_to root_path
  end
end

user.rb
class User < ApplicationRecord
    has_many :surveys
    mount_uploader :avatar, AvatarUploader

    devise :database_authenticatable, :registerable,
    :recoverable, :rememberable, :validatable, :confirmable,
    :omniauthable, omniauth_providers: %i[facebook]

    def self.from_omniauth(auth)
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.email = auth.info.email
        user.password = Devise.friendly_token[0, 20]
        user.first_name = auth.info.first_name   # assuming the user model has a name
        # If you are using confirmable and the provider(s) you use validate emails,
        # uncomment the line below to skip the confirmation emails.
        user.skip_confirmation!
      end
    end

    def self.new_with_session(params, session)
        super.tap do |user|
          if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
            user.email = data["email"] if user.email.blank?
          end
        end
    end
end

Thanks in advance

A: I think you are configuring omniauth two times. You should remove omniauth.rb under config/initializers folder.

Remember that config.omniauth adds omniauth provider middleware to your application. This means you should not add this provider middleware again in config/initializers/omniauth.rb as they'll clash with each other and result in always-failing authentication.

Check Devise wiki on Facebook omniauth for Facebook integration.


text:
Q: How to push SFSafariViewController? 2 strange things happen when I try to push Safari ViewController:

*

*Its adress bar with Done button is placed below my Navigation Bar;

*Delegate method safariViewControllerDidFinish: does not get called when I press back button.
I don't think Apple would approve of this behavoir, so:
Is there a way to push Safari ViewController without these problems?

A: In addition to rckoenes comment the only other option i see is to hide the navigation bar when presenting an SFSafariViewController
import UIKit
import SafariServices

class ViewController: UIViewController {
    @IBAction func openBrowser(sender: AnyObject) {
        let safariViewController = SFSafariViewController(URL: NSURL(string: "http://your.url")!)
        safariViewController.delegate = self

        // hide navigation bar and present safari view controller
        navigationController?.navigationBarHidden = true
        navigationController?.pushViewController(safariViewController, animated: true)
    }
}

extension ViewController: SFSafariViewControllerDelegate {
    func safariViewControllerDidFinish(controller: SFSafariViewController) {
        // pop safari view controller and display navigation bar again
        navigationController?.popViewControllerAnimated(true)
        navigationController?.navigationBarHidden = false
    }
}

A: Do not push a SFSafariViewController with the pushViewController:animated: method, instead, use the presentViewController:animated:completion: method.
The Safari view controller will be presented with a standard push animation.


text:
Q: I have an issue with the on click handler it triggers 3 times and doesn't work in I am starting to get frustrated please it's in JSX I don't know the issue or I might not understand the scopes of react I tried event listener but it also did not work

import "./Navbar.css"
import React from 'react'

function Navbar() {
    function scrolldown(){
        alert("d")
    }
    return (

            home
            Contact us

    )
}

export default Navbar

C

A: In your case onClick={scrolldown()} this means you will call scrolldown() in first render without click. If you want to scroll when html tag clicked then use callback . onClick={() => scrolldown()}
Alo you can do this without js actually. As i understood you want to scroll down to Contact section. Give the id="some-id" to contact elemnt and then use #anchor. e.g. Contact


text:
Q: I'm having trouble running my web app on Apache Tomcat v8.5 I can start the server using the startup.bat command (no app on the server) just fine, but when I add my files to the server in eclipse I get the following stack trace:
    Feb 04, 2019 5:26:55 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/NEASmallScale]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/NEASmallScale]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@67a0c803]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4927)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5062)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@1a62ec62]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:112)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:140)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:724)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:142)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
    ... 12 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInputStream.read(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at sun.misc.IOUtils.readFully(Unknown Source)
    at java.util.jar.JarFile.getBytes(Unknown Source)
    at java.util.jar.JarFile.getManifestFromReference(Unknown Source)
    at java.util.jar.JarFile.getManifest(Unknown Source)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:140)
    ... 13 more

Feb 04, 2019 5:26:55 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:687)
    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 org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/NEASmallScale]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 8 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/NEASmallScale]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@67a0c803]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4927)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5062)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@1a62ec62]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:112)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:140)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:724)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:142)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
    ... 12 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInputStream.read(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at sun.misc.IOUtils.readFully(Unknown Source)
    at java.util.jar.JarFile.getBytes(Unknown Source)
    at java.util.jar.JarFile.getManifestFromReference(Unknown Source)
    at java.util.jar.JarFile.getManifest(Unknown Source)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:140)
    ... 13 more

Feb 04, 2019 5:26:55 PM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:687)
    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 org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 13 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/NEASmallScale]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 8 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/NEASmallScale]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@67a0c803]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4927)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5062)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@1a62ec62]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:112)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:140)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:724)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:142)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
    ... 12 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInputStream.read(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at sun.misc.IOUtils.readFully(Unknown Source)
    at java.util.jar.JarFile.getBytes(Unknown Source)
    at java.util.jar.JarFile.getManifestFromReference(Unknown Source)
    at java.util.jar.JarFile.getManifest(Unknown Source)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:140)
    ... 13 more

I appreciate that many instances of this question are on the site, but I have tried the solutions on those questions to no avail. I am happy to provide additional details as needed.

A: Use the J! button in the Breakpoints view's toolbar and have it break on java.util.zip.ZipExceptions. Then, try to debug your app. Figure out which zip file is causing the problem and replace it.


text:
Q: How ignore/hide/deactivate my policy non-compliance state and get 100% compliance? Below is my policy definition and is correctly working (policy is responsible to assign tags from resource group to resources):
{
  "properties": {
    "displayName": "inheritTags",
    "policyType": "Custom",
    "mode": "Indexed",
    "metadata": {
      "createdBy": "3332dc03-2402-46e3-9098-c7350b0bc8dd",
      "createdOn": "2019-11-25T14:49:57.8136557Z",
      "updatedBy": "3332dc03-2402-46e3-9098-c7350b0bc8dd",
      "updatedOn": "2019-11-26T19:43:48.752452Z"
    },
    "parameters": {},
    "policyRule": {
      "if": {
        "allOf": [
          {
            "value": "[resourceGroup().tags]",
            "exists": "true"
          },
          {
            "value": "[resourceGroup().tags]",
            "notEquals": ""
          }
        ]
      },
      "then": {
        "effect": "modify",
        "details": {
          "operations": [
            {
              "operation": "addOrReplace",
              "field": "tags",
              "value": "[resourceGroup().tags]"
            }
          ],
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ]
        }
      }
    }
  },
  "id": "/subscriptions/78afced4-1c58-4e66-8242-c042890d34c3/providers/Microsoft.Authorization/policyDefinitions/9f2a0e94-5ada-47b0-8125-42464f93cf37",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "9f2a0e94-5ada-47b0-8125-42464f93cf37"
}

Nevertheless in Overview tab on Policy page I have information that assigned policy definition is in Non-compliant state:

Reason for that? Different values due to comparing previous state to expected state and I know that source of "issues" are keywords like exists, notEquals and so on: https://learn.microsoft.com/en-us/azure/governance/policy/how-to/determine-non-compliance#compliance-reasons

How to ignore those compliance messages and get resource compliance, you know tags are correctly assigned so what is the problem? or maybe I have wrong understanding of azure policies?

A: The resources that are coming up as non-compliant is because they do not have the same tags as  the RG. For some resources, modify won't because they don't support tags or don't support updating/adding tags. I can't tell what type of resource it is so I can't say forsure that is the issues. If this is the case that those resources don't support tags, then you can just excluded that resource from the assignment to see the compliance percentage not including those. (Edit the assignment and add an exclusion)


text:
Q: ET1 Enterprise Tablet Motorola Emulator Android Does anyone know if there exists an emulator for the ET1 Enterprise tablets from Motorola? I am currently in need of one, since I need to work on an app.
As far as I can see in the Android-sdk manager there is none available.
Thanks
Rajat

A: ET1 uses version 2.3.4. I don't think you need an specific emulator, just SDK environment to lunch a virtual machine with that version.


text:
Q: iPhone : Does not getting proper output while converting NSString into NSDate I want to convert NSString into NSDate.
So I tried following code :
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];

    NSString *checkInDate = lblCheckIn.text;
    NSString *checkOutDate = lblCheckOut.text;

Here I am getting following output.
    NSLog(@"\nCheckIn Date : %@\nCheckOut Date : %@",checkInDate,checkOutDate);
    // CheckIn Date : 26-10-2011
    // CheckOut Date : 29-10-2011

Now I want to convert this NSString into NSDate with dd-MM-yyyy formate.
    NSDate *checkOut = [formatter dateFromString:checkOutDate];
    NSDate *checkIn = [formatter dateFromString:checkInDate];
    [formatter release];

But I got following output.
    NSLog(@"\nCheck In : %@\nCheck Out : %@",checkIn,checkOut);
    // Check In : 2011-10-25 18:30:00 +000
    // Check Out : 2011-10-28 18:30:00 +000

What could be wrong ?

A: I hope you are in +5:30 timezone..
Nothing wrong with your code. Its only printing the time in GMT timezone.

A: NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[formatter setTimeZone:gmt];
NSString *checkInDate =@"26-10-2011";
NSString *checkOutDate =@"29-10-2011";
NSDate *checkOut = [formatter dateFromString:checkOutDate];
NSDate *checkIn = [formatter dateFromString:checkInDate];

    [formatter release];


text:
Q: Attractive exchange energy and correlation energy of different spin in DFT
*

*In DFT, why do most texts ignore/don't mention the attractive exchange "force" between two antiparallel spins electrons?
The repulsive "exchange" force of two same spins electrons are always mentioned to correct the Coulombic repulsion, which is logical. But books and youtube lectures often ignore the fact that there is an exchange "force" between two antiparallel spins that are attractive. And given that electrons are fermions, with antisymmetric spin wavefunction and symmetric space wavefunction, shouldn't we be emphasizing more on this force?

*Is the correlation energy the Coulombic interaction that was ignored when we were considering the indistinguishability of the two electrons? If so, it should be present in both same spin electrons and different spin electrons, right? In the context of DFT, it seems that we always consider the correlation repulsion of different spin electrons.


text:
Q: Dynamic Input direct from user in console In the following code;
for (int i = 0; i < 5; i++)
        {
            dynamic x;
            x = Console.ReadLine(); //readline methode returns string.
            Console.WriteLine(x.GetType().ToString());
        }

I tried to make a simple concept where the user would like to enter 5 elements of different type data then each time would show up.
the thing is, ReadLine will always return value as string, I can use convert but still, this will force the user to enter the only convert type.
I have been searching but don't really know what to do cause I don't know how to express the question.
Is there is another method that can take input dynamically from user or a property I don't know about.

A: No. There's no other method to accept user inputs from the console. It will always be text/string.
You'll have to parse the inputs from Console.ReadLine() from a string to whatever type you need. Your problem is there's no way of knowing what the type is if you just have a string. If the user input "2" did she mean the number 2 (int) or did she actually mean "2" (string).

A: You can have limited success, but for reasons pointed out in comments, it will be limited to a few primitive types. For example, a float input can't be discriminated between Float32 and Float64
for (int i = 0; i < 5; i++)
{
    var input = Console.ReadLine();

    dynamic x;
    if (int.TryParse(input, out int a))
        x = a;
    else if (float.TryParse(input, out float b))
        x = b;
    else if (input.Length == 1)
        x = input[0];
    else
        x = input;

    Console.WriteLine($"{x}: {x.GetType()}");
}

5
5: System.Int32
6.9
6.9: System.Single
f
f: System.Char
stri
stri: System.String


text:
Q: Error: call super outside of class constructor I try to call parent method but I get error:

Error: call super outside of class constructor

My example :
class xo{
    cool(x){
        console.log(`parent init${x}`)
    }
}
class boo extends xo{
    cool(val){
        super(val);
        console.log(`child init${x}`)
    }
}

x = new boo;

A: Use super.cool(val) instead to call the cool method on the super class. super() invokes the super class' constructor.

A: You call not the parent method, but parent constructor which is not valid call outside of the constructor. You need to use super.cool(val); instead of super(val);
class xo{

    cool(x) {
        console.log(`parent init${x}`)
    }

}

class boo extends xo {

    cool(val) {
        super.cool(val);
        console.log(`child init${x}`)
    }

}

x = new boo();


text:
Q: How to add weight as label to vertex? I want to add weight to the vertex.
I have the first step going in r-studio. The following code gives a dataframe with the weight:
query = "
MATCH (p)-[:REFERS_TO]->(q)<-[:REFERS_TO]-(r)
WHERE (ID(p) < ID(q))
RETURN q.name, COUNT(q) AS Weight
ORDER BY Weight DESC
"
newvalue = cypher(graph, query)

How can the weight be added to the vertex as a label? The following does not work for me because it adds the weight to the node instead of the vertex:
query = "
MATCH (p)-[:REFERS_TO]->(q)<-[:REFERS_TO]-(r)
WITH q.name, COUNT(q) AS Weight
SET q.weight = Weight
"
cypher(graph, query)

Thanks!

A: I think what you're trying to do is to add the weight to the edge (or relationship) rather than to the node (or vertex).
In order to add the weight as a property of the edge, you need to bind it to a variable, and then you can set the property as before:
query = "
MATCH (p)-[r1:REFERS_TO]->(q)<-[r2:REFERS_TO]-(r)
WITH q.name, COUNT(q) AS Weight
SET r1.weight = Weight, r2.weight = Weight
"
cypher(graph, query)

Note I can't tell which of the relationships you want the weight on, so in this example I'm doing both.  The only thing here is I'm binding those two relationships to r1 and r2.  Relationships can have properties just like nodes, so the rest is straightforward.


text:
Q: Question about a confusing sentence structure
The touch of a cluster of leaves revolved it slowly, tracing,
  like the leg of compass, a thin red circle in the water.
  (Context: "It" is a laden mattress that carries the dead body of
  Gastsby and it is moving down the pool.) (Great Gastby, novel by F. Scott Fitzgerald)

I don't understand the structure of this sentence. Is the second part of the sentence a reduced relative clause? or a absoluete phrase? As far as I understand, the second part is defining the action of the "ladden mattress"
after the touch which is "tracing a thin red circle in the water" .


text:
Q: add values to each array in a 2D numpy array I'm looking for a way to efficiently add a fixed number of np.nan values at the beginning of each array in a numpy array of shape (3,123...):
Original numpy array:

[[1,2,3...],
 [4,5,6...],
 [7,8,9...]]

New numpy array:

[[nan,nan,1,2,3...],
 [nan,nan,4,5,6...],
 [nan,nan,7,8,9...]]

I tried with a for loop:
import numpy as np

original_array = np.random.rand(3,3)
gap = np.empty(shape=(2,))
gap.fill(np.nan)
new_array = np.zeros(shape=(3,5))
for i,row in enumerate(original_array):
    new_array[i] = np.concatenate([gap,row])

It works but this is probably not the best way to do it.

A: You could also use np.pad
import numpy as np

original_array = np.arange(1, 10).reshape(-1, 3).astype(np.float32)
npad = ((0, 0), (2, 0))
np.pad(original_array,npad,mode='constant',constant_values=(np.nan))

Output:
array([[nan, nan,  1.,  2.,  3.],
       [nan, nan,  4.,  5.,  6.],
       [nan, nan,  7.,  8.,  9.]], dtype=float32)

A: A possible solution (thanks to @roganjosh for suggesting the use of numpy.full), which is based on numpy.hstack:
a = np.full((3,2), np.nan)
b = np.arange(1, 10).reshape(-1, 3)
np.hstack((a, b))

Output:
array([[nan, nan,  1.,  2.,  3.],
       [nan, nan,  4.,  5.,  6.],
       [nan, nan,  7.,  8.,  9.]])


text:
Q: How can implement mat like numpy in python can batch operations in Android(Java) ? In python, Numpy arrays can be batched to achieve the following functions: keep those data whose fourth dimension is greater than 0.25
note: item's shape = (6300,7)
detects = item[item[..., 4] > 0.25]

But in Android, I hava no idea how to implement the above operation, except using a for loop.


text:
Q: How do I design a database to support OpenID I'm looking into implementing OpenID, but I drawing a blank as to how the database would look with new / existing users. How does stackoverflow do it? I understand the concept that an external site does the authentication for me, but as far as storing user information on my end I need help with.

A:
Since this is one of the top search results when searching for OpenID
  Database Structures on Google, and the Plaxo link referenced in the
  previous answer is no longer around. I've copied and pasted the
  content of the Plaxo instructions below. I was able to get them by
  using the wayback machine page referenced
  here.
  Keep in mind that because of StackOverflow's 30000 character restrictions, I will have to crop certain sections, and Joseph Smarr included some images in his
  instructions, so you might want to look at the wayback machine page I
  referenced.
                     -Jason

A Recipe for OpenID-Enabling Your Site
Prepared by Joseph Smarr at Plaxo on July 18, 2007.
This is a step-by-step tutorial guide for implementing OpenID consumer-side support with a web site that already has users with accounts. It will explain how to easily let new users sign up for an account on your site using their OpenID URL and how to let existing users attach their OpenID(s) so they can sign in using them.
I developed this guide by talking to fellow OpenID developers at the Internet Identity Workshop and elsewhere, and by implementing OpenID support for Plaxo using these instructions. I've also posted detailed screenshots of Plaxo's implementation for reference. I've intended for this guide to be clear and complete and to follow best-practices, but if you have any questions or feedback, please let me know at ob_male('joseph','plaxo.com'); or by posting a comment on Plaxo's blog.
This guide may look a bit long, but my hope is you can just follow it straight through without thinking much, and you'll be completely done by the time you reach the end! :)
Overview
I'm assuming your web site currently has:

*

*A user database with rows for each user

*

*Each user has a unique internal user ID

*Users currently sign in using a username/e-mail and password

*A registration flow for signing up new users and getting collecting basic profile info

*A signin page for authenticating users

*

*Internally you authenticate users based on username/e-mail and password, look up their unique user ID, and use it in the rest of your site

*A settings page for users to manage their account info.

If your site doesn't look like this, you should still be able to follow along, but some of the sections may not be relevant to you.

Snipped.. so check the wayback machine link up above for the rest.

Implementation details

*Install an OpenID consumer library

*

*There are OpenID libraries already available in many popular programming languages that will do almost all of the heavy lifting for you. The team at JanRain wrote a bunch of them and are generally super-smart and knowledgeable when it comes to OpenID, so they'd probably make a good resource if you need help here.

*Depending on the library, you may need to provide a persistent store for associations with OpenID provider sites. Essentially this is just storing a mapping from a server/handle string to an association string. You'll need to store the association at least for the session (to verify an OpenID authentication) but ideally you should store them longer so you won't have to re-associate every time you redirect to the OpenID provider (doing so will result in a faster redirect). You can use memcached, a database, or any other persistent storage medium you have access to.

*Create a new OpenID database table

*

*Use a schema like this (this will work with MySQL, but you may have to tweak it slightly if you use a different database or if you represent your internal user IDs differently): create table user_openids (
  openid_url varchar(255) not null,
  primary key (openid_url),

  user_id int not null,
  index (user_id)
);

*Keep a single global table so you can use it to look up OpenIDs for all your users (even if you have your users partitioned into multiple databases).

*Store OpenID URLs in canonicalized form for robust lookup (i.e. so if users enter their OpenID slightly differently next time, you can still map it to their account). Most OpenID libraries will provide a canonicaliztion function, but briefly you should add http:// if it's missing and you should convert the protocol and domain to lowercase (but NOT the rest of the URL), so e.g. "WWW.AOL.COM/myOpenID" should be stored as "http://www.aol.com/myOpenID". You should also probably remove any trailing slashes from the URL.

*If you usually have a layer of database-access code, you should expose the following functions to your application (in each case I've sketched the SQL to implement the function). As a reminder, all functions that take an OpenID as input should canonicalize it prior to looking it up in the database.

*

*GetUserId(openid_url)select user_id from user_openids where openid_url = openid_url

*GetOpenIDsByUser(user_id)select openid_url from user_openids where user_id = user_id

*AttachOpenID(openid_url, user_id)insert into user_openids values (openid_url, user_id)

*DetachOpenID(openid_url, user_id)delete from user_openids where openid_url = openid_url and user_id = user_id

*DetachOpenIDsByUser(user_id)delete from user_openids where user_id = user_id

*Add OpenID UI to your registration page

*

*Add a section to your registration page where OpenID users can sign up using their OpenID. The UI goal should be that OpenID users can easily identify that your site supports OpenID, but that users without OpenID can continue to register normally without being confused. You can either put an OpenID input box directly on the page or link to an OpenID page where users can enter their OpenID.

*Wherever you put it, you should follow the community standards for naming and styling the text field where users enter their OpenID:

*

*Use "openid_url" as the ID and name attributes of the text field (this will allow plug-ins to easily identify and handle OpenID input boxes across different web sites)

*Add the small OpenID logo as a background image to the text box, using CSS like this:background: #FFFFFF url('/images/openid-icon-small.gif') no-repeat scroll 0pt 50%;
padding-left: 18px;

*It's also a good idea to provide a brief explanation of what OpenID is and how your users can use it on your site (since you'll probably get curious people clicking through to take a look).

*Wrap the OpenID text box in a form that will submit to your OpenID login CGI, which we'll build below.

*Upon providing an OpenID and signing in to the OpenID provider, you'll need to redirect your user back to your registration page with a couple of small tweaks. First, you should show the OpenID that the user is registering with, preferably with the small OpenID logo next to it to consistently identify it as an OpenID (see the screenshots below for an example). Second, you should NOT ask the user for a site-specific password, since they'll be signing in with their OpenID. So hide the password fields and make sure your registration code will allow this (you may need to stick in a random password behind the scenes if your code requires some password text, just don't show it to the user). [Note: it's fine to let users enter a site-specific password later by using your account settings page, but the point here is that one of the major benefits you're providing OpenID users is that they no longer need to maintain separate credentials for each site they use.]

*Here are some screenshots of how we added OpenID to Plaxo's registration flow:

*Add OpenID UI to your signin page

*

*Add a section to your signin page where OpenID users can sign in using their OpenID. This will work both for existing users of your site that have attached an OpenID to their account and new users, who will be able to sign up using their OpenID (using the same flow as above). Like with the registration page, the UI goal should be a balance between being obvious to OpenID users without overly distracting or confusing the rest of your users. You should name and style your OpenID box as specified above in the registration page. And like above, the form surrounding the OpenID input box should go to the OpenID login CGI you're about to build.

*In addition to your main signin page, you may also have signin UI in your home page or elsewhere. You should ideally provide an option to sign in using OpenID in every place you provide a traditional signin option.

*Here are some screenshots of how we added OpenID to Plaxo's signin pages:

*Create a new OpenID login web page / CGI

*

*Your CGI should take two basic input (query) parameters:

*

*openid_url: the OpenID entered by the user (for registration, signin, attaching, etc.)

*action_type: the operation the user wants to perform. Possible values will be login, complete, attach, list, and delete. (If you're using Rails or a similar system, these could also be controller methods and thus part of the URL itself.)

*Implement the login action (this is where the UI you added to the registration and signin flows will both submit to)

*

*Look up the provided openid_url using the GetUserId function described above.

*If the OpenID is already attached to a user in your system, check to see if the user is currently signed in to your site.

*

*If the user is not signed in, they are attempting to sign in as an existing user, so prepare to redirect to their OpenID provider, but set a flag to NOT ask the provider for registration info (since the user is not signing up for a new account).

*If the user is already signed in, and this OpenID already belongs to them (i.e. the OpenID URL is mapped to the same user_id as the currently signed-in user), then you don't have to do anything (this user is already signed in and already attached that OpenID, so this is a no-op). This is an edge case.

*If the user is already signed in but the OpenID belongs to a different user, show an error message saying that this OpenID has already been claimed by another user. You can also provide the user the option to sign out and try again. This is an edge case.

*If the OpenID is NOT currently in your database, the user is trying to sign up for a new account, so prepare to redirect to their OpenID provider and ask for registration info.

*Save the provided openid_url in your session, since you'll need it to remember it when the OpenID provider redirects back to you, and the provider may not return it to you. If you don't have a session, you can use your database, but it has to be somewhere persistent and protected from user-tampering (i.e. not in a cookie or something that could be changed or forged by the user). (The reason you need to store the requested OpenID is that OpenID lets users delegate their OpenID to another provider behind-the-scenes. For instance, if I try to sign up with the OpenID josephsmarr.com, I may have actually delegated that URL to a different OpenID like jsmarr.myopenid.com, and when the provider returns to you to complete authentication, you need to remember that I wanted to sign up as josephsmarr.com and not jsmarr.myopenid.com. Luckily your OpenID library will most likely handle this for you, but you still have to keep the originally requested OpenID in your session for now. This may be solved in the upcoming OpenID 2.0 spec.)

*Construct your return_to URL for the OpenID provider to return to after the user has authenticated. This will be your OpenID login CGI with the complete action specified.

*If you've determined above that the user is registering for a new account, decide what registration info to ask for. Most OpenID providers support the simple-registration extension, which is a list of common registration fields that you can request as required or optional for your site, including full name, e-mail, nickname, gender, date of birth, gender, postal code, country, language, and time zone. If you ask for these fields and the user consents to provide them, you can pre-fill them into your registration flow, thus removing time and friction from your registration process. If your OpenID consumer library doesn't natively support requesting simple-registration parameters, see if they have a general facility for supporting extensions, or worst-case you can manually add it to the generated redirect URL before redirecting.

*Call checkid_setup in your OpenID library to generate the URL to redirect to the user's OpenID provider. Pass in the (canonicalized) OpenID provided by the user and the return_to URL you constructed above. Also pass in the simple registration info you want if appropriate. Depending on your library, you may need to trap and handle some errors from this function. But assuming everything goes well, it will give you back a URL to redirect to.

*Have your CGI redirect to the provided URL, ideally by issuing a server-side redirect response.

*The user will be redirected to their OpenID provider's web site. They will be asked to sign in (unless they've recently signed in there), they will be asked whether they trust your web site, and if you've asked for simple registration info, they'll be asked what info they want to share with you. Once they complete this process, the OpenID provider will redirect the user back to the return_to URL you supplied, which will then let you initiate your complete action to finish the job.Here are some screenshots of signing into an OpenID provider (myopenid.com in this case) and being prompted to share some registration info with Plaxo:

*Implement the complete action (this is where the user gets redirected after signing in to their OpenID provider):

*

*When the OpenID provider redirects to your return_to URL, they will add a bunch of additional query string parameters that contain the information needed to verify the user's authentication with this OpenID. Depending on the OpenID library you're using, you may need to gather these up into a data structure to pass in to the verification function, or it may do it for you.

*Get the OpenID the user initially requested from your session (you stored it before redirecting to the OpenID provider above).

*Call id_res in your OpenID library to verify the authentication data you've been sent by the OpenID provider. Pass in the OpenID that the user initially requested, along with the query parameters as needed. This function will check to see if everything looks valid. If you get an error back, display an appropriate error message to your user. Otherwise you've now confirmed that the user has authenticated the OpenID they provided to you.

*Optional: after successfully verifying the OpenID, you may wish to set a persistent cookie for your site with the OpenID used so that you can recognize that the user has an OpenID next time they come to your site and pre-fill the OpenID box on the signin page. If you do this, make sure to also clear the cookie when the user explicitly signs out.

*Look up the verified OpenID again using the GetUserId function. If you don't find it in your database, check to see if the user is currently signed in on your site. If they are, perform the attach action below to attach this OpenID to their existing account. Otherwise, it's time to start the registration process for a new account using this OpenID. Start by storing the verified OpenID in your session so your account creation code will remember the user has already verified this OpenID. (Do NOT use the same session variable you used to store the requested OpenID, since the user can type in anything there.) Then redirect your user to your registration flow and pass along the simple registration data you got back (if any). You will probably have to map the fields returned by simple-registration to the registration parameters that your site normally takes.

*

*As described above, the registration page should show the OpenID prominently in the account information, and you should NOT ask the user to enter a password for your site, since they'll be using their OpenID to sign in. In addition, you should pre-fill any registration info provided from their OpenID provider. It is fine to ask for additional registration info and maintain your current policies about which fields are required and optional. (Using OpenID should be an acceleration for registering on your site, but should not require you to change what information you require or otherwise change your site's normal behavior). Finally, you should provide a link for existing users of your service to attach this OpenID to their existing account, if they have one. This will handle the case of existing users that weren't signed in and entered their OpenID and have no found themselves in the new-user registration flow. [Since this isn't common, it's better to just have a small link at the beginning of the registration flow rather than asking every user "do you want to register a new account or sign in to an existing account" when they first verify their OpenID.]

*When the user completes your site's registration flow and you create a user account, attach the verified OpenID to the newly created account using your AttachOpenID function. [If your user table and OpenID table are in separate databases and cannot be part of the same transaction, there is a small chance that the attach command could fail and leave you with an orphaned user account. There's no easy way to prevent this in 100% of cases, but since it's rare and the user can always sign up again, in most cases you can ignore this race condition and just hope for the best.

*If you found that the verified OpenID was attached to an existing account, you can now sign the user in as you normally would if they'd signed in through your traditional method. (If the user happens to be signed in to a different account, sign them out and then sign them in as the user the OpenID is attached to, since they just proved they own it).

*Implement the attach action (for existing users to attach additional OpenIDs to their account):

*(This action will be called as part of the complete action when the user is already signed in and has just verified a new OpenID. So make sure the user is signed in before calling this action.)

*Attach the verified OpenID to the signed-in user's account using your AttachOpenID function.

*Show a confirmation message that this OpenID has now been attached and can be used to sign in from now on. Consider redirecting to the list action so the user can now see this OpenID among the list of attached OpenIDs for their account.Here's a screenshot of Plaxo's attach confirmation page:

*Implement the list action (for showing a signed-in user the OpenIDs attached to their account):

*

*Require the user to be signed in (redirect through your signin page first if needed).

*Fetch the list of attached OpenIDs for the signed-in user by calling your GetOpenIDsByUser function.

*Show the list of OpenIDs in a web page with a link by each one to detach it if the user wants. The links will call the delete action below and pass in the OpenID to delete as the openid_url parameter.

*Provide a link or input box to attach an additional OpenID. This will take the user through the login and attach flows (since the user is already signed in) and end up back on the list page.

*If your site already has a general settings page, you should provide a link to "Manage your OpenIDs" that links to this list page. You may also decide to build this functionality directly into your current settings page.Here's a screenshot of Plaxo's list page, as well as links to it from our current settings pages:

*Implement the delete action (for detaching an OpenID from a user's account):

*

*Require the user to be signed in (redirect through your signin page first if needed).

*Optional: Check whether the user is trying to delete the last credential they could use to sign in to your site. If the user has not set up a normal password on your site and this is the only OpenID attached to their account, deleting their last OpenID would essentially lock them out of their account forever. If you don't have a good way to recover users in this situation, show an error message if the user tries to delete their last attached credential, saying essentially "You can't delete the last OpenID attached to your account because you'd have no way to sign in. First attach another OpenID or create a password for this site."

*Assuming it's ok to proceed, detach the OpenID provided by the openid_url parameter from the signed-in user's account by calling your DetachOpenID function. If the OpenID provided is not currently attached to the user's account, you can choose to show an error or just treat it as a no-op success.

*Show a confirmation message that this OpenID has now been detached and can no longer be used to sign in to your site. Tell the user that if they want to re-attach this OpenID, they will have to go through the normal verification process to re-attach it. Consider redirecting to the list action so the user can see the updated list of OpenIDs attached to their account.Here are some screenshots of detaching an OpenID from a Plaxo account:

*Add a hook to your delete-user routine to detach all OpenIDs from that user.

*

*If your site currently lets users delete their accounts, it's important that you also detach any OpenIDs that were attached so they can be re-attached to another account later. You can do this by calling your DetachOpenIDsByUser function inside your delete-user routine, or by otherwise triggering this function when deleting a user.

...and you're done!

Snipped.. so check the wayback machine link up above for the rest. Joseph goes
  through some best practices for OpenID, but at this point you should have a working
  example.