text:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>FRIENDS</title>

FRIENDS

THE ONE WITH RACHEL'S PHONE NUMBER

Directed by: Ben Weiss

  Written by: Mark Kunerth

  Transcript by: David Buehrle

[Scene: Chandler's office in Tulsa.   His assistant is showing him photographs.]

JO LYNN: This kitty is Mittens and this one is Fitzhugh, and this little guy
  in the cat condo is Jinkies.

CHANDLER: Yep.  That's a lot of cats Jo Lynn.  Single are ya?

(Phone rings.  Chandler answers using the speaker phone.)

CHANDLER: Chandler Bing.

JOEY: Hey.  How come you're answering your own phone?  Where's your crazy assistant?

(She frowns.  Chandler picks up the hand set.)

CHANDLER: What's up Joe?

JOEY: Okay, what have we always wanted to do together?

CHANDLER: Braid each other's hair and ride horseback on the beach?

JOEY: No, no, no.  When you get home tomorrow night, you and I are going to
  be at the Wizzards-Knicks game . . .  courtside!

CHANDLER: Courtside?  Oh my God.

JOEY: Yeah.  Maybe Michael Jordon will dive for the ball and break my jaw with
  his knee.

CHANDLER: That's so cool.  I'll let Monica know.

(Chandler hangs up and calls Monica who is reading a book on their sofa as
  the phone rings.)

MONICA: Hello?

CHANDLER: Joey just called.  He's got courtside Knicks tickets for him and
  me tomorrow night.

MONICA: Really?  But tomorrow night is the only night I get off from the restaurant.
  If you go to the game, we won't have a night together for another week.

CHANDLER: But hey, it's courtside.  The cheerleaders are going to be right
  in fr. . . (Pause)  That's not the way to convince you.

MONICA: Chandler look, I don't want to be one of those wives who says, "You
  can't go to the game.  You have to spend time with me."  So, if you could just
  realize it on your own . . .

CHANDLER: I know.  You're right.  I want to see you too.  I've just got to
  figure out a way to tell Joey, you know?  He's really looking forward to this.

MONICA: Tell him that you haven't seen your wife in a long time.  Tell him
  that having a long-distance relationship is really difficult.  Tell him that
  what little time we have is precious.

CHANDLER: Yeah, ah, ah . . .  I'll think of something.

[ OPENING CREDITS ]

[Scene: Ross and Rachel's apartment.  Ross is in the living room covering Emma.
  Rachel enters wearing a sexy dress.]

ROSS: Wow!  (pause)  Wow, You look . . . uh . . .   It's just, ah . . .   That
  dress . . . uh . . .

RACHEL: Well, I hope the ends of these sentences are good.

ROSS: Well, well, they're good.  It's been a while since I've seen you like
  this.  You, you clean up good.

RACHEL: Oh well, well thank you.  (She laughs.  He stares for a moment.)  Okay,
  stop.  Stop looking at me like that.  The last time that happened, (points
  to Ross) that happened.  (points to Emma.)

ROSS: Oh right, right.  (They pause and exchange a glance. Then, Ross looks
  away.)  So, are you . . . ah . . . you excited about your, your first night
  away from Emma?

RACHEL: Yeah, yeah.  Phoebe and I are going to have so much fun.  And thank
  you for watching the baby, by the way.

ROSS: Oh, it's fine.  Actually, I, I invited Mike over.

RACHEL: Phoebe's Mike?

ROSS: Yeah.

RACHEL: I didn't know you guys hung out.

ROSS: We don't.  But I thought it would be nice to get to know him.  You know,
  maybe have a little dinner, drinks, conversation.

RACHEL: Oh that's so cute:  Ross and Mike's first date.  Is that going to be
  awkward?  I mean, what are you guys going to talk about?

ROSS: I don't know.  But, you know, we, we have a lot in common, you know.
  He plays piano; I played keyboards in college.  He's been divorced; I have some
  experience in that area.

(Rachel nods.  There is a knock on the door.)

RACHEL: Yeah.

(Phoebe and Mike enter.)

PHOEBE: Hi

RACHEL: Hey.

PHOEBE: (spotting Rachel's dress) Oooh.  Girl's night out indeed.

RACHEL: (to Ross) Ok.  So now, I think Emma is probably down for the night,
  but if you need anything Ross . . .

ROSS: Rach, Rach, we'll be fine, all right?  You go have fun.

RACHEL: Okay.  You too.  And I hope you score.  (to Mike) Bye.

MIKE: Bye.

ROSS: So . . .  Welcome.

MIKE: (Holds up a six pack of Foster's Lager) I got beer.

ROSS: I got bottled breast milk.

MIKE: Eh, why don't we start with the beer?

ROSS: Okay.  (They sit.)  So, um, Phoebe tells me you, ah, you play piano.

MIKE: Yeah.

ROSS: You know, I, I used to, ah, play keyboards in college.

MIKE: Ah?  (pause)  Do you have one here?

ROSS: No.

MIKE: Okay.  (pause)

(They clink beer bottles, and drink.  Then, they stare uncomfortably at their
  bottles.)

ROSS: Um . . . ah . . . you know, I'm divorced.  Um, Phoebe, ah . . . Phoebe
  said you . . . You've been divorced?

MIKE: Yeah.  (pause)  Yeah, I'm sorry.  I don't . . . I don't really like to
  talk about it.

ROSS: (pause) That's okay.  We'll talk about (pause) something else.  (They
  pause.  They drink.)

MIKE:  So, you're a paleontologist, right?

ROSS: Yeah.

MIKE: My cousin's a paleontologist.

ROSS: Ah?  (Mike nods.  Another pause.)  Well, he and I would probably have
  a lot to talk about.

[Scene:  Monica and Chandler's apartment.  Monica is wearing a sexy negligee.
  She pours two glasses of wine as Chandler enters with a carry-on suitcase.
  He sets the case by the door.)

MONICA: Hi.

CHANDLER: Hey.

MONICA: Welcome home.

CHANDLER: (Hangs his jacket over the suitcase, locks the door, then turns to
  Monica.)  Oh well, look at you.

MONICA: Yeah.  What do you think?

CHANDLER: Well, it looks great.  It's just that . . . well, I'm wearing the
  same thing underneath.  So . . .

MONICA: Oh.

CHANDLER: See what I mean . . . (They kiss.)

(There is a loud thud at the door.)

JOEY: Hey!  How come the door's locked?

MONICA: Just a second.

CHANDLER: (hushed) No, no, no, no, no.  Joey can't know that I'm here.

MONICA: Why not?

CHANDLER: Because I didn't know how to tell him that I couldn't go to the Knicks
  game.  So, I just told him that I had to stay in Tulsa.

MONICA: So, you lied to him?

CHANDLER: Achhh.  It's always better to lie than to have the complicated discussion.
  (pause)  Except with you.

JOEY: Hey!  Open the door.  What's going on?  (He knocks.)

(Monica goes to the door.  Chandler slides behind it as she opens it slightly.)

JOEY: What are you . ..  (He sees her in her negligee.)  Why are you dressed
  like that?

MONICA: Oh, because, um . . .  well, Chandler's going to be home in a couple
  of days.  So, I thought I would, you know, practice the art of seduction.

JOEY: Oh, I thought I heard a man's voice before.

MONICA: Oh I was just doing Chandler's side of the conversation.  You know,
  like, "Hi, How do I look?"  (As Chandler) "Really sexy.  Could I BE any more
  turned on?"

JOEY: Okay.  (pause.  He looks over her shoulder at the table with the wine.)
  Whoa, whoa.  Why are there two glasses of wine out?

MONICA: Because. . .  one of them is for you.

(Monica turns to get the wine.  Chandler peeps through the peephole.  Joey,
  seeing something, peeps back.  Chandler ducks.  Monica returns with two glasses
  of wine.  She gives one to Joey.)

MONICA: Cheers.  (She clinks his glass and pulls back.)  Okay, buh-bye.  (She
  closes the door.)

CHANDLER: You know, it's funny.  I've been, ah, practicing the art of seduction
  myself.  (He raises his hands in front of himself, sticks out his behind, and
  wiggles it.)  Hi ya.

MONICA: You might want to keep practicing.

CHANDLER: Yah.

(Chandler's cell phone rings.  He looks at it.)

CHANDLER: It's Joey.  (He answers it, holding it out so that Monica can hear
  too.)  Hey Joe.

JOEY: Dude, come home!

CHANDLER: What? Why?

JOEY: COME . . .  HOME.

CHANDLER: Look I, I can't.  What's going on?

JOEY: I don't know how to tell you this but, uh . . . I think Monica's cheatin'
  on ya.  I told you shouldn't have married someone so much hotter than you.

(Chandler and Monica look at each other.  Chandler nods.)

JOEY: All right look.  (He walks to the hallway.)  If you can't come home and
  deal with this, then I'm gonna.

CHANDLER: NO!

JOEY: (outside the apartment door) I just heard him!

CHANDLER: (softly) Can you . . . hear him . . . now?

JOEY: (listens at the door.)  No.  (pause) All right, I'm going in.

CHANDLER: No! Wait!

JOEY: I heard him again!

CHANDLER: (writhes as if in agony) All right, look.  Just stay there.  I'm
  coming home.

JOEY: Okay.  Great.  I'll see you when you get here.  I'm gonna wait out in
  the hall in case the dude comes out.

CHANDLER: Is that really necessary?

JOEY: Absolutely.  You'd do it for me.  Not that you ever have to because I
  know how to keep my women satisfied.

[Scene: Ross and Rachel's apartment.  Mike is blowing a note from his beer
  bottle.  Ross stares off to the side.)

ROSS: Shouldn't the pizza be here by now?  I mean, they said thirty minutes
  or less.  Well, how long has it been?

MIKE: (looking at his watch) Eleven minutes.  (long pause)  And now twelve.
  So, do you like the beer?

ROSS: I do.  I do.  Although, it's actually a lager.

MIKE: huh.  (pause)  What's the difference between beer and lager?

ROSS: I don't know.  We could look it up.

MIKE: (nods) Things are about to get wild.

[Scene: A bar.  Rachel and Phoebe are bringing their drinks from the bar to
  a sofa.]

PHOEBE: Oh God.  Remember the girls' nights we used to have sitting around
  talking about you and Ross?

RACHEL: Oh God.  It seems like forever ago.

PHOEBE: I know.  (sighs)   So, what's going on with you and Ross?

RACHEL: Well, um . . . I don't know.  I mean, for a long time nothing.  But
  you know, actually right before you picked me up, Ross and I had a . . . ah
  . . . little thing.

PHOEBE: Oh my God!  I love things.  What happened?

RACHEL: Well, um, first he told me he liked how I looked.  And, ah, then we
  had a little . . . um . . . eye-contact.

PHOEBE: Eye-contact?

RACHEL: Mm-hmm.

PHOEBE: I hope you were using protection.

WAITER: (with tray and two drinks)  Excuse me.  Um, these are from the two
  gentlemen at the end of the bar.

RACHEL: Oh.  (to Phoebe) Should we send them something back?

PHOEBE: Oooh.  Let's do.  Let's send them mashed potatoes.

RACHEL: No!  Wait!  No, no.  Don't do that!  That's going to make them think
  they can come over here.

PHOEBE: So?  What if they do?

RACHEL: Well, we're not here to meet guys.  You have a boyfriend, I have a
  b. . . baby and a Ross.

PHOEBE: Yeah, but, ah, ah, nothing has to happen.  We're just having fun.
  You know, not everything had to go as far as "eye-contact."

[Scene: Monica and Chandler's apartment.  Chandler is seated in the chair and
  Monica stands behind the sofa.]

MONICA: Chandler, you have to tell Joey that you're not in Tulsa.

CHANDLER: Don't you think it's better for him to think that you're cheating
  on me, than for him to think that I'm cheating on him?  (Monica tips her head
  slightly as if asking "Did you hear yourself?")  I heard it.

MONICA: I don't want him to think that I'm having an affair.

CHANDLER: All right.  I've got a plan.  I'll go down the fire escape.

MONICA: Yes, because all good plans start with, "I'll go down the fire escape."

CHANDLER: Hear me out woman.  I'll go down the fire escape.  Then, I'll wait
  for a while.  Then, when I come up the stairs, it'll be just like I just got
  back from Tulsa.  Then, Joey and I will come in and see that there's no guy
  in here.

MONICA: Aren't you afraid that Joey's going to figure all of this out?  (pause)
  I heard it.

(Chandler runs to the window, opens it, starts out, but returns, casually walking
  back to his chair.)

CHANDLER: I'm just going to wait for a little while.

MONICA: Scary pigeon's back?

CHANDLER: It's huge.

[Scene: Ross and Rachel's apartment.  Three pizza crusts, two bottle caps and
  the plastic tripod are left in the otherwise empty pizza box.  Mike is making
  hollow popping noises with his mouth.  He begins to speak, but stops and pops
  his lips a few more times and takes a drink.  Ross smiles as if he has thought
  of something to say, but then he stops and sinks back in a slump on the sofa.]

[Scene: The bar.  Two men are chatting with Rachel and Phoebe.]

RACHEL: Oh my God.  I can't believe you live in that building.  My grandmother
  lives in that building.  Ida Green?  No sense of personal space?  Kind of smells
  like chicken?  Looks like a potato.

BILL: "Spuds" is your grandmother?

RACHEL: That's my bubby!

KEVIN: So, we're on our way to a couple of parties.  Um. . . maybe we can get
  your numbers and give you guys a call if we find something fun.

PHOEBE: Yeah. . . I'm sorry.  We weren't really looking for anything to happen
  with you guys.  I, I have a boyfriend.

  KEVIN: All right. It's no big deal.

  BILL: So, she has a boyfriend. What is your situation?

  RACHEL: Oh, well, it's complicated. I don't actually have a boyfriend.  But
  um. . .

  BILL: Then, can I have your number?

  RACHEL: (pause) I'm sorry, no.

  BILL: Okay. (They start to walk away.)

  RACHEL: Oh sure.  (She pulls a business card from her purse and writes on it.)

  PHOEBE: (Reading the card.) Oh my God, you're giving your real number.

  BILL: Okay, thanks. I'll give you a call later tonight.

  RACHEL: Great.

  BILL: Bye

  PHOEBE: Bye. (The guys leave.) Wow. So, that's great. You, Bill, Ross, and Emma
  are going to be so happy together. What were you thinking?

RACHEL: I don't know.  He was cute, and he liked me.  It was an impulse.

PHOEBE: What about Ross?  What about your moment?  Don't you want to talk to
  Ross about it?

RACHEL: No.  No, because I know exactly how the conversation's gonna go.  "Hey
  Ross, you know, I think we had a moment before."

RACHEL: (lowers voice to imitate Ross) "Yeah."  (Clears throat.)  "Me too."

RACHEL: (as herself) "Well, but I'm not sure I really want to do anything about
  it."

RACHEL: (as Ross) "Yeah."  (Clears throat twice.) "Me neither." (Clears throat
  again.)

RACHEL: (as herself) "Well, should we just continue to live together and not
  really tell each other how we're really feeling?"

RACHEL: (as Ross) "Yeah.  That works for me." (Clears throat twice more.)

PHOEBE: Yeah, I see what you mean.  By the way, nice Ross imitation.

RACHEL: Oh, thanks.

PHOEBE: But, your Rachel wasn't whiny enough.

RACHEL: (whining) Wha. . . hey!

PHOEBE: (pointing) Better!

RACHEL: Well, the point is, maybe I should just stop waiting around for moments
  with Ross, you know?  I should just . . . move on with my life.

PHOEBE: Really?  You're moving on from Ross?

RACHEL: I don't know.  Do I have to decide right now?

PHOEBE: Well, you kind of just did.  That guy is going to call you tonight.
  Ross is going to pick up the phone and that's a pretty clear message.

RACHEL: Oh God, Ross.  Ross is going to pick up the phone.  Oh, I have to get
  my number back.  (She turns to find Bill, but they have gone.)  Oh my God.
  He's gone.

PHOEBE: (imitating Rachel) "Oh, I have to get my number back.  Oh my God.
  He's gone."  (smiles) Dead on.

[Scene: Ross and Rachel's apartment.  Ross and Mike are sitting on the sofa.
  Ross is fidgeting with the cuff of his sweater while Mike blows his cheeks out.
  Ross blows a piece of fuzz from his finger.)

MIKE: (releases a whoosh of air) Ya know, I'm going to take off.

ROSS: So soon?

MIKE: Well, yeah.

ROSS: Okay.  Well, thanks, ah, thanks for the beer.

MIKE: Ah, you mean lager.

ROSS: Ah yeah.  Good times.

(Mike leaves.  Ross closes the door behind him.)

MIKE: (In the hall, relieved) Oh.

(Ross, inside the door, releases a sign of relief.  Back in the hall, Mike's
  cell phone rings.)

MIKE: Hello?

PHOEBE: (calling from the bar on her cell phone.) Hey, Mike, it's me.  Listen,
  is um, is Ross near you?

MIKE: Uh, no.  I just left.

PHOEBE: Well, you have to go back in.

MIKE: Wha . . .?  Go back?  To the "land where time stands still"?

PHOEBE: I'm so sorry honey, but, okay, Rachel gave this guy her number and,
  um, she doesn't want Ross to answer the phone.  So, you have to intercept all
  his calls.

MIKE: I can't do that!

PHOEBE: (to Rachel) He says he can't do that.

RACHEL: Oh give me , , ,  (Phoebe gives Rachel the phone.)  Hi, Mike?  Hi.
  Listen.  I know this is a lot to ask, but you know what?  If you do this I .
  . . Phoebe will . . . do anything you want.  Seriously, I'm talking dirty stuff.

PHOEBE: All right. (She takes the phone from Rachel.)  Hello?  Hi.  I'm sorry
  about her, but she wasn't wrong about the dirty stuff.

MIKE: All right.  I'll do it.  (Phoebe gives the thumbs-up sign to Rachel.)
  But really, how much dirtier can it get?

PHOEBE: (knowingly chuckles) Oh, Mike.  Bye.

(Mike knocks on Ross's door.  Ross opens it.)

MIKE: Hey buddy.

ROSS: Uh, hi.

MIKE: Um, can I come back in?

ROSS: (putting his arm up with his hand on the door frame.)  Why?  (He starts
  to lower his arm.)

MIKE: (Entering the apartment) I, I was just thinking about how much more we
  have to talk about.

ROSS: (whining) But you left.

[Scene: The hallway and stairs outside Chandler and Monica's apartment.  Chandler
  enters from the stairs.  Joey is sitting with a baseball bat.]

JOEY: Wow!  That didn't take long.  I thought you said Tulsa was, like a three
  hour flight.

CHANDLER: (pause) Well, you're forgetting about the time difference.

(Joey thinks a moment. Then, he nods.  Joey follows Chandler into the apartment.)

MONICA: (gasp) Chandler!  You're home!

CHANDLER: That's right.  You're husband's home.  So, now the sex can stop.

(Joey gives him and odd look.  Monica gives a similar look.)

MONICA: What are you saying?

CHANDLER: Joey said that you're in here with another man.

MONICA: There's no man in here.  How dare you accuse me of that.  (She slaps
  Chandler.)

JOEY: All right.  All right.  Then, maybe you won't mind if me and my friend
  take a look around, huh?  (He checks the bathroom shaking the bat.  Then he
  proceeds to their bedroom.)  Bwa-ah-ah!

(Thudding sounds can be heard from the bedroom.)

CHANDLER: (To Monica) What is he doing?

MONICA: (smiling) I arranged some pillows on the bed to look like a guy.

JOEY: (emerging) Bedroom is clear, although you might need some new pillows.

CHANDLER: All right.  Well, I'll check the guest room.

JOEY: (sniffing the air and then Monica.)  Why do I smell men's cologne?

MONICA: (sniffing Joey) I think that's you.

JOEY: (sniffs his shirt.)  Oh yeah.  I rubbed a magazine on myself earlier.

CHANDLER: There's nobody here Joe.

JOEY: I guess not.

MONICA: I can't believe you thought I was cheating.  (pointing at Joey) You
  own me an apology.

JOEY: Yeah, right Monica.  I'm so sorry.

MONICA: (suddenly starts issuing him out) Ah, it's an honest mistake.  It could
  happen to anyone.  All right, see ya.

JOEY: (spots the suitcase just inside the door where Chandler left it) Whoa,
  whoa.  Wait a minute.  Wait a minute.  If you just got back from Tulsa, how
  did your suitcase beat you here?

CHANDLER: (thinks, then turns to Monica) I climb down the fire escape and you
  can't put that in the closet?

[Scene: Ross and Rachel's apartment.  Mike is reading from a book.]

MIKE: So, except for the fermentation process, beer and ale are basically the
  same thing.  Fascinating isn't it.

ROSS: Maybe you should look up "fascinating."

(Phone rings.)

MIKE: I'll get it.  (He lunges across Ross's lap on the sofa to reach the phone.
  Ross stares at him with wide eyes.)  Hello?  Ross's place.  Mike speaking.
  (pause.  Hands phone to Ross)  It's for you.

ROSS: (takes the phone, but speaks to Mike) I don't understand what just happened
  here.

[Scene: Monica and Chandler's apartment " continuing action.]

JOEY: What's going on?

CHANDLER: I'm sorry.  I, I told you I was in Tulsa because I wanted to spend
  the night with Monica and I, I didn't know . . .  I didn't think you'd understand.

JOEY: What? You think I'm too dumb to understand that a husband needs to be
  with his wife?  Huh?  Do you think I'm like, "Duh."  (He strikes himself in
  the head with the bat.  He stands dazed for a moment.)

MONICA: Joey?

JOEY: Yeah?  (His eyes bug out.)

MONICA: I don't know what to say.  We shouldn't have lied to you.

CHANDLER: Yeah.  I feel so bad.  Is there anything I can do to make it up to
  you?

JOEY: (pause) Yeah, you could go to the game with me, ah, even though I know
  you said you couldn't.  But then you lied to me and tricked me and gave me a
  bump on the head.

CHANDLER: I'm sorry.  That's the one thing I can't do.  I promised I'd be with
  Monica.

JOEY: All right.

MONICA: (taps chandler on the arm) You can go.

CHANDLER: What?

MONICA: You should go to the game.  It's okay.  I want you to.

CHANDLER: Really?  You're gonna be okay?

MONICA: Yeah, I'll be fine.  You know, maybe I'll stay here and practice the
  art of seduction.

CHANDLER: You're gonna put on sweats and clean, aren't you?

MONICA: It's gonna be so hot!  (She kisses him.)

CHANDLER: Okay, bye.

MONICA: Have fun.

JOEY: Thanks.  (Joey and Chandler exit to the hall.  Joey pulls out the tickets
  and hands one to Chandler.)  Here's your ticket.

CHANDLER: Hey, listen.  I'm never going to lie to you again, okay?  And I want
  you to know that nobody thinks you're stupid.

JOEY: Thanks man.

(Chandler heads toward the stairs, but makes a turn back to his apartment while
  looking at the ticket.)

JOEY: Where are you going?

CHANDLER: Game's tomorrow night Joe.

(Chandler goes into the apartment, while Joey checks his ticket and is embarrassed
  by his stupid mistake.)

[Scene: Ross and Rachel's apartment.  Rachel and Phoebe enter.)

RACHEL: Hi.

(Everyone exchanges greetings.)

ROSS: Oh God.  (He hugs Rachel)

RACHEL: Oh . . .

MIKE: I'm so glad you're back.  (He hugs Phoebe.)

PHOEBE: Oh.

RACHEL: Wow.  So, what did you guys do?

ROSS: Oh, you know . . . we just drank some beer and Mike played with the boundaries
  of normal social conduct.

MIKE: It's true.  I did.

PHOEBE: (pause) Well, good bye.

(Okays, and good byes are exchanged all around.)

RACHEL: That was fun Pheebs.

PHOEBE: I know.  That was fun.  (She and Mike exit.)

RACHEL: See you guys.  (She closes the door.)

ROSS: Rachel, lock the door.  Lock the door,  seriously.

RACHEL: Oh shoot.  I forgot to pay Phoebe for the drinks.  (She exits to the
  hallway and closes the door behind her.)  Wait, wait.  Sorry.  Did he call?
  Did that guy call?

MIKE: No.  Just his mom.

RACHEL: Oh, around 8:30?

MIKE: Yeah.

RACHEL: Then, again at 9:00?

MIKE: (nods) uh-huh.

RACHEL: Yeah.

(Inside the apartment the phone rings.  Ross answers it.)

ROSS: Hello.  (listens)  Ah, no, she's not here right now.  Can I take a message?
  (grabs a pad and pen)  Bill from the bar?  (writes)  Okay, "Bill from the bar."
  I'll make sure she gets your number.

(He hangs up the phone and tears the note off the pad.  Then, he stops and
  re-reads it.  Rachel enters.)

RACHEL: Aaah.  (She goes to tend Emma.)

ROSS: So, ah . . . So, how was it?   Uh, did you guys. . . Did you guys have
  a good time?

RACHEL: Oh, it was so much fun.  It felt so good to be out.

ROSS: (holds up the message) Uh, Rach.

RACHEL: (still looking at Emma) Yeah?

ROSS: (pauses, then crunches up the note and stuffs it in his pocket.)  Never
  mind.

[END]

[Tag Scene: Central Perk.  Phoebe and Mike are on the sofa.  Ross enters.]

ROSS: Hey you guys.  (He sits.)

MIKE: Hey.

PHOEBE: Hey.  I'll be right back.  I've got to go to the bathroom.  (She rises
  and exits.)

(Ross and Mike glance at each other then both suddenly turn to Phoebe who is
  gone.  They sheepishly exchange glances.)

MIKE: (finally) Stout.  That's a kind of beer.

(Ross smiles slightly.  Then he gives a single nod that lifts him to his feet.
  He exits the coffee shop.

[END TAG]


text:
package com.trip.controller;

import com.trip.service.inter.UserService;
import com.trip.util.MethodResourceDesc;
import com.trip.util.Result;
import com.trip.util.SysConst;
import com.trip.vo.FollowVo;
import com.trip.vo.UserVo;
import com.trip.vo.searchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

	HttpSession session;
	@Autowired
	UserService service ;
	@MethodResourceDesc(name="注册用户")
	@RequestMapping(value="/trip/user/register.do")
	@ResponseBody
	public Result register(UserVo vo){
		return service.register(vo);

	}

	@MethodResourceDesc(name="上传用户头像")
	@RequestMapping(value="/trip/user/upload_head.do")
	@ResponseBody
	public Result upload_head(String photoUrl,HttpServletRequest request){
		return service.upload_head(photoUrl,request);
	}

	@MethodResourceDesc(name="查询个人信息的数量")
	@RequestMapping(value="/trip/user/personalCount.do")
	@ResponseBody
	public Result search_personalCount(HttpServletRequest request){
		session = request.getSession();
		int id =((UserVo) session.getAttribute(SysConst.CurrentUser)).getId();
		return service.search_personalCount(id);
	}
	@MethodResourceDesc(name="根据id查询个人信息")
	@RequestMapping(value="/trip/user/getPersonById.do")
	@ResponseBody
	public Result getPersonById(HttpServletRequest request){
		return service.getPersonById(request);
	}
	@MethodResourceDesc(name="查询我关注的人")
	@RequestMapping(value="/trip/user/listFollower.do")
	@ResponseBody
	public Result listFollower(int id){
		return service.listFollower(id);
	}

	@MethodResourceDesc(name="查询我的粉丝")
	@RequestMapping(value="/trip/user/listFans.do")
	@ResponseBody
	public Result listFans(int id){
		return service.listFans(id);
	}

	@MethodResourceDesc(name="修改资料")
	@RequestMapping(value="/trip/user/editInfo.do")
	@ResponseBody
	public Result editInfo(UserVo user,HttpServletRequest request){
		return service.editInfo(user, request);
	}

	@MethodResourceDesc(name="搜索个人")
	@RequestMapping(value="/trip/user/searchUser.do")
	@ResponseBody
	public Result searchUser(searchVo vo,HttpServletRequest request){
		return service.searchUser(vo,request);
	}

	@MethodResourceDesc(name="加关注")
	@RequestMapping(value="/trip/user/addfollow.do")
	@ResponseBody
	public Result addFollow(FollowVo vo,HttpServletRequest request ){
		return service.addFollow(vo,request);
	}

	@MethodResourceDesc(name="取消关注与移除粉丝")
	@RequestMapping(value="/trip/user/deletefollowOrFans.do")
	@ResponseBody
	public Result deletefollowOrFans(FollowVo vo,HttpServletRequest request ){
		return service.deletefollowOrFans(vo,request);
	}

	/**
	 *
	 * jspx页面
	 * */
	@MethodResourceDesc(name="修改个人信息页面")
	@RequestMapping(value="/trip/user/editInfo.jspx")
	public ModelAndView _toEditInfo(){
		return new ModelAndView("forward:/editInfo.jsp");
	}

	@MethodResourceDesc(name="主页")
	@RequestMapping(value="/trip/user/index.jspx")
	public ModelAndView _toIndex(){
		return new ModelAndView("forward:/index.jsp");
	}

	@MethodResourceDesc(name="注册页面")
	@RequestMapping(value="/trip/user/register.jspx")
	public ModelAndView _toregister(){
		return new ModelAndView("forward:/register.jsp");
	}

	@MethodResourceDesc(name= "我关注的页面")
	@RequestMapping(value="/trip/user/follower.jspx")
	public ModelAndView _tofollower(HttpServletRequest request){
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", request.getParameter("id"));
		return new ModelAndView("forward:/follower.jsp",map);

	}

	@MethodResourceDesc(name="我的粉丝页面")
	@RequestMapping(value="/trip/user/fans.jspx")
	public ModelAndView _tofans(HttpServletRequest request){
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", request.getParameter("id"));
		return new ModelAndView("forward:/fans.jsp",map);
	}
}

redpajama_set_name: RedPajamaGithub


text:
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This script is used to synthesize generated parts of this library."""

import synthtool as s
import synthtool.gcp as gcp
import logging

logging.basicConfig(level=logging.DEBUG)

gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()

# ----------------------------------------------------------------------------
# Generate dlp GAPIC layer
# ----------------------------------------------------------------------------
library = gapic.py_library(
    "irm",
    "v1alpha2",
    config_path="/google/cloud/irm/artman_irm_v1alpha2.yaml",
    include_protos=True,
)

excludes = ["README.rst", "nox*.py", "setup.py", "docs/index.rst"]
s.move(library, excludes=excludes)

# Fix docstrings
s.replace("google/**/*.py", r"\\_", "_")
s.replace("google/**/incidents_service_pb2.py", r"""\\\*""", r"""*""")
s.replace("google/**/incident_service_client.py", r"""\\\*""", r"""*""")
s.replace(
    "google/**/incident_service_client.py",
    r"""        This will fail if:
           a\. there are too many \(50\) subscriptions in the incident already
           b\. a subscription using the given channel already exists""",
    r"""        This will fail if:
        a. there are too many (50) subscriptions in the incident already
        b. a subscription using the given channel already exists""",
)

# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = common.py_library(unit_cov_level=97, cov_level=100)
s.move(templated_files)

s.shell.run(["nox", "-s", "blacken"], hide_output=False)


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>QuickStart — SystemDS 2.3.0-SNAPSHOT documentation</title>

  <link rel="stylesheet" href="../static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Federated Environment" href="../guide/federated.html" />
    <link rel="prev" title="Install SystemDS" href="install.html" />

             SystemDS

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Getting Started:

Install SystemDS

QuickStart

Matrix Operations

More complex operations

Guides

Federated Environment

Built-in Algorithms

Python end-to-end tutorial

API

SystemDSContext

Algorithms

Matrix

Frame

List

Scalar

Source

Internals API

Operation Node

Dag

Script

Converters

Helpers

          SystemDS

 »

QuickStart

             View page source

QuickStart¶

Let's take a look at some code examples.

Matrix Operations¶

Making use of SystemDS, let us multiply an Matrix with an scalar:

# Import SystemDSContext
from systemds.context import SystemDSContext
# Create a context and if necessary (no SystemDS py4j instance running)
# it starts a subprocess which does the execution in SystemDS
with SystemDSContext() as sds:
    # Full generates a matrix completely filled with one number.
    # Generate a 5x10 matrix filled with 4.2
    m = sds.full((5, 10), 4.20)
    # multiply with scalar. Nothing is executed yet!
    m_res = m * 3.1
    # Do the calculation in SystemDS by calling compute().
    # The returned value is an numpy array that can be directly printed.
    print(m_res.compute())
# context will automatically be closed and process stopped

As output we get

[[ 13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02]
 [ 13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02]
 [ 13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02]
 [ 13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02]
 [ 13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02  13.02]]

The Python SystemDS package is compatible with numpy arrays.
Let us do a quick element-wise matrix multiplication of numpy arrays with SystemDS.
Remember to first start up a new terminal:

import numpy as np  # import numpy

# Import SystemDSContext
from systemds.context import SystemDSContext

# create a random array
m1 = np.array(np.random.randint(100, size=5 * 5) + 1.01, dtype=np.double)
m1.shape = (5, 5)
# create another random array
m2 = np.array(np.random.randint(5, size=5 * 5) + 1, dtype=np.double)
m2.shape = (5, 5)

# Create a context
with SystemDSContext() as sds:
    # element-wise matrix multiplication, note that nothing is executed yet!
    m_res = sds.from_numpy(m1) * sds.from_numpy(m2)
    # lets do the actual computation in SystemDS! The result is an numpy array
    m_res_np = m_res.compute()
    print(m_res_np)

More complex operations¶

SystemDS provides algorithm level functions as built-in functions to simplify development.
One example of this is l2SVM, a high level functions for Data-Scientists. Let's take a look at l2svm:

# Import numpy and SystemDS
import numpy as np
from systemds.context import SystemDSContext
from systemds.operator.algorithm import l2svm

# Set a seed
np.random.seed(0)
# Generate random features and labels in numpy
# This can easily be exchanged with a data set.
features = np.array(np.random.randint(100, size=10 * 10) + 1.01, dtype=np.double)
features.shape = (10, 10)
labels = np.zeros((10, 1))

# l2svm labels can only be 0 or 1
for i in range(10):
    if np.random.random() > 0.5:
        labels[i][0] = 1

# compute our model
with SystemDSContext() as sds:
    model = l2svm(sds.from_numpy(features), sds.from_numpy(labels)).compute()
    print(model)

The output should be similar to

[[ 0.02033445]
 [-0.00324092]
 [ 0.0014692 ]
 [ 0.02649209]
 [-0.00616902]
 [-0.0095087 ]
 [ 0.01039221]
 [-0.0011352 ]
 [-0.01686351]
 [-0.03839821]]

        Next

         Previous

        © Copyright 2021, Apache SystemDS

    Built with Sphinx using a

    theme

    provided by Read the Docs.


text:
<?xml version="1.0" encoding="UTF-8"?>

<rights>

<right name="getAccount" type="getAttrs" targetType="account">
  <desc>get all account attributes</desc>
</right>

<right name="modifyAccount" type="setAttrs" targetType="account">
  <desc>modify all account attributes</desc>
</right>

<right name="listAccount" type="preset" targetType="account">
  <desc>see account in GetAllAccounts/SearchDirectoryResponse</desc>
</right>

<right name="renameAccount" type="preset" targetType="account">
  <desc>rename account</desc>
</right>

<right name="deleteAccount" type="preset" targetType="account">
  <desc>delete account</desc>
</right>

<right name="addAccountAlias" type="preset" targetType="account">
  <desc>add account alias</desc>
</right>

<right name="removeAccountAlias" type="preset" targetType="account">
  <desc>remove account alias</desc>
</right>

<right name="getAccountInfo" type="preset" targetType="account">
  <desc>get basic account info: account id, home server, and access URLs</desc>
</right>

<right name="getAccountMembership" type="preset" targetType="account">
  <desc>get all groups the account is a member of</desc>
</right>

<right name="adminLoginAs" type="preset" targetType="account" cache="1">
  <desc>
    login to the user's account as an administrator
  </desc>
</right>

<right name="checkRightUsr" type="preset" targetType="account">
  <desc>check if the account has any effective rights</desc>
</right>

<right name="getMailboxInfo" type="preset" targetType="account">
  <desc>get mailbox id and size(quota) of an account</desc>
</right>

<right name="purgeMessages" type="preset" targetType="account">
  <desc>purge messages of an account</desc>
</right>

<right name="reindexMailbox" type="preset" targetType="account">
  <desc>reindex mailbox</desc>
</right>

<right name="moveAccountMailbox" type="preset" targetType="account">
  <desc>move account mailbox</desc>
</right>

<right name="setAccountPassword" type="preset" targetType="account">
  <desc>set account password, not restricted by password strength policies</desc>
</right>

<right name="changeAccountPassword" type="preset" targetType="account">
  <desc>change account password, restricted by password strength policies</desc>
</right>

<right name="checkPasswordStrength" type="preset" targetType="account">
  <desc>check password strength</desc>
</right>

<right name="configurePasswordStrength" type="setAttrs" targetType="account,calresource,cos">
  <desc>configure password strength</desc>
  <attrs>

  </attrs>
</right>

<right name="viewAdminSavedSearch" type="getAttrs" targetType="account,calresource">
  <desc>view admin saved searches</desc>
  <attrs>

  </attrs>
</right>

<right name="setAdminSavedSearch" type="setAttrs" targetType="account,calresource">
  <desc>save admin saved searches</desc>
  <attrs>

  </attrs>
</right>

<right name="configureQuota" type="setAttrs" targetType="account,cos">
  <desc>configure quota</desc>
  <attrs>

  </attrs>
</right>

<right name="viewAccountAdminUI" type="preset" targetType="account">
  <desc>
    execute the GetAdminConsoleUIComp SOAP when an account
    other than the authenticated account is specified in the request.
  </desc>
</right>

<right name="viewDistributionListAdminUI" type="preset" targetType="dl">
  <desc>
    execute the GetAdminConsoleUIComp SOAP when a distribution list
    is specified in the request.
  </desc>
</right>

<right name="configureAdminUI" type="setAttrs" targetType="account,dl">
  <desc>configure admin UI components</desc>
  <attrs>

  </attrs>
</right>

<right name="getCalendarResource" type="getAttrs" targetType="calresource">
  <desc>get all calendar resource attributes</desc>
</right>

<right name="modifyCalendarResource" type="setAttrs" targetType="calresource">
  <desc>modify all calendar resource attributes</desc>
</right>

<right name="listCalendarResource" type="preset" targetType="calresource">
  <desc>see calendar resource in GetAllCalendarResources/SearchDirectoryResponse</desc>
</right>

<right name="renameCalendarResource" type="preset" targetType="calresource">
  <desc>rename calendar resource</desc>
</right>

<right name="deleteCalendarResource" type="preset" targetType="calresource">
  <desc>delete calendar resource</desc>
</right>

<right name="addCalendarResourceAlias" type="preset" targetType="calresource">
  <desc>add calendar resource alias</desc>
</right>

<right name="removeCalendarResourceAlias" type="preset" targetType="calresource">
  <desc>remove calendar resource alias</desc>
</right>

<right name="adminLoginCalendarResourceAs" type="preset" targetType="calresource">
  <desc>login to the calendar resource as an admin.</desc>
</right>

<right name="getCalendarResourceInfo" type="preset" targetType="calresource">
  <desc>get account id, home server, cos id and name, and access URL</desc>
</right>

<right name="setCalendarResourcePassword" type="preset" targetType="calresource">
  <desc>set calendar resource password, not restricted by password strength policies</desc>
</right>

<right name="changeCalendarResourcePassword" type="preset" targetType="calresource">
  <desc>set calendar resource password, restricted by password strength policies</desc>
</right>

<right name="checkCalendarResourcePasswordStrength" type="preset" targetType="calresource">
  <desc>check password strength</desc>
</right>

<right name="reindexCalendarResourceMailbox" type="preset" targetType="calresource">
  <desc>reindex mailbox</desc>
</right>

<right name="moveCalendarResourceMailbox" type="preset" targetType="calresource">
  <desc>move calendar resource mailbox</desc>
</right>

<right name="getCos" type="getAttrs" targetType="cos">
  <desc>get all cos attributes</desc>
</right>

<right name="modifyCos" type="setAttrs" targetType="cos">
  <desc>set all cos attributes</desc>
</right>

<right name="listCos" type="preset" targetType="cos">
  <desc>see cos in GetAllCos/SearchDirectoryResponse</desc>
</right>

<right name="renameCos" type="preset" targetType="cos">
  <desc>rename cos</desc>
</right>

<right name="deleteCos" type="preset" targetType="cos">
  <desc>delete cos</desc>
</right>

<right name="assignCos" type="preset" targetType="cos">
  <desc>assign the cos (to domains or accounts)</desc>
</right>

<right name="manageZimlet" type="preset" targetType="cos">
  <desc>activate/deactivate zimlets on a cos</desc>
</right>

<right name="configureCosConstraint" type="setAttrs" targetType="cos">
  <desc>configure cos constraint</desc>
  <attrs>

  </attrs>
</right>

<right name="getGlobalConfig" type="getAttrs" targetType="config">
  <desc>get all global config attributes</desc>
</right>

<right name="modifyGlobalConfig" type="setAttrs" targetType="config">
  <desc>modify all global config attributes</desc>
</right>

<right name="configureGlobalConfigConstraint" type="setAttrs" targetType="config">
  <desc>configure global config constraint</desc>
  <attrs>

  </attrs>
</right>

<right name="checkRightGrp" type="preset" targetType="dl">
  <desc>check if the group has any effective rights</desc>
</right>

<right name="getDistributionList" type="getAttrs" targetType="dl">
  <desc>get all distribution list attributes</desc>
</right>

<right name="modifyDistributionList" type="setAttrs" targetType="dl">
  <desc>set all distribution list attributes</desc>
</right>

<right name="listDistributionList" type="preset" targetType="dl">
  <desc>see distribution list in GetAllCos/SearchDirectoryResponse</desc>
</right>

<right name="renameDistributionList" type="preset" targetType="dl">
  <desc>rename distribution list</desc>
</right>

<right name="deleteDistributionList" type="preset" targetType="dl">
  <desc>delete distribution list</desc>
</right>

<right name="addDistributionListAlias" type="preset" targetType="dl">
  <desc>add distribution list alias</desc>
</right>

<right name="removeDistributionListAlias" type="preset" targetType="dl">
  <desc>remove distribution list alias</desc>
</right>

<right name="getDistributionListMembership" type="preset" targetType="dl">
  <desc>get all groups the distribution list is a member of</desc>
</right>

<right name="addDistributionListMember" type="preset" targetType="dl">
  <desc>add member to distribution list</desc>
</right>

<right name="removeDistributionListMember" type="preset" targetType="dl">
  <desc>remove member from distribution list</desc>
</right>

<right name="getGroup" type="getAttrs" targetType="group">
  <desc>get all group attributes</desc>
</right>

<right name="modifyGroup" type="setAttrs" targetType="group">
  <desc>set all group attributes</desc>
</right>

<right name="listGroup" type="preset" targetType="group">
  <desc>see group in GetAllCos/SearchDirectoryResponse</desc>
</right>

<right name="renameGroup" type="preset" targetType="group">
  <desc>rename group</desc>
</right>

<right name="deleteGroup" type="preset" targetType="group">
  <desc>delete group</desc>
</right>

<right name="addGroupAlias" type="preset" targetType="group">
  <desc>add group alias</desc>
</right>

<right name="removeGroupAlias" type="preset" targetType="group">
  <desc>remove group alias</desc>
</right>

<right name="addGroupMember" type="preset" targetType="group">
  <desc>add member to group</desc>
</right>

<right name="removeGroupMember" type="preset" targetType="group">
  <desc>remove member from group</desc>
</right>

<right name="getDomain" type="getAttrs" targetType="domain">
  <desc>get all domain attributes</desc>
</right>

<right name="modifyDomain" type="setAttrs" targetType="domain">
  <desc>set all domain attributes</desc>
</right>

<right name="listDomain" type="preset" targetType="domain">
  <desc>see domain in GetAllCos/SearchDirectoryResponse</desc>
</right>

<right name="deleteDomain" type="preset" targetType="domain">
  <desc>delete domain</desc>
</right>

<right name="createSubDomain" type="preset" targetType="domain">
  <desc>create sub domain</desc>
</right>

<right name="checkDomainMXRecord" type="preset" targetType="domain">
  <desc>check domain MX record</desc>
</right>

<right name="countAccount" type="preset" targetType="domain">
  <desc>count accounts in a domain</desc>
</right>

<right name="getDomainQuotaUsage" type="preset" targetType="domain">
  <desc>get domain quota usage</desc>
</right>

<right name="createAccount" type="preset" targetType="domain">
  <desc>create account in the domain</desc>
</right>

<right name="autoProvisionAccount" type="preset" targetType="domain">
  <desc>auto provision account in the domain in MANUAL mode</desc>
</right>

<right name="createCalendarResource" type="preset" targetType="domain">
  <desc>create calendar resource in the domain</desc>
</right>

<right name="createDistributionList" type="preset" targetType="domain">
  <desc>create distribution list in the domain</desc>
</right>

<right name="createGroup" type="preset" targetType="domain">
  <desc>create group in the domain</desc>
</right>

<right name="createAlias" type="preset" targetType="domain">
  <desc>create alias in this domain</desc>
</right>

<right name="deleteAlias" type="preset" targetType="domain">
  <desc>delete alias in this domain</desc>
</right>

<right name="listAlias" type="preset" targetType="domain">
  <desc>list alias in this domain</desc>
</right>

<right name="accessGAL" type="preset" targetType="domain">
  <desc>access GAL(global address list)</desc>
</right>

<right name="checkExchangeAuthConfig" type="preset" targetType="domain">
  <desc>check exchange auth config</desc>
</right>

<right name="configureWikiAccount" type="setAttrs" targetType="domain,config">
  <desc>configure attributes for wiki account</desc>
   <attrs>

  </attrs>
</right>

<right name="configureExternalGAL" type="setAttrs" targetType="domain">
  <desc>configure attributes for external GAL</desc>
   <attrs>

  </attrs>
</right>

<right name="configureExternalAuth" type="setAttrs" targetType="domain">
  <desc>configure attributes for external auth</desc>
   <attrs>

  </attrs>
</right>

<right name="getServer" type="getAttrs" targetType="server">
  <desc>get all server attributes</desc>
</right>

<right name="modifyServer" type="setAttrs" targetType="server">
  <desc>set all server attributes</desc>
</right>

<right name="listServer" type="preset" targetType="server">
  <desc>see server in GetAllServers/SearchDirectoryResponse</desc>
</right>

<right name="deleteServer" type="preset" targetType="server">
  <desc>delete server</desc>
</right>

<right name="flushCache" type="preset" targetType="server">
  <desc>flush LDAP, skin, local caches on server</desc>
</right>

<right name="checkDirectoryOnFileSystem" type="preset" targetType="server">
  <desc>check and create directory on file system</desc>
</right>

<right name="checkHealth" type="preset" targetType="server">
  <desc>check server health</desc>
</right>

<right name="getSessions" type="preset" targetType="server">
  <desc>dump/get sessions</desc>
</right>

<right name="getMailboxStats" type="preset" targetType="server">
  <desc>get mailbox stats homed on the server</desc>
</right>

<right name="manageMailQueue" type="preset" targetType="server">
  <desc>view and take actions on mail queues</desc>
</right>

<right name="manageAccountLogger" type="preset" targetType="server">
  <desc>add/remove account loggers</desc>
</right>

<right name="manageVolume" type="preset" targetType="server">
  <desc>create, volumes</desc>
</right>

<right name="applianceAll" type="preset" targetType="server">
  <desc>catchall, appliance</desc>
</right>

<right name="deployZimlet" type="preset" targetType="server">
  <desc>deploy and undeploy zimlets on a server</desc>
</right>

<right name="backupAccount" type="preset" targetType="server">
  <desc>backup accounts on a server</desc>
</right>

<right name="restoreAccount" type="preset" targetType="server">
  <desc>restore accounts on a server</desc>
</right>

<right name="rolloverRedoLog" type="preset" targetType="server">
  <desc>rollover redo log on a server</desc>
</right>

<right name="moveMailboxToServer" type="preset" targetType="server">
  <desc>move mailboxes to a server</desc>
</right>

<right name="moveMailboxFromServer" type="preset" targetType="server">
  <desc>move mailboxes from a server and purge moved mailboxes</desc>
</right>

<right name="getServiceStatus" type="preset" targetType="server">
  <desc>get service status of server</desc>
</right>

<right name="manageCrossMailboxSearchTask" type="preset" targetType="server">
  <desc>create/abort/delete/purge/get status of a cross mailbox search task</desc>
</right>

<right name="getServerStats" type="preset" targetType="server">
  <desc>get stats of server</desc>
</right>

<right name="getHSMStatus" type="preset" targetType="server">
  <desc>get HSM process status for a server</desc>
</right>

<right name="moveBlobs" type="preset" targetType="server">
  <desc>move blobs, start and abort HSM thread on a server</desc>
</right>

<right name="createMigrationTask" type="preset" targetType="server">
    <desc>create bulk migration task on a server</desc>
</right>

<right name="getCertificateInfo" type="preset" targetType="server">
    <desc>view SSL certificates installed on the target server</desc>
</right>

<right name="installCertificate" type="preset" targetType="server">
    <desc>install SSL certificates on the target server</desc>
</right>

<right name="getCSR" type="preset" targetType="server">
    <desc>get CSR from the target server</desc>
</right>

<right name="generateCSR" type="preset" targetType="server">
    <desc>generate CSR on the target server</desc>
</right>

<right name="getUCService" type="getAttrs" targetType="ucservice">
  <desc>get all UC service attributes</desc>
</right>

<right name="modifyUCService" type="setAttrs" targetType="ucservice">
  <desc>set all UC service attributes</desc>
</right>

<right name="listUCService" type="preset" targetType="ucservice">
  <desc>see UC service in GetAllUCServices/SearchDirectoryResponse</desc>
</right>

<right name="deleteUCService" type="preset" targetType="ucservice">
  <desc>delete UC service</desc>
</right>

<right name="renameUCService" type="preset" targetType="ucservice">
  <desc>rename UC service</desc>
</right>

<right name="getXMPPComponent" type="getAttrs" targetType="xmppcomponent">
  <desc>get all XMPP component attributes</desc>
</right>

<right name="modifyXMPPComponent" type="setAttrs" targetType="xmppcomponent">
  <desc>set all XMPP component attributes</desc>
</right>

<right name="listXMPPComponent" type="preset" targetType="xmppcomponent">
  <desc>see XMPP component in GetAllXMPPComponents</desc>
</right>

<right name="deleteXMPPComponent" type="preset" targetType="xmppcomponent">
  <desc>delete XMPP component</desc>
</right>

<right name="getZimlet" type="getAttrs" targetType="zimlet">
  <desc>get all zimlet attributes</desc>
</right>

<right name="modifyZimlet" type="setAttrs" targetType="zimlet">
  <desc>set all zimlet attributes</desc>
</right>

<right name="listZimlet" type="preset" targetType="zimlet">
  <desc>see zimlet in GetAllZimlets</desc>
</right>

<right name="deleteZimlet" type="preset" targetType="zimlet">
  <desc>delete zimlet</desc>
</right>

<right name="createCos" type="preset" targetType="global">
  <desc>create cos</desc>
</right>

<right name="createServer" type="preset" targetType="global">
  <desc>create server</desc>
</right>

<right name="createUCService" type="preset" targetType="global">
  <desc>create UC service</desc>
</right>

<right name="createTopDomain" type="preset" targetType="global">
  <desc>create a top-level domain</desc>
</right>

<right name="createXMPPComponent" type="preset" targetType="global">
  <desc>create XMPP component</desc>
</right>

<right name="createZimlet" type="preset" targetType="global">
  <desc>create zimlet</desc>
</right>

<right name="installZCSLicense" type="preset" targetType="global">
    <desc>install Zimbra License file on the target server</desc>
</right>

<right name="getAllFreeBusyProviders" type="preset" targetType="global">
    <desc>Retrieve a list of Free/Busy providers via GetAllFreeBusyProvidersRequest SOAP request</desc>
</right>

<right name="checkSoftwareUpdates" type="preset" targetType="global">
    <desc>check for Zimbra software updates</desc>
</right>

<right name="uploadClientSoftware" type="preset" targetType="global">
    <desc>upload client software via Admin Console</desc>
</right>

<right name="crossDomainAdmin" type="preset" targetType="domain">
  <desc>cross domain admin right</desc>
</right>

<right name="viewGrants" type="getAttrs" targetType="account,calresource,cos,dl,domain,server,xmppcomponent,zimlet,config,global">
  <desc>view grants on all target types</desc>

  <attrs>

  </attrs>
</right>

</rights>


text:
#include "Search/Kino03/KinoSearch/Util/ToolSet.h"

#include "Search/Kino03/KinoSearch/Index/LexIndex.h"
#include "Search/Kino03/KinoSearch/Architecture.h"
#include "Search/Kino03/KinoSearch/FieldType.h"
#include "Search/Kino03/KinoSearch/Index/Segment.h"
#include "Search/Kino03/KinoSearch/Index/TermInfo.h"
#include "Search/Kino03/KinoSearch/Schema.h"
#include "Search/Kino03/KinoSearch/Store/Folder.h"
#include "Search/Kino03/KinoSearch/Store/InStream.h"

/* Read the data we've arrived at after a seek operation. */
static void
S_read_entry(LexIndex *self);

LexIndex*
LexIndex_new(Schema *schema, Folder *folder, Segment *segment,
             const CharBuf *field)
{
    LexIndex *self = (LexIndex*)VTable_Make_Obj(&LEXINDEX);
    return LexIndex_init(self, schema, folder, segment, field);
}

LexIndex*
LexIndex_init(LexIndex *self, Schema *schema, Folder *folder,
              Segment *segment, const CharBuf *field)
{
    i32_t    field_num = Seg_Field_Num(segment, field);
    CharBuf *seg_name  = Seg_Get_Name(segment);
    CharBuf *ixix_file = CB_newf("%o/lexicon-%i32.ixix", seg_name, field_num);
    CharBuf *ix_file   = CB_newf("%o/lexicon-%i32.ix", seg_name, field_num);
    Architecture *arch = Schema_Get_Architecture(schema);

    /* Init. */
    self->term  = ViewCB_new_from_trusted_utf8(NULL, 0);
    self->tinfo = TInfo_new(0,0,0,0);
    self->tick  = 0;

    /* Derive */
    self->field_type = Schema_Fetch_Type(schema, field);
    if (!self->field_type) {
        CharBuf *mess = MAKE_MESS("Unknown field: '%o'", field);
        DECREF(ix_file);
        DECREF(ixix_file);
        DECREF(self);
        Err_throw_mess(mess);
    }
    INCREF(self->field_type);
    self->ixix_in = Folder_Open_In(folder, ixix_file);
    self->ix_in   = Folder_Open_In(folder, ix_file);
    if (!self->ixix_in || !self->ix_in) {
        CharBuf *mess =
             MAKE_MESS("Can't open either %o or %o", ix_file, ixix_file);
        DECREF(ix_file);
        DECREF(ixix_file);
        DECREF(self);
        Err_throw_mess(mess);
    }
    self->index_interval = Arch_Index_Interval(arch);
    self->skip_interval  = Arch_Skip_Interval(arch);
    self->size    = (i32_t)(InStream_Length(self->ixix_in) / sizeof(i64_t));
    self->offsets = (i64_t*)InStream_Buf(self->ixix_in,
        (size_t)InStream_Length(self->ixix_in));
    self->data = InStream_Buf(self->ix_in, InStream_Length(self->ix_in));
    self->limit = self->data + InStream_Length(self->ix_in);

    DECREF(ixix_file);
    DECREF(ix_file);

    return self;
}

void
LexIndex_destroy(LexIndex *self)
{
    DECREF(self->field_type);
    DECREF(self->ixix_in);
    DECREF(self->ix_in);
    DECREF(self->term);
    DECREF(self->tinfo);
    FREE_OBJ(self);
}

i32_t
LexIndex_get_term_num(LexIndex *self)
{
    return (self->index_interval * self->tick) - 1;
}

Obj*
LexIndex_get_term(LexIndex *self) { return (Obj*)self->term; }
TermInfo*
LexIndex_get_term_info(LexIndex *self) { return self->tinfo; }

static void
S_read_entry(LexIndex *self)
{
    TermInfo *tinfo  = self->tinfo;
    i64_t     offset = (i64_t)Math_decode_bigend_u64(self->offsets + self->tick);
    char     *data   = self->data + offset;
    size_t    size   = Math_decode_c32(&data);

    ViewCB_Assign_Str(self->term, data, size);
    data += size;
    tinfo->doc_freq = Math_decode_c32(&data);
    tinfo->post_filepos = Math_decode_c64(&data);
    tinfo->skip_filepos = tinfo->doc_freq >= self->skip_interval
                        ? Math_decode_c64(&data) : 0;
    tinfo->lex_filepos  = Math_decode_c64(&data);

    /* Don't allow buffer overruns. */
    if (data > self->limit) {
        THROW("Buffer overrun in lexicon index for %o",
            InStream_Get_Filename(self->ix_in));
    }
}

void
LexIndex_seek(LexIndex *self, Obj *target)
{
    FieldType   *type   = self->field_type;
    i32_t        lo     = 0;
    i32_t        hi     = self->size - 1;
    i32_t        result = -100;

    if (target == NULL || self->size == 0) {
        self->tick = 0;
        return;
    }
    else {
        if ( !OBJ_IS_A(target, CHARBUF)) {
            THROW("Target is a %o, and not comparable to a %o",
                Obj_Get_Class_Name(target), CHARBUF.name);
        }
        /* TODO:
        Obj *first_obj = VA_Fetch(terms, 0);
        if ( !Obj_Is_A(target, Obj_Get_VTable(first_obj)) ) {
            THROW("Target is a %o, and not comparable to a %o",
                Obj_Get_Class_Name(target), Obj_Get_Class_Name(first_obj));
        }
        */
    }

    /* Divide and conquer. */
    while (hi >= lo) {
        const i32_t mid = lo + ((hi - lo) / 2);
        const i64_t offset
            = (i64_t)Math_decode_bigend_u64(self->offsets + mid);
        char *data = self->data + offset;
        size_t size = Math_decode_c32(&data);
        i64_t comparison;

        ViewCB_Assign_Str(self->term, data, size);
        comparison = FType_Compare_Values(type, target, (Obj*)self->term);
        if (comparison < 0) {
            hi = mid - 1;
        }
        else if (comparison > 0) {
            lo = mid + 1;
        }
        else {
            result = mid;
            break;
        }
    }

    /* Record the index of the entry we've seeked to, then read entry. */
    self->tick = hi == -1   ? 0  /* indicating that target lt first entry */
           : result == -100 ? hi /* if result is still -100, it wasn't set */
           : result;
    S_read_entry(self);
}

/* Copyright 2006-2009 Marvin Humphrey
 *
 * This program is free software; you can redistribute it and/or modify
 * under the same terms as Perl itself.
 */


text:
![](https://cldup.com/JDmmHX3uhF.svg)

_**Micro —** Async ES6 HTTP microservices_

[![Build Status](https://travis-ci.org/zeit/micro.svg?branch=master)](https://travis-ci.org/zeit/micro)
[![Slack Channel](https://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/)
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)

## Features

* **Easy**. Designed for usage with `async` and `await` ([more](https://zeit.co/blog/async-and-await))
* **Fast**. Ultra-high performance (even JSON parsing is opt-in).
* **Micro**. The whole project is ~100 lines of code.
* **Agile**. Super easy deployment and containerization.
* **Simple**. Oriented for single purpose modules (function).
* **Explicit**. No middleware. Modules declare all dependencies.
* **Standard**. Just HTTP!
* **Lightweight**. The package is small and the `async` transpilation fast and transparent

## Example

The following example `sleep.js` will wait before responding (without blocking!)

```js
const {send} = require('micro')
const sleep = require('then-sleep')

module.exports = async function (req, res) {
  await sleep(500)
  send(res, 200, 'Ready!')
}
```

To run the microservice on port `3000`, use the `micro` command:

```bash
$ micro -p 3000 sleep.js
```

To run the microservice on port `3000` and localhost instead of listening on every interface, use the `micro` command:

```bash
$ micro -p 3000 -H localhost sleep.js
```

## Usage

**Note**: `micro` requires Node `6.0.0` or later

Install the package:

```js
$ npm install --save micro
```

And start using it in your `package.json` file:

```js
"main": "index.js",
"scripts": {
  "start": "micro -p 3000"
}
```

Then write your `index.js` (see above for an example). To run your
app and make it listen on `http://localhost:3000` run:

```bash
$ npm start
```

### API

#### micro
**`micro(fn)`**

- This function is exposed as the `default` export.
- Use `require('micro')`.
- Returns a [`http.Server`](https://nodejs.org/dist/latest-v4.x/docs/api/http.html#http_class_http_server) that uses the provided `fn` as the request handler.
- The supplied function is run with `await`. It can be `async`!
- Example:

  ```js
  const micro = require('micro');
  const sleep = require('then-sleep');
  const srv = micro(async function (req, res) {
    await sleep(500);
    res.writeHead(200);
    res.end('woot');
  });
  srv.listen(3000);
  ```

#### json

**`json(req, { limit = '1mb' })`**

- Use `require('micro').json`.
- Buffers and parses the incoming body and returns it.
- Exposes an `async` function that can be run with  `await`.
- `limit` is how much data is aggregated before parsing at max. Otherwise, an `Error` is thrown with `statusCode` set to `413` (see [Error Handling](#error-handling)). It can be a `Number` of bytes or [a string](https://www.npmjs.com/package/bytes) like `'1mb'`.
- If JSON parsing fails, an `Error` is thrown with `statusCode` set to `400` (see [Error Handling](#error-handling))
- Example:

  ```js
  const { json, send } = require('micro');
  module.exports = async function (req, res) {
    const data = await json(req);
    console.log(data.price);
    send(res, 200);
  }
  ```

#### send

**`send(res, statusCode, data = null)`**

- Use `require('micro').send`.
- `statusCode` is a `Number` with the HTTP error code, and must always be supplied.
- If `data` is supplied it is sent in the response. Different input types are processed appropriately, and `Content-Type` and `Content-Length` are automatically set.
  - `Stream`: `data` is piped as an `octet-stream`. Note: it is _your_ responsibility to handle the `error` event in this case (usually, simply logging the error and aborting the response is enough).
  - `Buffer`: `data` is written as an `octet-stream`.
  - `object`: `data` is serialized as JSON.
  - `string`: `data` is written as-is.
- If JSON serialization fails (for example, if a cyclical reference is found), a `400` error is thrown. See [Error Handling](#error-handling).
- Example

  ```js
  const { send } = require('micro')
  module.exports = async function (req, res) {
    send(res, 400, { error: 'Please use a valid email' });
  }
  ```

#### return

**`return val;`**

- Returning `val` from your function is shorthand for: `send(res, 200, val)`.
- Example

  ```js
  module.exports = function (req, res) {
    return {message: 'Hello!'};
  }
  ```

- Returning a promise works as well!
- Example

  ```js
  const sleep = require('then-sleep')
  module.exports = async function (req, res) {
    return new Promise(async (resolve) => {
      await sleep(100);
      resolve('I Promised');
    });
  }
  ```

#### sendError

**`sendError(req, res, error)`**

- Use `require('micro').sendError`.
- Used as the default handler for errors thrown.
- Automatically sets the status code of the response based on `error.statusCode`.
- Sends the `error.message` as the body.
- During development (when `NODE_ENV` is set to `'development'`), stacks are printed out with `console.error` and also sent in responses.
- Usually, you don't need to invoke this method yourself, as you can use the [built-in error handling](#error-handling) flow with `throw`.

#### createError

**`createError(code, msg, orig)`**

- Use `require('micro').createError`.
- Creates an error object with a `statusCode`.
- Useful for easily throwing errors with HTTP status codes, which are interpreted by the [built-in error handling](#error-handling).
- `orig` sets `error.originalError` which identifies the original error (if any).

### Error handling

Micro allows you to write robust microservices. This is accomplished primarily by bringing sanity back to error handling and avoiding callback soup.

If an error is thrown and not caught by you, the response will automatically be `500`. **Important:** during development mode (if the env variable `NODE_ENV` is `'development'`), error stacks will be printed as `console.error` and included in the responses.

If the `Error` object that's thrown contains a `statusCode` property, that's used as the HTTP code to be sent. Let's say you want to write a rate limiting module:

```js
const rateLimit = require('my-rate-limit')
module.exports = async function (req, res) {
  await rateLimit(req);
  // … your code
}
```

If the API endpoint is abused, it can throw an error like so:

```js
if (tooMany) {
  const err = new Error('Rate limit exceeded');
  err.statusCode = 429;
  throw err;
}
```

Alternatively you can use ``createError`` as described above.

```js
if (tooMany) {
  throw createError(429, 'Rate limit exceeded')
}
```

The nice thing about this model is that the `statusCode` is merely a suggestion. The user can override it:

```js
try {
  await rateLimit(req);
} catch (err) {
  if (429 == err.statusCode) {
    // perhaps send 500 instead?
    send(res, 500);
  }
}
```

If the error is based on another error that **Micro** caught, like a `JSON.parse` exception, then `originalError` will point to it.

If a generic error is caught, the status will be set to `500`.

In order to set up your own error handling mechanism, you can use composition in your handler:

```js
module.exports = handleErrors(async (req, res) => {
  throw new Error('What happened here?');
});

function handleErrors (fn) {
  return async function (req, res) {
    try {
      return await fn(req, res);
    } catch (err) {
      console.log(err.stack);
      send(res, 500, 'My custom error!');
    }
  }
}
```

### Testing

Micro makes tests compact and a pleasure to read and write.
We recommend [ava](https://github.com/sindresorhus/ava), a highly parallel micro test framework with built-in support for async tests:

```js
const test = require('ava');
const listen = require('./listen');
const send = require('micro').send;
const request = require('request-promise');

test('my endpoint', async t => {
  const fn = async function (req, res) {
    send(res, 200, { test: 'woot' });
  };
  const url = await listen(fn);
  const body = await request(url);
  t.same(body.test, 'woot');
});
```

Look at the [test-listen](https://github.com/zeit/test-listen) for a
function that returns a URL with an ephemeral port every time it's called.

### Transpilation

We use [is-async-supported](https://github.com/timneutkens/is-async-supported) combined with [async-to-gen](https://github.com/leebyron/async-to-gen),
so that the we only convert `async` and `await` to generators when needed.

If you want to do it manually, you can! `micro(1)` is idempotent and
should not interfere.

`micro` exclusively supports Node 6+ to avoid a big transpilation
pipeline. `async-to-gen` is fast and can be distributed with
the main `micro` package due to its small size.

### Deployment

You can use the `micro` CLI for `npm start`:

```json
{
  "name": "my-microservice",
  "dependencies": {
    "micro": "x.y.z"
  },
  "main": "microservice.js",
  "scripts": {
    "start": "micro -p 3000"
  }
}
```

Then simply run `npm start`!

## Contribute

1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Transpile the source code and watch for changes: `npm start`
4. Within the module you want to test your local development instance of micro, just link it to the dependencies: `npm link micro`. Instead of the default one from npm, node will now use your clone of micro!

## Credits

Thanks Tom Yandell and Richard Hodgson for donating the  `micro` npm name.


text:
#pragma once

#include "engine.h"
#include "hashtable.h"

#include <cinttypes>

namespace juddperft {

bool setMemory(uint64_t nTotalBytes);
void setProcessPriority();

} // namespace juddperft


text:
from twisted.internet.defer import Deferred
from foolscap.tokens import Violation
from foolscap.slicer import BaseUnslicer
from foolscap.slicers.list import ListSlicer
from foolscap.constraint import OpenerConstraint, Any, IConstraint
from foolscap.util import AsyncAND

class TupleSlicer(ListSlicer):
    opentype = ("tuple",)
    slices = tuple

class TupleUnslicer(BaseUnslicer):
    opentype = ("tuple",)

    debug = False
    constraints = None

    def setConstraint(self, constraint):
        if isinstance(constraint, Any):
            return
        assert isinstance(constraint, TupleConstraint)
        self.constraints = constraint.constraints

    def start(self, count):
        self.list = []
        # indices of .list which are unfilled because of children that could
        # not yet be referenced
        self.num_unreferenceable_children = 0
        self.count = count
        if self.debug:
            print "%s[%d].start with %s" % (self, self.count, self.list)
        self.finished = False
        self.deferred = Deferred()
        self.protocol.setObject(count, self.deferred)
        self._ready_deferreds = []

    def checkToken(self, typebyte, size):
        if self.constraints == None:
            return
        if len(self.list) >= len(self.constraints):
            raise Violation("the tuple is full")
        self.constraints[len(self.list)].checkToken(typebyte, size)

    def doOpen(self, opentype):
        where = len(self.list)
        if self.constraints != None:
            if where >= len(self.constraints):
                raise Violation("the tuple is full")
            self.constraints[where].checkOpentype(opentype)
        unslicer = self.open(opentype)
        if unslicer:
            if self.constraints != None:
                unslicer.setConstraint(self.constraints[where])
        return unslicer

    def update(self, obj, index):
        if self.debug:
            print "%s[%d].update: [%d]=%s" % (self, self.count, index, obj)
        self.list[index] = obj
        self.num_unreferenceable_children -= 1
        if self.finished:
            self.checkComplete()
        return obj

    def receiveChild(self, obj, ready_deferred=None):
        if ready_deferred:
            self._ready_deferreds.append(ready_deferred)
        if isinstance(obj, Deferred):
            obj.addCallback(self.update, len(self.list))
            obj.addErrback(self.explode)
            self.num_unreferenceable_children += 1
            self.list.append("placeholder")
        else:
            self.list.append(obj)

    def checkComplete(self):
        if self.debug:
            print "%s[%d].checkComplete: %d pending" % \
                  (self, self.count, self.num_unreferenceable_children)
        if self.num_unreferenceable_children:
            # not finished yet, we'll fire our Deferred when we are
            if self.debug:
                print " not finished yet"
            return

        # list is now complete. We can finish.
        return self.complete()

    def complete(self):
        ready_deferred = None
        if self._ready_deferreds:
            ready_deferred = AsyncAND(self._ready_deferreds)

        t = tuple(self.list)
        if self.debug:
            print " finished! tuple:%s{%s}" % (t, id(t))
        self.protocol.setObject(self.count, t)
        self.deferred.callback(t)
        return t, ready_deferred

    def receiveClose(self):
        if self.debug:
            print "%s[%d].receiveClose" % (self, self.count)
        self.finished = 1

        if self.num_unreferenceable_children:
            # not finished yet, we'll fire our Deferred when we are
            if self.debug:
                print " not finished yet"
            ready_deferred = None
            if self._ready_deferreds:
                ready_deferred = AsyncAND(self._ready_deferreds)
            return self.deferred, ready_deferred

        # the list is already complete
        return self.complete()

    def describe(self):
        return "[%d]" % len(self.list)

class TupleConstraint(OpenerConstraint):
    opentypes = [("tuple",)]
    name = "TupleConstraint"

    def __init__(self, *elemConstraints):
        self.constraints = [IConstraint(e) for e in elemConstraints]
    def checkObject(self, obj, inbound):
        if not isinstance(obj, tuple):
            raise Violation("not a tuple")
        if len(obj) != len(self.constraints):
            raise Violation("wrong size tuple")
        for i in range(len(self.constraints)):
            self.constraints[i].checkObject(obj[i], inbound)


text:
from ..utils import format_coord, format_time, render_view_url

BAD_FRUIT_CRUD_ARGS = [
    ({"kind": None}, {"kind": ["This field may not be null."]}),
    ({"kind": ""}, {"kind": ["This field may not be null."]}),
    ({"kind": "nonexistent"}, {"kind": ["nonexistent is not a valid Kind key."]}),
    ({"lat": None}, {"lat": ["This field may not be null."]}),
    ({"lat": ""}, {"lat": ["A valid number is required."]}),
    ({"lat": "NaN"}, {"lat": ["A valid number is required."]}),
    (
        {"lat": "60.1234564567890"},
        {"lat": ["Ensure that there are no more than 13 digits in total."]},
    ),
    ({"lng": None}, {"lng": ["This field may not be null."]}),
    ({"lng": ""}, {"lng": ["A valid number is required."]}),
    ({"lng": "NaN"}, {"lng": ["A valid number is required."]}),
    (
        {"lng": "60.1234564567890"},
        {"lng": ["Ensure that there are no more than 13 digits in total."]},
    ),
]

def fruit_to_data(fruit, response):
    return {
        "id": fruit.id,
        "lat": format_coord(fruit.position.y),
        "lng": format_coord(fruit.position.x),
        "kind": fruit.kind.key,
        "time": format_time(fruit.created),
        "url": render_view_url(response, "api:fruit-detail", fruit.id),
    }

def fruit_to_verbose_data(fruit, response):
    return {
        "id": fruit.id,
        "lat": format_coord(fruit.position.y),
        "lng": format_coord(fruit.position.x),
        "kind": fruit.kind.key,
        "time": format_time(fruit.created),
        "url": render_view_url(response, "api:fruit-detail", fruit.id),
        "description": fruit.description,
        "user": {
            "id": fruit.user.id,
            "username": fruit.user.username,
            "url": render_view_url(response, "api:users-detail", fruit.user.id),
        },
        "images_count": 0,
        "images": render_view_url(response, "api:image-list", fruit.id),
    }


text:
package alert

import (
	"errors"
	"io"
	"net/http"
	"os"
	"path"
	"strings"

	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
)

type CreateAlertAttachmentRequest struct {
	client.BaseRequest
	IdentifierType  AlertIdentifier
	IdentifierValue string
	FileName        string
	FilePath        string
	User            string
	IndexFile       string
}

func (r *CreateAlertAttachmentRequest) Metadata(ar client.ApiRequest) map[string]interface{} {
	headers := make(map[string]interface{})

	formDataMap := make(map[string]io.Reader)
	filePath := path.Join(r.FilePath, r.FileName)
	file, _ := os.Open(filePath)

	formDataMap["file"] = file
	formDataMap["user"] = strings.NewReader(r.User)
	formDataMap["indexFile"] = strings.NewReader(r.IndexFile)
	headers["form-data-values"] = formDataMap

	return headers
}

func (r *CreateAlertAttachmentRequest) Validate() error {
	if r.FileName == "" {
		return errors.New("FileName can not be empty")
	}
	if r.FilePath == "" {
		return errors.New("FilePath can not be empty")
	}
	if r.IdentifierValue == "" {
		return errors.New("Identifier can not be empty")
	}
	return nil
}

func (r *CreateAlertAttachmentRequest) ResourcePath() string {

	return "/v2/alerts/" + r.IdentifierValue + "/attachments"
}

func (r *CreateAlertAttachmentRequest) Method() string {
	return http.MethodPost
}

func (r *CreateAlertAttachmentRequest) RequestParams() map[string]string {

	params := make(map[string]string)

	if r.IdentifierType == ALIAS {
		params["alertIdentifierType"] = "alias"

	} else if r.IdentifierType == TINYID {
		params["alertIdentifierType"] = "tiny"

	} else {
		params["alertIdentifierType"] = "id"

	}
	return params
}