prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>test_amino_acids.py<|end_file_name|><|fim▁begin|>from nose.tools import eq_<|fim▁hole|> canonical_amino_acids,
canonical_amino_acid_letters,
extended_amino_acids,
extended_amino_acid_letters,
)
def test_canonical_amino_acids():
assert len(canonical_amino_acids) == 20
def test_canonical_amino_acids_letters():
assert len(canonical_amino_acid_letters) == 20
assert "X" not in canonical_amino_acid_letters
expected_letters = [aa.letter for aa in canonical_amino_acids]
eq_(expected_letters, canonical_amino_acid_letters)
def test_extended_amino_acids():
assert len(extended_amino_acids) > 20
def test_extended_amino_acids_letters():
assert len(extended_amino_acid_letters) > 20
assert "X" in extended_amino_acid_letters
assert "J" in extended_amino_acid_letters
expected_letters = [aa.letter for aa in extended_amino_acids]
eq_(expected_letters, extended_amino_acid_letters)<|fim▁end|>
|
from pepdata.amino_acid_alphabet import (
|
<|file_name|>blogger-gen.go<|end_file_name|><|fim▁begin|>// Package blogger provides access to the Blogger API.
//
// See https://developers.google.com/blogger/docs/3.0/getting_started
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/blogger/v3"
// ...
// bloggerService, err := blogger.New(oauthHttpClient)
package blogger
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "blogger:v3"
const apiName = "blogger"
const apiVersion = "v3"
const basePath = "https://www.googleapis.com/blogger/v3/"
// OAuth2 scopes used by this API.
const (
// Manage your Blogger account
BloggerScope = "https://www.googleapis.com/auth/blogger"
// View your Blogger account
BloggerReadonlyScope = "https://www.googleapis.com/auth/blogger.readonly"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.BlogUserInfos = NewBlogUserInfosService(s)
s.Blogs = NewBlogsService(s)
s.Comments = NewCommentsService(s)
s.PageViews = NewPageViewsService(s)
s.Pages = NewPagesService(s)
s.PostUserInfos = NewPostUserInfosService(s)
s.Posts = NewPostsService(s)
s.Users = NewUsersService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
BlogUserInfos *BlogUserInfosService
Blogs *BlogsService
Comments *CommentsService
PageViews *PageViewsService
Pages *PagesService
PostUserInfos *PostUserInfosService
Posts *PostsService
Users *UsersService
}
func NewBlogUserInfosService(s *Service) *BlogUserInfosService {
rs := &BlogUserInfosService{s: s}
return rs
}
type BlogUserInfosService struct {
s *Service
}
func NewBlogsService(s *Service) *BlogsService {
rs := &BlogsService{s: s}
return rs
}
type BlogsService struct {
s *Service
}
func NewCommentsService(s *Service) *CommentsService {
rs := &CommentsService{s: s}
return rs
}
type CommentsService struct {
s *Service
}
func NewPageViewsService(s *Service) *PageViewsService {
rs := &PageViewsService{s: s}
return rs
}
type PageViewsService struct {
s *Service
}
func NewPagesService(s *Service) *PagesService {
rs := &PagesService{s: s}
return rs
}
type PagesService struct {
s *Service
}
func NewPostUserInfosService(s *Service) *PostUserInfosService {
rs := &PostUserInfosService{s: s}
return rs
}
type PostUserInfosService struct {
s *Service
}
func NewPostsService(s *Service) *PostsService {
rs := &PostsService{s: s}
return rs
}
type PostsService struct {
s *Service
}
func NewUsersService(s *Service) *UsersService {
rs := &UsersService{s: s}
return rs
}
type UsersService struct {
s *Service
}
type Blog struct {
// CustomMetaData: The JSON custom meta-data for the Blog
CustomMetaData string `json:"customMetaData,omitempty"`
// Description: The description of this blog. This is displayed
// underneath the title.
Description string `json:"description,omitempty"`
// Id: The identifier for this resource.
Id string `json:"id,omitempty"`
// Kind: The kind of this entry. Always blogger#blog
Kind string `json:"kind,omitempty"`
// Locale: The locale this Blog is set to.
Locale *BlogLocale `json:"locale,omitempty"`
// Name: The name of this blog. This is displayed as the title.
Name string `json:"name,omitempty"`
// Pages: The container of pages in this blog.
Pages *BlogPages `json:"pages,omitempty"`
// Posts: The container of posts in this blog.
Posts *BlogPosts `json:"posts,omitempty"`
// Published: RFC 3339 date-time when this blog was published.
Published string `json:"published,omitempty"`
// SelfLink: The API REST URL to fetch this resource from.
SelfLink string `json:"selfLink,omitempty"`
// Status: The status of the blog.
Status string `json:"status,omitempty"`
// Updated: RFC 3339 date-time when this blog was last updated.
Updated string `json:"updated,omitempty"`
// Url: The URL where this blog is published.
Url string `json:"url,omitempty"`
}
type BlogLocale struct {
// Country: The country this blog's locale is set to.
Country string `json:"country,omitempty"`
// Language: The language this blog is authored in.
Language string `json:"language,omitempty"`
// Variant: The language variant this blog is authored in.
Variant string `json:"variant,omitempty"`
}
type BlogPages struct {
// SelfLink: The URL of the container for pages in this blog.
SelfLink string `json:"selfLink,omitempty"`
// TotalItems: The count of pages in this blog.
TotalItems int64 `json:"totalItems,omitempty"`
}
type BlogPosts struct {
// Items: The List of Posts for this Blog.
Items []*Post `json:"items,omitempty"`
// SelfLink: The URL of the container for posts in this blog.
SelfLink string `json:"selfLink,omitempty"`
// TotalItems: The count of posts in this blog.
TotalItems int64 `json:"totalItems,omitempty"`
}
type BlogList struct {
// BlogUserInfos: Admin level list of blog per-user information
BlogUserInfos []*BlogUserInfo `json:"blogUserInfos,omitempty"`
// Items: The list of Blogs this user has Authorship or Admin rights
// over.
Items []*Blog `json:"items,omitempty"`
// Kind: The kind of this entity. Always blogger#blogList
Kind string `json:"kind,omitempty"`
}
type BlogPerUserInfo struct {
// BlogId: ID of the Blog resource
BlogId string `json:"blogId,omitempty"`
// HasAdminAccess: True if the user has Admin level access to the blog.
HasAdminAccess bool `json:"hasAdminAccess,omitempty"`
// Kind: The kind of this entity. Always blogger#blogPerUserInfo
Kind string `json:"kind,omitempty"`
// PhotosAlbumKey: The Photo Album Key for the user when adding photos
// to the blog
PhotosAlbumKey string `json:"photosAlbumKey,omitempty"`
// Role: Access permissions that the user has for the blog (ADMIN,
// AUTHOR, or READER).
Role string `json:"role,omitempty"`
// UserId: ID of the User
UserId string `json:"userId,omitempty"`
}
type BlogUserInfo struct {
// Blog: The Blog resource.
Blog *Blog `json:"blog,omitempty"`
// Blog_user_info: Information about a User for the Blog.
Blog_user_info *BlogPerUserInfo `json:"blog_user_info,omitempty"`
// Kind: The kind of this entity. Always blogger#blogUserInfo
Kind string `json:"kind,omitempty"`
}
type Comment struct {
// Author: The author of this Comment.
Author *CommentAuthor `json:"author,omitempty"`
// Blog: Data about the blog containing this comment.
Blog *CommentBlog `json:"blog,omitempty"`
// Content: The actual content of the comment. May include HTML markup.
Content string `json:"content,omitempty"`
// Id: The identifier for this resource.
Id string `json:"id,omitempty"`
// InReplyTo: Data about the comment this is in reply to.
InReplyTo *CommentInReplyTo `json:"inReplyTo,omitempty"`
// Kind: The kind of this entry. Always blogger#comment
Kind string `json:"kind,omitempty"`
// Post: Data about the post containing this comment.
Post *CommentPost `json:"post,omitempty"`
// Published: RFC 3339 date-time when this comment was published.
Published string `json:"published,omitempty"`
// SelfLink: The API REST URL to fetch this resource from.
SelfLink string `json:"selfLink,omitempty"`
// Status: The status of the comment (only populated for admin users)
Status string `json:"status,omitempty"`
// Updated: RFC 3339 date-time when this comment was last updated.
Updated string `json:"updated,omitempty"`
}
type CommentAuthor struct {
// DisplayName: The display name.
DisplayName string `json:"displayName,omitempty"`
// Id: The identifier of the Comment creator.
Id string `json:"id,omitempty"`
// Image: The comment creator's avatar.
Image *CommentAuthorImage `json:"image,omitempty"`
// Url: The URL of the Comment creator's Profile page.
Url string `json:"url,omitempty"`
}
type CommentAuthorImage struct {
// Url: The comment creator's avatar URL.
Url string `json:"url,omitempty"`
}
type CommentBlog struct {
// Id: The identifier of the blog containing this comment.
Id string `json:"id,omitempty"`
}
type CommentInReplyTo struct {
// Id: The identified of the parent of this comment.
Id string `json:"id,omitempty"`
}
type CommentPost struct {
// Id: The identifier of the post containing this comment.
Id string `json:"id,omitempty"`
}
type CommentList struct {
// Items: The List of Comments for a Post.
Items []*Comment `json:"items,omitempty"`
// Kind: The kind of this entry. Always blogger#commentList
Kind string `json:"kind,omitempty"`
// NextPageToken: Pagination token to fetch the next page, if one
// exists.
NextPageToken string `json:"nextPageToken,omitempty"`
// PrevPageToken: Pagination token to fetch the previous page, if one
// exists.
PrevPageToken string `json:"prevPageToken,omitempty"`
}
type Page struct {
// Author: The author of this Page.
Author *PageAuthor `json:"author,omitempty"`
// Blog: Data about the blog containing this Page.
Blog *PageBlog `json:"blog,omitempty"`
// Content: The body content of this Page, in HTML.
Content string `json:"content,omitempty"`
// Etag: Etag of the resource.
Etag string `json:"etag,omitempty"`
// Id: The identifier for this resource.
Id string `json:"id,omitempty"`
// Kind: The kind of this entity. Always blogger#page
Kind string `json:"kind,omitempty"`
// Published: RFC 3339 date-time when this Page was published.
Published string `json:"published,omitempty"`
// SelfLink: The API REST URL to fetch this resource from.
SelfLink string `json:"selfLink,omitempty"`
// Status: The status of the page for admin resources (either LIVE or
// DRAFT).
Status string `json:"status,omitempty"`
// Title: The title of this entity. This is the name displayed in the
// Admin user interface.
Title string `json:"title,omitempty"`
// Updated: RFC 3339 date-time when this Page was last updated.
Updated string `json:"updated,omitempty"`
// Url: The URL that this Page is displayed at.
Url string `json:"url,omitempty"`
}
type PageAuthor struct {
// DisplayName: The display name.
DisplayName string `json:"displayName,omitempty"`
// Id: The identifier of the Page creator.
Id string `json:"id,omitempty"`
// Image: The page author's avatar.
Image *PageAuthorImage `json:"image,omitempty"`
// Url: The URL of the Page creator's Profile page.
Url string `json:"url,omitempty"`
}
type PageAuthorImage struct {
// Url: The page author's avatar URL.
Url string `json:"url,omitempty"`
}
type PageBlog struct {
// Id: The identifier of the blog containing this page.
Id string `json:"id,omitempty"`
}
type PageList struct {
// Items: The list of Pages for a Blog.
Items []*Page `json:"items,omitempty"`
// Kind: The kind of this entity. Always blogger#pageList
Kind string `json:"kind,omitempty"`
}
type Pageviews struct {
// BlogId: Blog Id
BlogId string `json:"blogId,omitempty"`
// Counts: The container of posts in this blog.
Counts []*PageviewsCounts `json:"counts,omitempty"`
// Kind: The kind of this entry. Always blogger#page_views
Kind string `json:"kind,omitempty"`
}
type PageviewsCounts struct {
// Count: Count of page views for the given time range
Count int64 `json:"count,omitempty,string"`
// TimeRange: Time range the given count applies to
TimeRange string `json:"timeRange,omitempty"`
}
type Post struct {
// Author: The author of this Post.
Author *PostAuthor `json:"author,omitempty"`
// Blog: Data about the blog containing this Post.
Blog *PostBlog `json:"blog,omitempty"`
// Content: The content of the Post. May contain HTML markup.
Content string `json:"content,omitempty"`
// CustomMetaData: The JSON meta-data for the Post.
CustomMetaData string `json:"customMetaData,omitempty"`
// Etag: Etag of the resource.
Etag string `json:"etag,omitempty"`
// Id: The identifier of this Post.
Id string `json:"id,omitempty"`
// Images: Display image for the Post.
Images []*PostImages `json:"images,omitempty"`
// Kind: The kind of this entity. Always blogger#post
Kind string `json:"kind,omitempty"`
// Labels: The list of labels this Post was tagged with.
Labels []string `json:"labels,omitempty"`
// Location: The location for geotagged posts.
Location *PostLocation `json:"location,omitempty"`
// Published: RFC 3339 date-time when this Post was published.
Published string `json:"published,omitempty"`
// ReaderComments: Comment control and display setting for readers of
// this post.
ReaderComments string `json:"readerComments,omitempty"`
// Replies: The container of comments on this Post.
Replies *PostReplies `json:"replies,omitempty"`
// SelfLink: The API REST URL to fetch this resource from.
SelfLink string `json:"selfLink,omitempty"`
// Status: Status of the post. Only set for admin-level requests
Status string `json:"status,omitempty"`
// Title: The title of the Post.
Title string `json:"title,omitempty"`
// TitleLink: The title link URL, similar to atom's related link.
TitleLink string `json:"titleLink,omitempty"`
// Updated: RFC 3339 date-time when this Post was last updated.
Updated string `json:"updated,omitempty"`
// Url: The URL where this Post is displayed.
Url string `json:"url,omitempty"`
}
type PostAuthor struct {
// DisplayName: The display name.
DisplayName string `json:"displayName,omitempty"`
// Id: The identifier of the Post creator.
Id string `json:"id,omitempty"`
// Image: The Post author's avatar.
Image *PostAuthorImage `json:"image,omitempty"`
// Url: The URL of the Post creator's Profile page.
Url string `json:"url,omitempty"`
}
type PostAuthorImage struct {
// Url: The Post author's avatar URL.
Url string `json:"url,omitempty"`
}
type PostBlog struct {
// Id: The identifier of the Blog that contains this Post.
Id string `json:"id,omitempty"`
}
type PostImages struct {
Url string `json:"url,omitempty"`
}
type PostLocation struct {
// Lat: Location's latitude.
Lat float64 `json:"lat,omitempty"`
// Lng: Location's longitude.
Lng float64 `json:"lng,omitempty"`
// Name: Location name.
Name string `json:"name,omitempty"`
// Span: Location's viewport span. Can be used when rendering a map
// preview.
Span string `json:"span,omitempty"`
}
type PostReplies struct {
// Items: The List of Comments for this Post.
Items []*Comment `json:"items,omitempty"`
// SelfLink: The URL of the comments on this post.
SelfLink string `json:"selfLink,omitempty"`
// TotalItems: The count of comments on this post.
TotalItems int64 `json:"totalItems,omitempty,string"`
}
type PostList struct {
// Items: The list of Posts for this Blog.
Items []*Post `json:"items,omitempty"`
// Kind: The kind of this entity. Always blogger#postList
Kind string `json:"kind,omitempty"`
// NextPageToken: Pagination token to fetch the next page, if one
// exists.
NextPageToken string `json:"nextPageToken,omitempty"`
}
type PostPerUserInfo struct {
// BlogId: ID of the Blog that the post resource belongs to.
BlogId string `json:"blogId,omitempty"`
// HasEditAccess: True if the user has Author level access to the post.
HasEditAccess bool `json:"hasEditAccess,omitempty"`
// Kind: The kind of this entity. Always blogger#postPerUserInfo
Kind string `json:"kind,omitempty"`
// PostId: ID of the Post resource.
PostId string `json:"postId,omitempty"`
// UserId: ID of the User.
UserId string `json:"userId,omitempty"`
}
type PostUserInfo struct {
// Kind: The kind of this entity. Always blogger#postUserInfo
Kind string `json:"kind,omitempty"`
// Post: The Post resource.
Post *Post `json:"post,omitempty"`
// Post_user_info: Information about a User for the Post.
Post_user_info *PostPerUserInfo `json:"post_user_info,omitempty"`
}
type PostUserInfosList struct {
// Items: The list of Posts with User information for the post, for this
// Blog.
Items []*PostUserInfo `json:"items,omitempty"`
// Kind: The kind of this entity. Always blogger#postList
Kind string `json:"kind,omitempty"`
// NextPageToken: Pagination token to fetch the next page, if one
// exists.
NextPageToken string `json:"nextPageToken,omitempty"`
}
type User struct {
// About: Profile summary information.
About string `json:"about,omitempty"`
// Blogs: The container of blogs for this user.
Blogs *UserBlogs `json:"blogs,omitempty"`
// Created: The timestamp of when this profile was created, in seconds
// since epoch.
Created string `json:"created,omitempty"`
// DisplayName: The display name.
DisplayName string `json:"displayName,omitempty"`
// Id: The identifier for this User.
Id string `json:"id,omitempty"`
// Kind: The kind of this entity. Always blogger#user
Kind string `json:"kind,omitempty"`
// Locale: This user's locale
Locale *UserLocale `json:"locale,omitempty"`
// SelfLink: The API REST URL to fetch this resource from.
SelfLink string `json:"selfLink,omitempty"`
// Url: The user's profile page.
Url string `json:"url,omitempty"`
}
type UserBlogs struct {
// SelfLink: The URL of the Blogs for this user.
SelfLink string `json:"selfLink,omitempty"`
}
type UserLocale struct {
// Country: The user's country setting.
Country string `json:"country,omitempty"`
// Language: The user's language setting.
Language string `json:"language,omitempty"`
// Variant: The user's language variant setting.
Variant string `json:"variant,omitempty"`
}
// method id "blogger.blogUserInfos.get":
type BlogUserInfosGetCall struct {
s *Service
userId string
blogId string
opt_ map[string]interface{}
}
// Get: Gets one blog and user info pair by blogId and userId.
func (r *BlogUserInfosService) Get(userId string, blogId string) *BlogUserInfosGetCall {
c := &BlogUserInfosGetCall{s: r.s, opt_: make(map[string]interface{})}
c.userId = userId
c.blogId = blogId
return c
}
// MaxPosts sets the optional parameter "maxPosts": Maximum number of
// posts to pull back with the blog.
func (c *BlogUserInfosGetCall) MaxPosts(maxPosts int64) *BlogUserInfosGetCall {
c.opt_["maxPosts"] = maxPosts
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BlogUserInfosGetCall) Fields(s ...googleapi.Field) *BlogUserInfosGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *BlogUserInfosGetCall) Do() (*BlogUserInfo, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxPosts"]; ok {
params.Set("maxPosts", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userId}/blogs/{blogId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"userId": c.userId,
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *BlogUserInfo
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one blog and user info pair by blogId and userId.",
// "httpMethod": "GET",
// "id": "blogger.blogUserInfos.get",
// "parameterOrder": [
// "userId",
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the blog to get.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "maxPosts": {
// "description": "Maximum number of posts to pull back with the blog.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "userId": {
// "description": "ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "users/{userId}/blogs/{blogId}",
// "response": {
// "$ref": "BlogUserInfo"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.blogs.get":
type BlogsGetCall struct {
s *Service
blogId string
opt_ map[string]interface{}
}
// Get: Gets one blog by ID.
func (r *BlogsService) Get(blogId string) *BlogsGetCall {
c := &BlogsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
return c
}
// MaxPosts sets the optional parameter "maxPosts": Maximum number of
// posts to pull back with the blog.
func (c *BlogsGetCall) MaxPosts(maxPosts int64) *BlogsGetCall {
c.opt_["maxPosts"] = maxPosts
return c
}
// View sets the optional parameter "view": Access level with which to
// view the blog. Note that some fields require elevated access.
func (c *BlogsGetCall) View(view string) *BlogsGetCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BlogsGetCall) Fields(s ...googleapi.Field) *BlogsGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *BlogsGetCall) Do() (*Blog, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxPosts"]; ok {
params.Set("maxPosts", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Blog
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one blog by ID.",
// "httpMethod": "GET",
// "id": "blogger.blogs.get",
// "parameterOrder": [
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the blog to get.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "maxPosts": {
// "description": "Maximum number of posts to pull back with the blog.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "view": {
// "description": "Access level with which to view the blog. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail.",
// "Author level detail.",
// "Reader level detail."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}",
// "response": {
// "$ref": "Blog"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.blogs.getByUrl":
type BlogsGetByUrlCall struct {
s *Service
url string
opt_ map[string]interface{}
}
// GetByUrl: Retrieve a Blog by URL.
func (r *BlogsService) GetByUrl(url string) *BlogsGetByUrlCall {
c := &BlogsGetByUrlCall{s: r.s, opt_: make(map[string]interface{})}
c.url = url
return c
}
// View sets the optional parameter "view": Access level with which to
// view the blog. Note that some fields require elevated access.
func (c *BlogsGetByUrlCall) View(view string) *BlogsGetByUrlCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BlogsGetByUrlCall) Fields(s ...googleapi.Field) *BlogsGetByUrlCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *BlogsGetByUrlCall) Do() (*Blog, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
params.Set("url", fmt.Sprintf("%v", c.url))
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/byurl")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Blog
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieve a Blog by URL.",
// "httpMethod": "GET",
// "id": "blogger.blogs.getByUrl",
// "parameterOrder": [
// "url"
// ],
// "parameters": {
// "url": {
// "description": "The URL of the blog to retrieve.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the blog. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail.",
// "Author level detail.",
// "Reader level detail."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/byurl",
// "response": {
// "$ref": "Blog"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.blogs.listByUser":
type BlogsListByUserCall struct {
s *Service
userId string
opt_ map[string]interface{}
}
// ListByUser: Retrieves a list of blogs, possibly filtered.
func (r *BlogsService) ListByUser(userId string) *BlogsListByUserCall {
c := &BlogsListByUserCall{s: r.s, opt_: make(map[string]interface{})}
c.userId = userId
return c
}
// FetchUserInfo sets the optional parameter "fetchUserInfo": Whether
// the response is a list of blogs with per-user information instead of
// just blogs.
func (c *BlogsListByUserCall) FetchUserInfo(fetchUserInfo bool) *BlogsListByUserCall {
c.opt_["fetchUserInfo"] = fetchUserInfo
return c
}
// Role sets the optional parameter "role": User access types for blogs
// to include in the results, e.g. AUTHOR will return blogs where the
// user has author level access. If no roles are specified, defaults to
// ADMIN and AUTHOR roles.
func (c *BlogsListByUserCall) Role(role string) *BlogsListByUserCall {
c.opt_["role"] = role
return c
}
// Status sets the optional parameter "status": Blog statuses to include
// in the result (default: Live blogs only). Note that ADMIN access is
// required to view deleted blogs.
func (c *BlogsListByUserCall) Status(status string) *BlogsListByUserCall {
c.opt_["status"] = status
return c
}
// View sets the optional parameter "view": Access level with which to
// view the blogs. Note that some fields require elevated access.
func (c *BlogsListByUserCall) View(view string) *BlogsListByUserCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BlogsListByUserCall) Fields(s ...googleapi.Field) *BlogsListByUserCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *BlogsListByUserCall) Do() (*BlogList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fetchUserInfo"]; ok {
params.Set("fetchUserInfo", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["role"]; ok {
params.Set("role", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["status"]; ok {
params.Set("status", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userId}/blogs")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"userId": c.userId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *BlogList
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of blogs, possibly filtered.",
// "httpMethod": "GET",
// "id": "blogger.blogs.listByUser",
// "parameterOrder": [
// "userId"
// ],
// "parameters": {
// "fetchUserInfo": {
// "description": "Whether the response is a list of blogs with per-user information instead of just blogs.",
// "location": "query",
// "type": "boolean"
// },
// "role": {
// "description": "User access types for blogs to include in the results, e.g. AUTHOR will return blogs where the user has author level access. If no roles are specified, defaults to ADMIN and AUTHOR roles.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin role - Blogs where the user has Admin level access.",
// "Author role - Blogs where the user has Author level access.",
// "Reader role - Blogs where the user has Reader level access (to a private blog)."
// ],
// "location": "query",
// "repeated": true,
// "type": "string"
// },
// "status": {
// "default": "LIVE",
// "description": "Blog statuses to include in the result (default: Live blogs only). Note that ADMIN access is required to view deleted blogs.",
// "enum": [
// "DELETED",
// "LIVE"
// ],
// "enumDescriptions": [
// "Blog has been deleted by an administrator.",
// "Blog is currently live."
// ],
// "location": "query",
// "repeated": true,
// "type": "string"
// },
// "userId": {
// "description": "ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the blogs. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail.",
// "Author level detail.",
// "Reader level detail."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "users/{userId}/blogs",
// "response": {
// "$ref": "BlogList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.comments.approve":
type CommentsApproveCall struct {
s *Service
blogId string
postId string
commentId string
opt_ map[string]interface{}
}
// Approve: Marks a comment as not spam.
func (r *CommentsService) Approve(blogId string, postId string, commentId string) *CommentsApproveCall {
c := &CommentsApproveCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
c.commentId = commentId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsApproveCall) Fields(s ...googleapi.Field) *CommentsApproveCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *CommentsApproveCall) Do() (*Comment, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/comments/{commentId}/approve")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
"commentId": c.commentId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Comment
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Marks a comment as not spam.",
// "httpMethod": "POST",
// "id": "blogger.comments.approve",
// "parameterOrder": [
// "blogId",
// "postId",
// "commentId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "commentId": {
// "description": "The ID of the comment to mark as not spam.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/comments/{commentId}/approve",
// "response": {
// "$ref": "Comment"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.comments.delete":
type CommentsDeleteCall struct {
s *Service
blogId string
postId string
commentId string
opt_ map[string]interface{}
}
// Delete: Delete a comment by ID.
func (r *CommentsService) Delete(blogId string, postId string, commentId string) *CommentsDeleteCall {
c := &CommentsDeleteCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
c.commentId = commentId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsDeleteCall) Fields(s ...googleapi.Field) *CommentsDeleteCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *CommentsDeleteCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/comments/{commentId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
"commentId": c.commentId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Delete a comment by ID.",
// "httpMethod": "DELETE",
// "id": "blogger.comments.delete",
// "parameterOrder": [
// "blogId",
// "postId",
// "commentId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "commentId": {
// "description": "The ID of the comment to delete.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/comments/{commentId}",
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.comments.get":
type CommentsGetCall struct {
s *Service
blogId string
postId string
commentId string
opt_ map[string]interface{}
}
// Get: Gets one comment by ID.
func (r *CommentsService) Get(blogId string, postId string, commentId string) *CommentsGetCall {
c := &CommentsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
c.commentId = commentId
return c
}
// View sets the optional parameter "view": Access level for the
// requested comment (default: READER). Note that some comments will
// require elevated permissions, for example comments where the parent
// posts which is in a draft state, or comments that are pending
// moderation.
func (c *CommentsGetCall) View(view string) *CommentsGetCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsGetCall) Fields(s ...googleapi.Field) *CommentsGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *CommentsGetCall) Do() (*Comment, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/comments/{commentId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
"commentId": c.commentId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Comment
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one comment by ID.",
// "httpMethod": "GET",
// "id": "blogger.comments.get",
// "parameterOrder": [
// "blogId",
// "postId",
// "commentId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to containing the comment.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "commentId": {
// "description": "The ID of the comment to get.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "ID of the post to fetch posts from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Access level for the requested comment (default: READER). Note that some comments will require elevated permissions, for example comments where the parent posts which is in a draft state, or comments that are pending moderation.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Admin level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/comments/{commentId}",
// "response": {
// "$ref": "Comment"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.comments.list":
type CommentsListCall struct {
s *Service
blogId string
postId string
opt_ map[string]interface{}
}
// List: Retrieves the comments for a post, possibly filtered.
func (r *CommentsService) List(blogId string, postId string) *CommentsListCall {
c := &CommentsListCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
return c
}
// EndDate sets the optional parameter "endDate": Latest date of comment
// to fetch, a date-time with RFC 3339 formatting.
func (c *CommentsListCall) EndDate(endDate string) *CommentsListCall {
c.opt_["endDate"] = endDate
return c
}
// FetchBodies sets the optional parameter "fetchBodies": Whether the
// body content of the comments is included.
func (c *CommentsListCall) FetchBodies(fetchBodies bool) *CommentsListCall {
c.opt_["fetchBodies"] = fetchBodies
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of comments to include in the result.
func (c *CommentsListCall) MaxResults(maxResults int64) *CommentsListCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// if request is paged.
func (c *CommentsListCall) PageToken(pageToken string) *CommentsListCall {
c.opt_["pageToken"] = pageToken
return c
}
// StartDate sets the optional parameter "startDate": Earliest date of
// comment to fetch, a date-time with RFC 3339 formatting.
func (c *CommentsListCall) StartDate(startDate string) *CommentsListCall {
c.opt_["startDate"] = startDate
return c
}
// Status sets the optional parameter "status":
func (c *CommentsListCall) Status(status string) *CommentsListCall {
c.opt_["status"] = status
return c
}
// View sets the optional parameter "view": Access level with which to
// view the returned result. Note that some fields require elevated
// access.
func (c *CommentsListCall) View(view string) *CommentsListCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsListCall) Fields(s ...googleapi.Field) *CommentsListCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *CommentsListCall) Do() (*CommentList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["endDate"]; ok {
params.Set("endDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchBodies"]; ok {
params.Set("fetchBodies", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["startDate"]; ok {
params.Set("startDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["status"]; ok {
params.Set("status", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/comments")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *CommentList
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the comments for a post, possibly filtered.",
// "httpMethod": "GET",
// "id": "blogger.comments.list",
// "parameterOrder": [
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch comments from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "endDate": {
// "description": "Latest date of comment to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "fetchBodies": {
// "description": "Whether the body content of the comments is included.",
// "location": "query",
// "type": "boolean"
// },
// "maxResults": {
// "description": "Maximum number of comments to include in the result.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token if request is paged.",
// "location": "query",
// "type": "string"
// },
// "postId": {
// "description": "ID of the post to fetch posts from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "startDate": {
// "description": "Earliest date of comment to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "status": {
// "enum": [
// "emptied",
// "live",
// "pending",
// "spam"
// ],
// "enumDescriptions": [
// "Comments that have had their content removed",
// "Comments that are publicly visible",
// "Comments that are awaiting administrator approval",
// "Comments marked as spam by the administrator"
// ],
// "location": "query",
// "repeated": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the returned result. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Reader level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/comments",
// "response": {
// "$ref": "CommentList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.comments.listByBlog":
type CommentsListByBlogCall struct {
s *Service
blogId string
opt_ map[string]interface{}
}
// ListByBlog: Retrieves the comments for a blog, across all posts,
// possibly filtered.
func (r *CommentsService) ListByBlog(blogId string) *CommentsListByBlogCall {
c := &CommentsListByBlogCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
return c
}
// EndDate sets the optional parameter "endDate": Latest date of comment
// to fetch, a date-time with RFC 3339 formatting.
func (c *CommentsListByBlogCall) EndDate(endDate string) *CommentsListByBlogCall {
c.opt_["endDate"] = endDate
return c
}
// FetchBodies sets the optional parameter "fetchBodies": Whether the
// body content of the comments is included.
func (c *CommentsListByBlogCall) FetchBodies(fetchBodies bool) *CommentsListByBlogCall {
c.opt_["fetchBodies"] = fetchBodies
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of comments to include in the result.
func (c *CommentsListByBlogCall) MaxResults(maxResults int64) *CommentsListByBlogCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// if request is paged.
func (c *CommentsListByBlogCall) PageToken(pageToken string) *CommentsListByBlogCall {
c.opt_["pageToken"] = pageToken
return c
}
// StartDate sets the optional parameter "startDate": Earliest date of
// comment to fetch, a date-time with RFC 3339 formatting.
func (c *CommentsListByBlogCall) StartDate(startDate string) *CommentsListByBlogCall {
c.opt_["startDate"] = startDate
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsListByBlogCall) Fields(s ...googleapi.Field) *CommentsListByBlogCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *CommentsListByBlogCall) Do() (*CommentList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["endDate"]; ok {
params.Set("endDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchBodies"]; ok {
params.Set("fetchBodies", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["startDate"]; ok {
params.Set("startDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/comments")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *CommentList
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the comments for a blog, across all posts, possibly filtered.",
// "httpMethod": "GET",
// "id": "blogger.comments.listByBlog",
// "parameterOrder": [
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch comments from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "endDate": {
// "description": "Latest date of comment to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "fetchBodies": {
// "description": "Whether the body content of the comments is included.",
// "location": "query",
// "type": "boolean"
// },
// "maxResults": {
// "description": "Maximum number of comments to include in the result.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token if request is paged.",
// "location": "query",
// "type": "string"
// },
// "startDate": {
// "description": "Earliest date of comment to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/comments",
// "response": {
// "$ref": "CommentList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.comments.markAsSpam":
type CommentsMarkAsSpamCall struct {
s *Service
blogId string
postId string
commentId string
opt_ map[string]interface{}
}
// MarkAsSpam: Marks a comment as spam.
func (r *CommentsService) MarkAsSpam(blogId string, postId string, commentId string) *CommentsMarkAsSpamCall {
c := &CommentsMarkAsSpamCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
c.commentId = commentId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsMarkAsSpamCall) Fields(s ...googleapi.Field) *CommentsMarkAsSpamCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *CommentsMarkAsSpamCall) Do() (*Comment, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/comments/{commentId}/spam")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
"commentId": c.commentId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Comment
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Marks a comment as spam.",
// "httpMethod": "POST",
// "id": "blogger.comments.markAsSpam",
// "parameterOrder": [
// "blogId",
// "postId",
// "commentId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "commentId": {
// "description": "The ID of the comment to mark as spam.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/comments/{commentId}/spam",
// "response": {
// "$ref": "Comment"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.comments.removeContent":
type CommentsRemoveContentCall struct {
s *Service
blogId string
postId string
commentId string
opt_ map[string]interface{}
}
// RemoveContent: Removes the content of a comment.
func (r *CommentsService) RemoveContent(blogId string, postId string, commentId string) *CommentsRemoveContentCall {
c := &CommentsRemoveContentCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
c.commentId = commentId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsRemoveContentCall) Fields(s ...googleapi.Field) *CommentsRemoveContentCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *CommentsRemoveContentCall) Do() (*Comment, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/comments/{commentId}/removecontent")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
"commentId": c.commentId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Comment
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Removes the content of a comment.",
// "httpMethod": "POST",
// "id": "blogger.comments.removeContent",
// "parameterOrder": [
// "blogId",
// "postId",
// "commentId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "commentId": {
// "description": "The ID of the comment to delete content from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/comments/{commentId}/removecontent",
// "response": {
// "$ref": "Comment"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.pageViews.get":
type PageViewsGetCall struct {
s *Service
blogId string
opt_ map[string]interface{}
}
// Get: Retrieve pageview stats for a Blog.
func (r *PageViewsService) Get(blogId string) *PageViewsGetCall {
c := &PageViewsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
return c
}
// Range sets the optional parameter "range":
func (c *PageViewsGetCall) Range(range_ string) *PageViewsGetCall {
c.opt_["range"] = range_
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PageViewsGetCall) Fields(s ...googleapi.Field) *PageViewsGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PageViewsGetCall) Do() (*Pageviews, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["range"]; ok {
params.Set("range", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pageviews")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Pageviews
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieve pageview stats for a Blog.",
// "httpMethod": "GET",
// "id": "blogger.pageViews.get",
// "parameterOrder": [
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the blog to get.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "range": {
// "enum": [
// "30DAYS",
// "7DAYS",
// "all"
// ],
// "enumDescriptions": [
// "Page view counts from the last thirty days.",
// "Page view counts from the last seven days.",
// "Total page view counts from all time."
// ],
// "location": "query",
// "repeated": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/pageviews",
// "response": {
// "$ref": "Pageviews"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.pages.delete":
type PagesDeleteCall struct {
s *Service
blogId string
pageId string
opt_ map[string]interface{}
}
// Delete: Delete a page by ID.
func (r *PagesService) Delete(blogId string, pageId string) *PagesDeleteCall {
c := &PagesDeleteCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.pageId = pageId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesDeleteCall) Fields(s ...googleapi.Field) *PagesDeleteCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesDeleteCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages/{pageId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"pageId": c.pageId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Delete a page by ID.",
// "httpMethod": "DELETE",
// "id": "blogger.pages.delete",
// "parameterOrder": [
// "blogId",
// "pageId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageId": {
// "description": "The ID of the Page.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/pages/{pageId}",
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.pages.get":
type PagesGetCall struct {
s *Service
blogId string
pageId string
opt_ map[string]interface{}
}
// Get: Gets one blog page by ID.
func (r *PagesService) Get(blogId string, pageId string) *PagesGetCall {
c := &PagesGetCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.pageId = pageId
return c
}
// View sets the optional parameter "view":
func (c *PagesGetCall) View(view string) *PagesGetCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesGetCall) Fields(s ...googleapi.Field) *PagesGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesGetCall) Do() (*Page, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages/{pageId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"pageId": c.pageId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Page
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one blog page by ID.",
// "httpMethod": "GET",
// "id": "blogger.pages.get",
// "parameterOrder": [
// "blogId",
// "pageId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog containing the page.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageId": {
// "description": "The ID of the page to get.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Reader level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/pages/{pageId}",
// "response": {
// "$ref": "Page"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.pages.insert":
type PagesInsertCall struct {
s *Service
blogId string
page *Page
opt_ map[string]interface{}
}
// Insert: Add a page.
func (r *PagesService) Insert(blogId string, page *Page) *PagesInsertCall {
c := &PagesInsertCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.page = page
return c
}
// IsDraft sets the optional parameter "isDraft": Whether to create the
// page as a draft (default: false).
func (c *PagesInsertCall) IsDraft(isDraft bool) *PagesInsertCall {
c.opt_["isDraft"] = isDraft
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesInsertCall) Fields(s ...googleapi.Field) *PagesInsertCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesInsertCall) Do() (*Page, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.page)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["isDraft"]; ok {
params.Set("isDraft", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Page
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Add a page.",
// "httpMethod": "POST",
// "id": "blogger.pages.insert",
// "parameterOrder": [
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to add the page to.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "isDraft": {
// "description": "Whether to create the page as a draft (default: false).",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "blogs/{blogId}/pages",
// "request": {
// "$ref": "Page"
// },
// "response": {
// "$ref": "Page"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.pages.list":
type PagesListCall struct {
s *Service
blogId string
opt_ map[string]interface{}
}
// List: Retrieves the pages for a blog, optionally including non-LIVE
// statuses.
func (r *PagesService) List(blogId string) *PagesListCall {
c := &PagesListCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
return c
}
// FetchBodies sets the optional parameter "fetchBodies": Whether to
// retrieve the Page bodies.
func (c *PagesListCall) FetchBodies(fetchBodies bool) *PagesListCall {
c.opt_["fetchBodies"] = fetchBodies
return c
}
// Status sets the optional parameter "status":
func (c *PagesListCall) Status(status string) *PagesListCall {
c.opt_["status"] = status
return c
}
// View sets the optional parameter "view": Access level with which to
// view the returned result. Note that some fields require elevated
// access.
func (c *PagesListCall) View(view string) *PagesListCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesListCall) Fields(s ...googleapi.Field) *PagesListCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesListCall) Do() (*PageList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fetchBodies"]; ok {
params.Set("fetchBodies", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["status"]; ok {
params.Set("status", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))<|fim▁hole|> }
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *PageList
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the pages for a blog, optionally including non-LIVE statuses.",
// "httpMethod": "GET",
// "id": "blogger.pages.list",
// "parameterOrder": [
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch pages from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "fetchBodies": {
// "description": "Whether to retrieve the Page bodies.",
// "location": "query",
// "type": "boolean"
// },
// "status": {
// "enum": [
// "draft",
// "live"
// ],
// "enumDescriptions": [
// "Draft (unpublished) Pages",
// "Pages that are publicly visible"
// ],
// "location": "query",
// "repeated": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the returned result. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Reader level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/pages",
// "response": {
// "$ref": "PageList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.pages.patch":
type PagesPatchCall struct {
s *Service
blogId string
pageId string
page *Page
opt_ map[string]interface{}
}
// Patch: Update a page. This method supports patch semantics.
func (r *PagesService) Patch(blogId string, pageId string, page *Page) *PagesPatchCall {
c := &PagesPatchCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.pageId = pageId
c.page = page
return c
}
// Publish sets the optional parameter "publish": Whether a publish
// action should be performed when the page is updated (default: false).
func (c *PagesPatchCall) Publish(publish bool) *PagesPatchCall {
c.opt_["publish"] = publish
return c
}
// Revert sets the optional parameter "revert": Whether a revert action
// should be performed when the page is updated (default: false).
func (c *PagesPatchCall) Revert(revert bool) *PagesPatchCall {
c.opt_["revert"] = revert
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesPatchCall) Fields(s ...googleapi.Field) *PagesPatchCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesPatchCall) Do() (*Page, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.page)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["publish"]; ok {
params.Set("publish", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["revert"]; ok {
params.Set("revert", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages/{pageId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"pageId": c.pageId,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Page
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Update a page. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "blogger.pages.patch",
// "parameterOrder": [
// "blogId",
// "pageId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageId": {
// "description": "The ID of the Page.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "publish": {
// "description": "Whether a publish action should be performed when the page is updated (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "revert": {
// "description": "Whether a revert action should be performed when the page is updated (default: false).",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "blogs/{blogId}/pages/{pageId}",
// "request": {
// "$ref": "Page"
// },
// "response": {
// "$ref": "Page"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.pages.publish":
type PagesPublishCall struct {
s *Service
blogId string
pageId string
opt_ map[string]interface{}
}
// Publish: Publishes a draft page.
func (r *PagesService) Publish(blogId string, pageId string) *PagesPublishCall {
c := &PagesPublishCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.pageId = pageId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesPublishCall) Fields(s ...googleapi.Field) *PagesPublishCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesPublishCall) Do() (*Page, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages/{pageId}/publish")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"pageId": c.pageId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Page
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Publishes a draft page.",
// "httpMethod": "POST",
// "id": "blogger.pages.publish",
// "parameterOrder": [
// "blogId",
// "pageId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageId": {
// "description": "The ID of the page.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/pages/{pageId}/publish",
// "response": {
// "$ref": "Page"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.pages.revert":
type PagesRevertCall struct {
s *Service
blogId string
pageId string
opt_ map[string]interface{}
}
// Revert: Revert a published or scheduled page to draft state.
func (r *PagesService) Revert(blogId string, pageId string) *PagesRevertCall {
c := &PagesRevertCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.pageId = pageId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesRevertCall) Fields(s ...googleapi.Field) *PagesRevertCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesRevertCall) Do() (*Page, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages/{pageId}/revert")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"pageId": c.pageId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Page
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Revert a published or scheduled page to draft state.",
// "httpMethod": "POST",
// "id": "blogger.pages.revert",
// "parameterOrder": [
// "blogId",
// "pageId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageId": {
// "description": "The ID of the page.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/pages/{pageId}/revert",
// "response": {
// "$ref": "Page"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.pages.update":
type PagesUpdateCall struct {
s *Service
blogId string
pageId string
page *Page
opt_ map[string]interface{}
}
// Update: Update a page.
func (r *PagesService) Update(blogId string, pageId string, page *Page) *PagesUpdateCall {
c := &PagesUpdateCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.pageId = pageId
c.page = page
return c
}
// Publish sets the optional parameter "publish": Whether a publish
// action should be performed when the page is updated (default: false).
func (c *PagesUpdateCall) Publish(publish bool) *PagesUpdateCall {
c.opt_["publish"] = publish
return c
}
// Revert sets the optional parameter "revert": Whether a revert action
// should be performed when the page is updated (default: false).
func (c *PagesUpdateCall) Revert(revert bool) *PagesUpdateCall {
c.opt_["revert"] = revert
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PagesUpdateCall) Fields(s ...googleapi.Field) *PagesUpdateCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PagesUpdateCall) Do() (*Page, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.page)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["publish"]; ok {
params.Set("publish", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["revert"]; ok {
params.Set("revert", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/pages/{pageId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PUT", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"pageId": c.pageId,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Page
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Update a page.",
// "httpMethod": "PUT",
// "id": "blogger.pages.update",
// "parameterOrder": [
// "blogId",
// "pageId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageId": {
// "description": "The ID of the Page.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "publish": {
// "description": "Whether a publish action should be performed when the page is updated (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "revert": {
// "description": "Whether a revert action should be performed when the page is updated (default: false).",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "blogs/{blogId}/pages/{pageId}",
// "request": {
// "$ref": "Page"
// },
// "response": {
// "$ref": "Page"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.postUserInfos.get":
type PostUserInfosGetCall struct {
s *Service
userId string
blogId string
postId string
opt_ map[string]interface{}
}
// Get: Gets one post and user info pair, by post ID and user ID. The
// post user info contains per-user information about the post, such as
// access rights, specific to the user.
func (r *PostUserInfosService) Get(userId string, blogId string, postId string) *PostUserInfosGetCall {
c := &PostUserInfosGetCall{s: r.s, opt_: make(map[string]interface{})}
c.userId = userId
c.blogId = blogId
c.postId = postId
return c
}
// MaxComments sets the optional parameter "maxComments": Maximum number
// of comments to pull back on a post.
func (c *PostUserInfosGetCall) MaxComments(maxComments int64) *PostUserInfosGetCall {
c.opt_["maxComments"] = maxComments
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostUserInfosGetCall) Fields(s ...googleapi.Field) *PostUserInfosGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostUserInfosGetCall) Do() (*PostUserInfo, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxComments"]; ok {
params.Set("maxComments", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userId}/blogs/{blogId}/posts/{postId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"userId": c.userId,
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *PostUserInfo
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one post and user info pair, by post ID and user ID. The post user info contains per-user information about the post, such as access rights, specific to the user.",
// "httpMethod": "GET",
// "id": "blogger.postUserInfos.get",
// "parameterOrder": [
// "userId",
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "maxComments": {
// "description": "Maximum number of comments to pull back on a post.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "postId": {
// "description": "The ID of the post to get.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "userId": {
// "description": "ID of the user for the per-user information to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "users/{userId}/blogs/{blogId}/posts/{postId}",
// "response": {
// "$ref": "PostUserInfo"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.postUserInfos.list":
type PostUserInfosListCall struct {
s *Service
userId string
blogId string
opt_ map[string]interface{}
}
// List: Retrieves a list of post and post user info pairs, possibly
// filtered. The post user info contains per-user information about the
// post, such as access rights, specific to the user.
func (r *PostUserInfosService) List(userId string, blogId string) *PostUserInfosListCall {
c := &PostUserInfosListCall{s: r.s, opt_: make(map[string]interface{})}
c.userId = userId
c.blogId = blogId
return c
}
// EndDate sets the optional parameter "endDate": Latest post date to
// fetch, a date-time with RFC 3339 formatting.
func (c *PostUserInfosListCall) EndDate(endDate string) *PostUserInfosListCall {
c.opt_["endDate"] = endDate
return c
}
// FetchBodies sets the optional parameter "fetchBodies": Whether the
// body content of posts is included. Default is false.
func (c *PostUserInfosListCall) FetchBodies(fetchBodies bool) *PostUserInfosListCall {
c.opt_["fetchBodies"] = fetchBodies
return c
}
// Labels sets the optional parameter "labels": Comma-separated list of
// labels to search for.
func (c *PostUserInfosListCall) Labels(labels string) *PostUserInfosListCall {
c.opt_["labels"] = labels
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of posts to fetch.
func (c *PostUserInfosListCall) MaxResults(maxResults int64) *PostUserInfosListCall {
c.opt_["maxResults"] = maxResults
return c
}
// OrderBy sets the optional parameter "orderBy": Sort order applied to
// search results. Default is published.
func (c *PostUserInfosListCall) OrderBy(orderBy string) *PostUserInfosListCall {
c.opt_["orderBy"] = orderBy
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// if the request is paged.
func (c *PostUserInfosListCall) PageToken(pageToken string) *PostUserInfosListCall {
c.opt_["pageToken"] = pageToken
return c
}
// StartDate sets the optional parameter "startDate": Earliest post date
// to fetch, a date-time with RFC 3339 formatting.
func (c *PostUserInfosListCall) StartDate(startDate string) *PostUserInfosListCall {
c.opt_["startDate"] = startDate
return c
}
// Status sets the optional parameter "status":
func (c *PostUserInfosListCall) Status(status string) *PostUserInfosListCall {
c.opt_["status"] = status
return c
}
// View sets the optional parameter "view": Access level with which to
// view the returned result. Note that some fields require elevated
// access.
func (c *PostUserInfosListCall) View(view string) *PostUserInfosListCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostUserInfosListCall) Fields(s ...googleapi.Field) *PostUserInfosListCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostUserInfosListCall) Do() (*PostUserInfosList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["endDate"]; ok {
params.Set("endDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchBodies"]; ok {
params.Set("fetchBodies", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["labels"]; ok {
params.Set("labels", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["orderBy"]; ok {
params.Set("orderBy", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["startDate"]; ok {
params.Set("startDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["status"]; ok {
params.Set("status", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userId}/blogs/{blogId}/posts")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"userId": c.userId,
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *PostUserInfosList
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of post and post user info pairs, possibly filtered. The post user info contains per-user information about the post, such as access rights, specific to the user.",
// "httpMethod": "GET",
// "id": "blogger.postUserInfos.list",
// "parameterOrder": [
// "userId",
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch posts from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "endDate": {
// "description": "Latest post date to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "fetchBodies": {
// "default": "false",
// "description": "Whether the body content of posts is included. Default is false.",
// "location": "query",
// "type": "boolean"
// },
// "labels": {
// "description": "Comma-separated list of labels to search for.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "description": "Maximum number of posts to fetch.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "orderBy": {
// "default": "PUBLISHED",
// "description": "Sort order applied to search results. Default is published.",
// "enum": [
// "published",
// "updated"
// ],
// "enumDescriptions": [
// "Order by the date the post was published",
// "Order by the date the post was last updated"
// ],
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "Continuation token if the request is paged.",
// "location": "query",
// "type": "string"
// },
// "startDate": {
// "description": "Earliest post date to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "status": {
// "enum": [
// "draft",
// "live",
// "scheduled"
// ],
// "enumDescriptions": [
// "Draft posts",
// "Published posts",
// "Posts that are scheduled to publish in future."
// ],
// "location": "query",
// "repeated": true,
// "type": "string"
// },
// "userId": {
// "description": "ID of the user for the per-user information to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the returned result. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Reader level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "users/{userId}/blogs/{blogId}/posts",
// "response": {
// "$ref": "PostUserInfosList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.posts.delete":
type PostsDeleteCall struct {
s *Service
blogId string
postId string
opt_ map[string]interface{}
}
// Delete: Delete a post by ID.
func (r *PostsService) Delete(blogId string, postId string) *PostsDeleteCall {
c := &PostsDeleteCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsDeleteCall) Fields(s ...googleapi.Field) *PostsDeleteCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsDeleteCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Delete a post by ID.",
// "httpMethod": "DELETE",
// "id": "blogger.posts.delete",
// "parameterOrder": [
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}",
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.posts.get":
type PostsGetCall struct {
s *Service
blogId string
postId string
opt_ map[string]interface{}
}
// Get: Get a post by ID.
func (r *PostsService) Get(blogId string, postId string) *PostsGetCall {
c := &PostsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
return c
}
// FetchBody sets the optional parameter "fetchBody": Whether the body
// content of the post is included (default: true). This should be set
// to false when the post bodies are not required, to help minimize
// traffic.
func (c *PostsGetCall) FetchBody(fetchBody bool) *PostsGetCall {
c.opt_["fetchBody"] = fetchBody
return c
}
// FetchImages sets the optional parameter "fetchImages": Whether image
// URL metadata for each post is included (default: false).
func (c *PostsGetCall) FetchImages(fetchImages bool) *PostsGetCall {
c.opt_["fetchImages"] = fetchImages
return c
}
// MaxComments sets the optional parameter "maxComments": Maximum number
// of comments to pull back on a post.
func (c *PostsGetCall) MaxComments(maxComments int64) *PostsGetCall {
c.opt_["maxComments"] = maxComments
return c
}
// View sets the optional parameter "view": Access level with which to
// view the returned result. Note that some fields require elevated
// access.
func (c *PostsGetCall) View(view string) *PostsGetCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsGetCall) Fields(s ...googleapi.Field) *PostsGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsGetCall) Do() (*Post, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fetchBody"]; ok {
params.Set("fetchBody", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchImages"]; ok {
params.Set("fetchImages", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxComments"]; ok {
params.Set("maxComments", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Post
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Get a post by ID.",
// "httpMethod": "GET",
// "id": "blogger.posts.get",
// "parameterOrder": [
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch the post from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "fetchBody": {
// "default": "true",
// "description": "Whether the body content of the post is included (default: true). This should be set to false when the post bodies are not required, to help minimize traffic.",
// "location": "query",
// "type": "boolean"
// },
// "fetchImages": {
// "description": "Whether image URL metadata for each post is included (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "maxComments": {
// "description": "Maximum number of comments to pull back on a post.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "postId": {
// "description": "The ID of the post",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the returned result. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Reader level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}",
// "response": {
// "$ref": "Post"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.posts.getByPath":
type PostsGetByPathCall struct {
s *Service
blogId string
path string
opt_ map[string]interface{}
}
// GetByPath: Retrieve a Post by Path.
func (r *PostsService) GetByPath(blogId string, path string) *PostsGetByPathCall {
c := &PostsGetByPathCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.path = path
return c
}
// MaxComments sets the optional parameter "maxComments": Maximum number
// of comments to pull back on a post.
func (c *PostsGetByPathCall) MaxComments(maxComments int64) *PostsGetByPathCall {
c.opt_["maxComments"] = maxComments
return c
}
// View sets the optional parameter "view": Access level with which to
// view the returned result. Note that some fields require elevated
// access.
func (c *PostsGetByPathCall) View(view string) *PostsGetByPathCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsGetByPathCall) Fields(s ...googleapi.Field) *PostsGetByPathCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsGetByPathCall) Do() (*Post, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
params.Set("path", fmt.Sprintf("%v", c.path))
if v, ok := c.opt_["maxComments"]; ok {
params.Set("maxComments", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/bypath")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Post
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieve a Post by Path.",
// "httpMethod": "GET",
// "id": "blogger.posts.getByPath",
// "parameterOrder": [
// "blogId",
// "path"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch the post from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "maxComments": {
// "description": "Maximum number of comments to pull back on a post.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "path": {
// "description": "Path of the Post to retrieve.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the returned result. Note that some fields require elevated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Reader level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/bypath",
// "response": {
// "$ref": "Post"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.posts.insert":
type PostsInsertCall struct {
s *Service
blogId string
post *Post
opt_ map[string]interface{}
}
// Insert: Add a post.
func (r *PostsService) Insert(blogId string, post *Post) *PostsInsertCall {
c := &PostsInsertCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.post = post
return c
}
// FetchBody sets the optional parameter "fetchBody": Whether the body
// content of the post is included with the result (default: true).
func (c *PostsInsertCall) FetchBody(fetchBody bool) *PostsInsertCall {
c.opt_["fetchBody"] = fetchBody
return c
}
// FetchImages sets the optional parameter "fetchImages": Whether image
// URL metadata for each post is included in the returned result
// (default: false).
func (c *PostsInsertCall) FetchImages(fetchImages bool) *PostsInsertCall {
c.opt_["fetchImages"] = fetchImages
return c
}
// IsDraft sets the optional parameter "isDraft": Whether to create the
// post as a draft (default: false).
func (c *PostsInsertCall) IsDraft(isDraft bool) *PostsInsertCall {
c.opt_["isDraft"] = isDraft
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsInsertCall) Fields(s ...googleapi.Field) *PostsInsertCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsInsertCall) Do() (*Post, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.post)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fetchBody"]; ok {
params.Set("fetchBody", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchImages"]; ok {
params.Set("fetchImages", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["isDraft"]; ok {
params.Set("isDraft", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Post
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Add a post.",
// "httpMethod": "POST",
// "id": "blogger.posts.insert",
// "parameterOrder": [
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to add the post to.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "fetchBody": {
// "default": "true",
// "description": "Whether the body content of the post is included with the result (default: true).",
// "location": "query",
// "type": "boolean"
// },
// "fetchImages": {
// "description": "Whether image URL metadata for each post is included in the returned result (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "isDraft": {
// "description": "Whether to create the post as a draft (default: false).",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "blogs/{blogId}/posts",
// "request": {
// "$ref": "Post"
// },
// "response": {
// "$ref": "Post"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.posts.list":
type PostsListCall struct {
s *Service
blogId string
opt_ map[string]interface{}
}
// List: Retrieves a list of posts, possibly filtered.
func (r *PostsService) List(blogId string) *PostsListCall {
c := &PostsListCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
return c
}
// EndDate sets the optional parameter "endDate": Latest post date to
// fetch, a date-time with RFC 3339 formatting.
func (c *PostsListCall) EndDate(endDate string) *PostsListCall {
c.opt_["endDate"] = endDate
return c
}
// FetchBodies sets the optional parameter "fetchBodies": Whether the
// body content of posts is included (default: true). This should be set
// to false when the post bodies are not required, to help minimize
// traffic.
func (c *PostsListCall) FetchBodies(fetchBodies bool) *PostsListCall {
c.opt_["fetchBodies"] = fetchBodies
return c
}
// FetchImages sets the optional parameter "fetchImages": Whether image
// URL metadata for each post is included.
func (c *PostsListCall) FetchImages(fetchImages bool) *PostsListCall {
c.opt_["fetchImages"] = fetchImages
return c
}
// Labels sets the optional parameter "labels": Comma-separated list of
// labels to search for.
func (c *PostsListCall) Labels(labels string) *PostsListCall {
c.opt_["labels"] = labels
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of posts to fetch.
func (c *PostsListCall) MaxResults(maxResults int64) *PostsListCall {
c.opt_["maxResults"] = maxResults
return c
}
// OrderBy sets the optional parameter "orderBy": Sort search results
func (c *PostsListCall) OrderBy(orderBy string) *PostsListCall {
c.opt_["orderBy"] = orderBy
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// if the request is paged.
func (c *PostsListCall) PageToken(pageToken string) *PostsListCall {
c.opt_["pageToken"] = pageToken
return c
}
// StartDate sets the optional parameter "startDate": Earliest post date
// to fetch, a date-time with RFC 3339 formatting.
func (c *PostsListCall) StartDate(startDate string) *PostsListCall {
c.opt_["startDate"] = startDate
return c
}
// Status sets the optional parameter "status": Statuses to include in
// the results.
func (c *PostsListCall) Status(status string) *PostsListCall {
c.opt_["status"] = status
return c
}
// View sets the optional parameter "view": Access level with which to
// view the returned result. Note that some fields require escalated
// access.
func (c *PostsListCall) View(view string) *PostsListCall {
c.opt_["view"] = view
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsListCall) Fields(s ...googleapi.Field) *PostsListCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsListCall) Do() (*PostList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["endDate"]; ok {
params.Set("endDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchBodies"]; ok {
params.Set("fetchBodies", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchImages"]; ok {
params.Set("fetchImages", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["labels"]; ok {
params.Set("labels", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["orderBy"]; ok {
params.Set("orderBy", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["startDate"]; ok {
params.Set("startDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["status"]; ok {
params.Set("status", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["view"]; ok {
params.Set("view", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *PostList
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of posts, possibly filtered.",
// "httpMethod": "GET",
// "id": "blogger.posts.list",
// "parameterOrder": [
// "blogId"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch posts from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "endDate": {
// "description": "Latest post date to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "fetchBodies": {
// "default": "true",
// "description": "Whether the body content of posts is included (default: true). This should be set to false when the post bodies are not required, to help minimize traffic.",
// "location": "query",
// "type": "boolean"
// },
// "fetchImages": {
// "description": "Whether image URL metadata for each post is included.",
// "location": "query",
// "type": "boolean"
// },
// "labels": {
// "description": "Comma-separated list of labels to search for.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "description": "Maximum number of posts to fetch.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "orderBy": {
// "default": "PUBLISHED",
// "description": "Sort search results",
// "enum": [
// "published",
// "updated"
// ],
// "enumDescriptions": [
// "Order by the date the post was published",
// "Order by the date the post was last updated"
// ],
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "Continuation token if the request is paged.",
// "location": "query",
// "type": "string"
// },
// "startDate": {
// "description": "Earliest post date to fetch, a date-time with RFC 3339 formatting.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "status": {
// "description": "Statuses to include in the results.",
// "enum": [
// "draft",
// "live",
// "scheduled"
// ],
// "enumDescriptions": [
// "Draft (non-published) posts.",
// "Published posts",
// "Posts that are scheduled to publish in the future."
// ],
// "location": "query",
// "repeated": true,
// "type": "string"
// },
// "view": {
// "description": "Access level with which to view the returned result. Note that some fields require escalated access.",
// "enum": [
// "ADMIN",
// "AUTHOR",
// "READER"
// ],
// "enumDescriptions": [
// "Admin level detail",
// "Author level detail",
// "Reader level detail"
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts",
// "response": {
// "$ref": "PostList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.posts.patch":
type PostsPatchCall struct {
s *Service
blogId string
postId string
post *Post
opt_ map[string]interface{}
}
// Patch: Update a post. This method supports patch semantics.
func (r *PostsService) Patch(blogId string, postId string, post *Post) *PostsPatchCall {
c := &PostsPatchCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
c.post = post
return c
}
// FetchBody sets the optional parameter "fetchBody": Whether the body
// content of the post is included with the result (default: true).
func (c *PostsPatchCall) FetchBody(fetchBody bool) *PostsPatchCall {
c.opt_["fetchBody"] = fetchBody
return c
}
// FetchImages sets the optional parameter "fetchImages": Whether image
// URL metadata for each post is included in the returned result
// (default: false).
func (c *PostsPatchCall) FetchImages(fetchImages bool) *PostsPatchCall {
c.opt_["fetchImages"] = fetchImages
return c
}
// MaxComments sets the optional parameter "maxComments": Maximum number
// of comments to retrieve with the returned post.
func (c *PostsPatchCall) MaxComments(maxComments int64) *PostsPatchCall {
c.opt_["maxComments"] = maxComments
return c
}
// Publish sets the optional parameter "publish": Whether a publish
// action should be performed when the post is updated (default: false).
func (c *PostsPatchCall) Publish(publish bool) *PostsPatchCall {
c.opt_["publish"] = publish
return c
}
// Revert sets the optional parameter "revert": Whether a revert action
// should be performed when the post is updated (default: false).
func (c *PostsPatchCall) Revert(revert bool) *PostsPatchCall {
c.opt_["revert"] = revert
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsPatchCall) Fields(s ...googleapi.Field) *PostsPatchCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsPatchCall) Do() (*Post, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.post)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fetchBody"]; ok {
params.Set("fetchBody", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchImages"]; ok {
params.Set("fetchImages", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxComments"]; ok {
params.Set("maxComments", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["publish"]; ok {
params.Set("publish", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["revert"]; ok {
params.Set("revert", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Post
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Update a post. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "blogger.posts.patch",
// "parameterOrder": [
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "fetchBody": {
// "default": "true",
// "description": "Whether the body content of the post is included with the result (default: true).",
// "location": "query",
// "type": "boolean"
// },
// "fetchImages": {
// "description": "Whether image URL metadata for each post is included in the returned result (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "maxComments": {
// "description": "Maximum number of comments to retrieve with the returned post.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "publish": {
// "description": "Whether a publish action should be performed when the post is updated (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "revert": {
// "description": "Whether a revert action should be performed when the post is updated (default: false).",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}",
// "request": {
// "$ref": "Post"
// },
// "response": {
// "$ref": "Post"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.posts.publish":
type PostsPublishCall struct {
s *Service
blogId string
postId string
opt_ map[string]interface{}
}
// Publish: Publishes a draft post, optionally at the specific time of
// the given publishDate parameter.
func (r *PostsService) Publish(blogId string, postId string) *PostsPublishCall {
c := &PostsPublishCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
return c
}
// PublishDate sets the optional parameter "publishDate": Optional date
// and time to schedule the publishing of the Blog. If no publishDate
// parameter is given, the post is either published at the a previously
// saved schedule date (if present), or the current time. If a future
// date is given, the post will be scheduled to be published.
func (c *PostsPublishCall) PublishDate(publishDate string) *PostsPublishCall {
c.opt_["publishDate"] = publishDate
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsPublishCall) Fields(s ...googleapi.Field) *PostsPublishCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsPublishCall) Do() (*Post, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["publishDate"]; ok {
params.Set("publishDate", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/publish")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Post
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Publishes a draft post, optionally at the specific time of the given publishDate parameter.",
// "httpMethod": "POST",
// "id": "blogger.posts.publish",
// "parameterOrder": [
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "publishDate": {
// "description": "Optional date and time to schedule the publishing of the Blog. If no publishDate parameter is given, the post is either published at the a previously saved schedule date (if present), or the current time. If a future date is given, the post will be scheduled to be published.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/publish",
// "response": {
// "$ref": "Post"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.posts.revert":
type PostsRevertCall struct {
s *Service
blogId string
postId string
opt_ map[string]interface{}
}
// Revert: Revert a published or scheduled post to draft state.
func (r *PostsService) Revert(blogId string, postId string) *PostsRevertCall {
c := &PostsRevertCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsRevertCall) Fields(s ...googleapi.Field) *PostsRevertCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsRevertCall) Do() (*Post, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}/revert")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Post
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Revert a published or scheduled post to draft state.",
// "httpMethod": "POST",
// "id": "blogger.posts.revert",
// "parameterOrder": [
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}/revert",
// "response": {
// "$ref": "Post"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.posts.search":
type PostsSearchCall struct {
s *Service
blogId string
q string
opt_ map[string]interface{}
}
// Search: Search for a post.
func (r *PostsService) Search(blogId string, q string) *PostsSearchCall {
c := &PostsSearchCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.q = q
return c
}
// FetchBodies sets the optional parameter "fetchBodies": Whether the
// body content of posts is included (default: true). This should be set
// to false when the post bodies are not required, to help minimize
// traffic.
func (c *PostsSearchCall) FetchBodies(fetchBodies bool) *PostsSearchCall {
c.opt_["fetchBodies"] = fetchBodies
return c
}
// OrderBy sets the optional parameter "orderBy": Sort search results
func (c *PostsSearchCall) OrderBy(orderBy string) *PostsSearchCall {
c.opt_["orderBy"] = orderBy
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsSearchCall) Fields(s ...googleapi.Field) *PostsSearchCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsSearchCall) Do() (*PostList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
params.Set("q", fmt.Sprintf("%v", c.q))
if v, ok := c.opt_["fetchBodies"]; ok {
params.Set("fetchBodies", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["orderBy"]; ok {
params.Set("orderBy", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/search")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *PostList
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Search for a post.",
// "httpMethod": "GET",
// "id": "blogger.posts.search",
// "parameterOrder": [
// "blogId",
// "q"
// ],
// "parameters": {
// "blogId": {
// "description": "ID of the blog to fetch the post from.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "fetchBodies": {
// "default": "true",
// "description": "Whether the body content of posts is included (default: true). This should be set to false when the post bodies are not required, to help minimize traffic.",
// "location": "query",
// "type": "boolean"
// },
// "orderBy": {
// "default": "PUBLISHED",
// "description": "Sort search results",
// "enum": [
// "published",
// "updated"
// ],
// "enumDescriptions": [
// "Order by the date the post was published",
// "Order by the date the post was last updated"
// ],
// "location": "query",
// "type": "string"
// },
// "q": {
// "description": "Query terms to search this blog for matching posts.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "blogs/{blogId}/posts/search",
// "response": {
// "$ref": "PostList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}
// method id "blogger.posts.update":
type PostsUpdateCall struct {
s *Service
blogId string
postId string
post *Post
opt_ map[string]interface{}
}
// Update: Update a post.
func (r *PostsService) Update(blogId string, postId string, post *Post) *PostsUpdateCall {
c := &PostsUpdateCall{s: r.s, opt_: make(map[string]interface{})}
c.blogId = blogId
c.postId = postId
c.post = post
return c
}
// FetchBody sets the optional parameter "fetchBody": Whether the body
// content of the post is included with the result (default: true).
func (c *PostsUpdateCall) FetchBody(fetchBody bool) *PostsUpdateCall {
c.opt_["fetchBody"] = fetchBody
return c
}
// FetchImages sets the optional parameter "fetchImages": Whether image
// URL metadata for each post is included in the returned result
// (default: false).
func (c *PostsUpdateCall) FetchImages(fetchImages bool) *PostsUpdateCall {
c.opt_["fetchImages"] = fetchImages
return c
}
// MaxComments sets the optional parameter "maxComments": Maximum number
// of comments to retrieve with the returned post.
func (c *PostsUpdateCall) MaxComments(maxComments int64) *PostsUpdateCall {
c.opt_["maxComments"] = maxComments
return c
}
// Publish sets the optional parameter "publish": Whether a publish
// action should be performed when the post is updated (default: false).
func (c *PostsUpdateCall) Publish(publish bool) *PostsUpdateCall {
c.opt_["publish"] = publish
return c
}
// Revert sets the optional parameter "revert": Whether a revert action
// should be performed when the post is updated (default: false).
func (c *PostsUpdateCall) Revert(revert bool) *PostsUpdateCall {
c.opt_["revert"] = revert
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PostsUpdateCall) Fields(s ...googleapi.Field) *PostsUpdateCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *PostsUpdateCall) Do() (*Post, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.post)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fetchBody"]; ok {
params.Set("fetchBody", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fetchImages"]; ok {
params.Set("fetchImages", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxComments"]; ok {
params.Set("maxComments", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["publish"]; ok {
params.Set("publish", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["revert"]; ok {
params.Set("revert", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "blogs/{blogId}/posts/{postId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PUT", urls, body)
googleapi.Expand(req.URL, map[string]string{
"blogId": c.blogId,
"postId": c.postId,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *Post
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Update a post.",
// "httpMethod": "PUT",
// "id": "blogger.posts.update",
// "parameterOrder": [
// "blogId",
// "postId"
// ],
// "parameters": {
// "blogId": {
// "description": "The ID of the Blog.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "fetchBody": {
// "default": "true",
// "description": "Whether the body content of the post is included with the result (default: true).",
// "location": "query",
// "type": "boolean"
// },
// "fetchImages": {
// "description": "Whether image URL metadata for each post is included in the returned result (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "maxComments": {
// "description": "Maximum number of comments to retrieve with the returned post.",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "postId": {
// "description": "The ID of the Post.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "publish": {
// "description": "Whether a publish action should be performed when the post is updated (default: false).",
// "location": "query",
// "type": "boolean"
// },
// "revert": {
// "description": "Whether a revert action should be performed when the post is updated (default: false).",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "blogs/{blogId}/posts/{postId}",
// "request": {
// "$ref": "Post"
// },
// "response": {
// "$ref": "Post"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger"
// ]
// }
}
// method id "blogger.users.get":
type UsersGetCall struct {
s *Service
userId string
opt_ map[string]interface{}
}
// Get: Gets one user by ID.
func (r *UsersService) Get(userId string) *UsersGetCall {
c := &UsersGetCall{s: r.s, opt_: make(map[string]interface{})}
c.userId = userId
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *UsersGetCall) Fields(s ...googleapi.Field) *UsersGetCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
func (c *UsersGetCall) Do() (*User, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"userId": c.userId,
})
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
var ret *User
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one user by ID.",
// "httpMethod": "GET",
// "id": "blogger.users.get",
// "parameterOrder": [
// "userId"
// ],
// "parameters": {
// "userId": {
// "description": "The ID of the user to get.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "users/{userId}",
// "response": {
// "$ref": "User"
// },
// "scopes": [
// "https://www.googleapis.com/auth/blogger",
// "https://www.googleapis.com/auth/blogger.readonly"
// ]
// }
}<|fim▁end|>
| |
<|file_name|>canonize.js<|end_file_name|><|fim▁begin|>var urls = [
"https://vk.com/igor.suvorov",
"https://twitter.com/suvorovigor",
"https://telegram.me/skillbranch",
"@skillbranch",
"https://vk.com/skillbranch?w=wall-117903599_1076",];
function getName(url) {
const reg = /(@|\/)?[\w\9.]+/ig;
const reg1 = /[\w\9.]+/ig;
const matches = url.match(reg);
console.log(matches);
// return "@"+matches[matches.length-1];
return "@"+matches[matches.length-1].match(reg1);
}
<|fim▁hole|> return getName(url);
}<|fim▁end|>
|
export default function canonize(url) {
|
<|file_name|>launch.js<|end_file_name|><|fim▁begin|>require.config({
baseUrl: 'vendor',
waitSeconds: 10,
paths: {
core: '../core',
lang: '../lang',
root: '..'
},
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'underscore': {
exports: '_'
}
}
});
require(['root/config'],function(Config){
require.config({
paths: {
theme: '../themes/'+ Config.theme
}
});
require(['jquery', 'core/app-utils', 'core/app', 'core/router', 'core/region-manager', 'core/stats', 'core/phonegap-utils'],
function ($, Utils, App, Router, RegionManager, Stats, PhoneGap) {
var launch = function() {
// Initialize application before using it
App.initialize( function() {
RegionManager.buildHead(function(){
RegionManager.buildLayout(function(){
RegionManager.buildHeader(function(){
App.router = new Router();
require(['theme/js/functions'],
function(){
App.sync(
function(){
RegionManager.buildMenu(function(){ //Menu items are loaded by App.sync
Stats.updateVersion();
Stats.incrementCountOpen();
Stats.incrementLastOpenTime();
if( Config.debug_mode == 'on' ){
Utils.log( 'App version : ', Stats.getVersionDiff() );
Utils.log( 'App opening count : ', Stats.getCountOpen() );
Utils.log( 'Last app opening was on ', Stats.getLastOpenDate() );
}
App.launchRouting();
App.sendInfo('app-launched'); //triggers info:app-ready, info:app-first-launch and info:app-version-changed
//Refresh at app launch can be canceled using the 'refresh-at-app-launch' App param,
//this is useful if we set a specific launch page and don't want to be redirected
//after the refresh.
if( App.getParam('refresh-at-app-launch') ){
//Refresh at app launch : as the theme is now loaded, use theme-app :
require(['core/theme-app'],function(ThemeApp){
last_updated = App.options.get( 'last_updated' );
refresh_interval = App.options.get( 'refresh_interval' );
if( undefined === last_updated || undefined === refresh_interval || Date.now() > last_updated.get( 'value' ) + ( refresh_interval.get( 'value' ) * 1000 ) ) {
Utils.log( 'Refresh interval exceeded, refreshing', { last_updated: last_updated, refresh_interval: refresh_interval } );
ThemeApp.refresh();
}
});
}
PhoneGap.hideSplashScreen();
});
},
function(){
Backbone.history.start();
Utils.log("launch.js error : App could not synchronize with website.");
PhoneGap.hideSplashScreen();
App.sendInfo('no-content');
},
false //true to force refresh local storage at each app launch.
);
},
function(error){
Utils.log('Error : theme/js/functions.js not found', error);
}
);
});
});
});
});
};
if( PhoneGap.isLoaded() ){
PhoneGap.setNetworkEvents(App.onOnline,App.onOffline);
document.addEventListener('deviceready', launch, false);
}else{
window.ononline = App.onOnline;
window.onoffline = App.onOffline;
$(document).ready(launch);
}
});
},function(){ //Config.js not found<|fim▁hole|> var message = 'WP AppKit error : config.js not found.';
console && console.log(message);
document.write(message);
//Check if we are simulating in browser :
var query = window.location.search.substring(1);
if( query.length && query.indexOf('wpak_app_id') != -1 ){
message = 'Please check that you are connected to your WordPress back office.';
console && console.log(message);
document.write('<br>'+ message);
}
});<|fim▁end|>
|
//Can't use Utils.log here : log messages by hand :
|
<|file_name|>basic_types.hpp<|end_file_name|><|fim▁begin|>// basic_types.hpp --------------------------------------------------------------//
// Copyright 2010 Vicente J. Botet Escriba
// Copyright 2015 Andrey Semashev
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#ifndef BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP
#define BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP
#include <cstdarg>
#include <boost/cstdint.hpp>
#include <boost/detail/winapi/config.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined( BOOST_USE_WINDOWS_H )
# include <windows.h>
#elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined(__CYGWIN__)
# include <winerror.h>
# ifdef UNDER_CE
# ifndef WINAPI
# ifndef _WIN32_WCE_EMULATION
# define WINAPI __cdecl // Note this doesn't match the desktop definition
# else
# define WINAPI __stdcall
# endif
# endif
// Windows CE defines a few functions as inline functions in kfuncs.h
typedef int BOOL;
typedef unsigned long DWORD;
typedef void* HANDLE;
# include <kfuncs.h>
# else
# ifndef WINAPI
# define WINAPI __stdcall
# endif
# endif
# ifndef NTAPI
# define NTAPI __stdcall
# endif
#else
# error "Win32 functions not available"
#endif
#ifndef NO_STRICT
#ifndef STRICT
#define STRICT 1
#endif
#endif
#if defined(STRICT)
#define BOOST_DETAIL_WINAPI_DECLARE_HANDLE(x) struct x##__; typedef struct x##__ *x
#else
#define BOOST_DETAIL_WINAPI_DECLARE_HANDLE(x) typedef void* x
#endif
#if !defined( BOOST_USE_WINDOWS_H )
extern "C" {
union _LARGE_INTEGER;
struct _SECURITY_ATTRIBUTES;
BOOST_DETAIL_WINAPI_DECLARE_HANDLE(HINSTANCE);
typedef HINSTANCE HMODULE;
}
#endif
#if defined(__GNUC__)
#define BOOST_DETAIL_WINAPI_MAY_ALIAS __attribute__ ((__may_alias__))
#else
#define BOOST_DETAIL_WINAPI_MAY_ALIAS
#endif
// MinGW64 gcc 4.8.2 fails to compile function declarations with boost::detail::winapi::VOID_ arguments even though
// the typedef expands to void. In Windows SDK, VOID is a macro which unfolds to void. We use our own macro in such cases.
#define BOOST_DETAIL_WINAPI_VOID void
namespace boost {
namespace detail {
namespace winapi {
#if defined( BOOST_USE_WINDOWS_H )
typedef ::BOOL BOOL_;
typedef ::PBOOL PBOOL_;
typedef ::LPBOOL LPBOOL_;
typedef ::BOOLEAN BOOLEAN_;
typedef ::PBOOLEAN PBOOLEAN_;
typedef ::BYTE BYTE_;
typedef ::PBYTE PBYTE_;
typedef ::LPBYTE LPBYTE_;
typedef ::WORD WORD_;
typedef ::PWORD PWORD_;
typedef ::LPWORD LPWORD_;
typedef ::DWORD DWORD_;
typedef ::PDWORD PDWORD_;
typedef ::LPDWORD LPDWORD_;
typedef ::HANDLE HANDLE_;
typedef ::PHANDLE PHANDLE_;
typedef ::SHORT SHORT_;
typedef ::PSHORT PSHORT_;
typedef ::USHORT USHORT_;
typedef ::PUSHORT PUSHORT_;
typedef ::INT INT_;
typedef ::PINT PINT_;
typedef ::LPINT LPINT_;
typedef ::UINT UINT_;
typedef ::PUINT PUINT_;
typedef ::LONG LONG_;
typedef ::PLONG PLONG_;
typedef ::LPLONG LPLONG_;
typedef ::ULONG ULONG_;
typedef ::PULONG PULONG_;
typedef ::LONGLONG LONGLONG_;
typedef ::ULONGLONG ULONGLONG_;
typedef ::INT_PTR INT_PTR_;
typedef ::UINT_PTR UINT_PTR_;
typedef ::LONG_PTR LONG_PTR_;
typedef ::ULONG_PTR ULONG_PTR_;
typedef ::DWORD_PTR DWORD_PTR_;
typedef ::PDWORD_PTR PDWORD_PTR_;
typedef ::SIZE_T SIZE_T_;
typedef ::PSIZE_T PSIZE_T_;
typedef ::SSIZE_T SSIZE_T_;
typedef ::PSSIZE_T PSSIZE_T_;
typedef VOID VOID_; // VOID is a macro
typedef ::PVOID PVOID_;
typedef ::LPVOID LPVOID_;
typedef ::LPCVOID LPCVOID_;
typedef ::CHAR CHAR_;
typedef ::LPSTR LPSTR_;
typedef ::LPCSTR LPCSTR_;
typedef ::WCHAR WCHAR_;
typedef ::LPWSTR LPWSTR_;
typedef ::LPCWSTR LPCWSTR_;<|fim▁hole|>typedef int BOOL_;
typedef BOOL_* PBOOL_;
typedef BOOL_* LPBOOL_;
typedef unsigned char BYTE_;
typedef BYTE_* PBYTE_;
typedef BYTE_* LPBYTE_;
typedef BYTE_ BOOLEAN_;
typedef BOOLEAN_* PBOOLEAN_;
typedef unsigned short WORD_;
typedef WORD_* PWORD_;
typedef WORD_* LPWORD_;
typedef unsigned long DWORD_;
typedef DWORD_* PDWORD_;
typedef DWORD_* LPDWORD_;
typedef void* HANDLE_;
typedef void** PHANDLE_;
typedef short SHORT_;
typedef SHORT_* PSHORT_;
typedef unsigned short USHORT_;
typedef USHORT_* PUSHORT_;
typedef int INT_;
typedef INT_* PINT_;
typedef INT_* LPINT_;
typedef unsigned int UINT_;
typedef UINT_* PUINT_;
typedef long LONG_;
typedef LONG_* PLONG_;
typedef LONG_* LPLONG_;
typedef unsigned long ULONG_;
typedef ULONG_* PULONG_;
typedef boost::int64_t LONGLONG_;
typedef boost::uint64_t ULONGLONG_;
# ifdef _WIN64
# if defined(__CYGWIN__)
typedef long INT_PTR_;
typedef unsigned long UINT_PTR_;
typedef long LONG_PTR_;
typedef unsigned long ULONG_PTR_;
# else
typedef __int64 INT_PTR_;
typedef unsigned __int64 UINT_PTR_;
typedef __int64 LONG_PTR_;
typedef unsigned __int64 ULONG_PTR_;
# endif
# else
typedef int INT_PTR_;
typedef unsigned int UINT_PTR_;
typedef long LONG_PTR_;
typedef unsigned long ULONG_PTR_;
# endif
typedef ULONG_PTR_ DWORD_PTR_, *PDWORD_PTR_;
typedef ULONG_PTR_ SIZE_T_, *PSIZE_T_;
typedef LONG_PTR_ SSIZE_T_, *PSSIZE_T_;
typedef void VOID_;
typedef void *PVOID_;
typedef void *LPVOID_;
typedef const void *LPCVOID_;
typedef char CHAR_;
typedef CHAR_ *LPSTR_;
typedef const CHAR_ *LPCSTR_;
typedef wchar_t WCHAR_;
typedef WCHAR_ *LPWSTR_;
typedef const WCHAR_ *LPCWSTR_;
#endif // defined( BOOST_USE_WINDOWS_H )
typedef ::HMODULE HMODULE_;
typedef union BOOST_DETAIL_WINAPI_MAY_ALIAS _LARGE_INTEGER {
struct {
DWORD_ LowPart;
LONG_ HighPart;
} u;
LONGLONG_ QuadPart;
} LARGE_INTEGER_, *PLARGE_INTEGER_;
typedef struct BOOST_DETAIL_WINAPI_MAY_ALIAS _SECURITY_ATTRIBUTES {
DWORD_ nLength;
LPVOID_ lpSecurityDescriptor;
BOOL_ bInheritHandle;
} SECURITY_ATTRIBUTES_, *PSECURITY_ATTRIBUTES_, *LPSECURITY_ATTRIBUTES_;
}
}
}
#endif // BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP<|fim▁end|>
|
#else // defined( BOOST_USE_WINDOWS_H )
|
<|file_name|>SolverResult.hpp<|end_file_name|><|fim▁begin|>/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2021 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#ifndef XCSOAR_SOLVER_RESULT_HPP
#define XCSOAR_SOLVER_RESULT_HPP
/**
* Return type for path solver methods.
*/
enum class SolverResult {
/**
* Still looking for a solution.
*/
INCOMPLETE,
/**
* A valid solution was found.
*/
VALID,
/**
* The solver has completed, but failed to find a valid solution,<|fim▁hole|> * or the solution was not better than the previous one. More
* data may be required.
*/
FAILED,
};
#endif<|fim▁end|>
| |
<|file_name|>nginx.go<|end_file_name|><|fim▁begin|>package mpnginx
import (
"bufio"
"flag"
"fmt"
"io"
"errors"
"net/http"
"regexp"
"strconv"
"strings"
mp "github.com/mackerelio/go-mackerel-plugin-helper"
)
var graphdef = map[string]mp.Graphs{
"nginx.connections": {
Label: "Nginx Connections",
Unit: "integer",
Metrics: []mp.Metrics{
{Name: "connections", Label: "Active connections", Diff: false},
},
},
"nginx.requests": {
Label: "Nginx requests",
Unit: "float",
Metrics: []mp.Metrics{
{Name: "accepts", Label: "Accepted connections", Diff: true, Type: "uint64"},
{Name: "handled", Label: "Handled connections", Diff: true, Type: "uint64"},
{Name: "requests", Label: "Handled requests", Diff: true, Type: "uint64"},
},
},
"nginx.queue": {
Label: "Nginx connection status",
Unit: "integer",
Metrics: []mp.Metrics{
{Name: "reading", Label: "Reading", Diff: false},
{Name: "writing", Label: "Writing", Diff: false},
{Name: "waiting", Label: "Waiting", Diff: false},
},
},
}
type stringSlice []string
<|fim▁hole|>func (s *stringSlice) Set(v string) error {
*s = append(*s, v)
return nil
}
func (s *stringSlice) String() string {
return fmt.Sprintf("%v", *s)
}
// NginxPlugin mackerel plugin for Nginx
type NginxPlugin struct {
URI string
Header stringSlice
}
// % wget -qO- http://localhost:8080/nginx_status
// Active connections: 123
// server accepts handled requests
// 1693613501 1693613501 7996986318
// Reading: 66 Writing: 16 Waiting: 41
// FetchMetrics interface for mackerelplugin
func (n NginxPlugin) FetchMetrics() (map[string]interface{}, error) {
req, err := http.NewRequest("GET", n.URI, nil)
if err != nil {
return nil, err
}
for _, h := range n.Header {
kv := strings.SplitN(h, ":", 2)
var k, v string
k = strings.TrimSpace(kv[0])
if len(kv) == 2 {
v = strings.TrimSpace(kv[1])
}
if http.CanonicalHeaderKey(k) == "Host" {
req.Host = v
} else {
req.Header.Set(k, v)
}
}
// set default User-Agent unless specified by n.Header
if _, ok := req.Header["User-Agent"]; !ok {
req.Header.Set("User-Agent", "mackerel-plugin-nginx")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return n.parseStats(resp.Body)
}
func (n NginxPlugin) parseStats(body io.Reader) (map[string]interface{}, error) {
stat := make(map[string]interface{})
r := bufio.NewReader(body)
line, _, err := r.ReadLine()
if err != nil {
return nil, errors.New("cannot get values")
}
re := regexp.MustCompile("Active connections: ([0-9]+)")
res := re.FindStringSubmatch(string(line))
if res == nil || len(res) != 2 {
return nil, errors.New("cannot get values")
}
stat["connections"], err = strconv.ParseFloat(res[1], 64)
if err != nil {
return nil, errors.New("cannot get values")
}
line, _, err = r.ReadLine()
if err != nil {
return nil, errors.New("cannot get values")
}
line, _, err = r.ReadLine()
if err != nil {
return nil, errors.New("cannot get values")
}
re = regexp.MustCompile("([0-9]+) ([0-9]+) ([0-9]+)")
res = re.FindStringSubmatch(string(line))
if res == nil || len(res) != 4 {
return nil, errors.New("cannot get values")
}
stat["accepts"], err = strconv.ParseFloat(res[1], 64)
if err != nil {
return nil, errors.New("cannot get values")
}
stat["handled"], err = strconv.ParseFloat(res[2], 64)
if err != nil {
return nil, errors.New("cannot get values")
}
stat["requests"], err = strconv.ParseFloat(res[3], 64)
if err != nil {
return nil, errors.New("cannot get values")
}
line, _, err = r.ReadLine()
if err != nil {
return nil, errors.New("cannot get values")
}
re = regexp.MustCompile("Reading: ([0-9]+) Writing: ([0-9]+) Waiting: ([0-9]+)")
res = re.FindStringSubmatch(string(line))
if res == nil || len(res) != 4 {
return nil, errors.New("cannot get values")
}
stat["reading"], err = strconv.ParseFloat(res[1], 64)
if err != nil {
return nil, errors.New("cannot get values")
}
stat["writing"], err = strconv.ParseFloat(res[2], 64)
if err != nil {
return nil, errors.New("cannot get values")
}
stat["waiting"], err = strconv.ParseFloat(res[3], 64)
if err != nil {
return nil, errors.New("cannot get values")
}
return stat, nil
}
// GraphDefinition interface for mackerelplugin
func (n NginxPlugin) GraphDefinition() map[string]mp.Graphs {
return graphdef
}
// Do the plugin
func Do() {
optURI := flag.String("uri", "", "URI")
optScheme := flag.String("scheme", "http", "Scheme")
optHost := flag.String("host", "localhost", "Hostname")
optPort := flag.String("port", "8080", "Port")
optPath := flag.String("path", "/nginx_status", "Path")
optTempfile := flag.String("tempfile", "", "Temp file name")
optHeader := &stringSlice{}
flag.Var(optHeader, "header", "Set http header (e.g. \"Host: servername\")")
flag.Parse()
var nginx NginxPlugin
if *optURI != "" {
nginx.URI = *optURI
} else {
nginx.URI = fmt.Sprintf("%s://%s:%s%s", *optScheme, *optHost, *optPort, *optPath)
}
nginx.Header = *optHeader
helper := mp.NewMackerelPlugin(nginx)
helper.Tempfile = *optTempfile
helper.Run()
}<|fim▁end|>
| |
<|file_name|>caching.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
from fam.buffer import buffered_db
cache = buffered_db
|
<|file_name|>counters.mako.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Counters", inherited=False, gecko_name="Content") %>
<%helpers:longhand name="content" boxed="True" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-content/#propdef-content">
#[cfg(feature = "gecko")]
use values::generics::CounterStyleOrNone;
#[cfg(feature = "gecko")]
use values::specified::url::SpecifiedUrl;
#[cfg(feature = "gecko")]
use values::specified::Attr;
#[cfg(feature = "servo")]
use super::list_style_type;
pub use self::computed_value::T as SpecifiedValue;
pub use self::computed_value::ContentItem;
pub mod computed_value {
use cssparser;
use std::fmt;
use style_traits::ToCss;
#[cfg(feature = "gecko")]
use values::specified::url::SpecifiedUrl;
#[cfg(feature = "servo")]
type CounterStyleType = super::super::list_style_type::computed_value::T;
#[cfg(feature = "gecko")]
type CounterStyleType = ::values::generics::CounterStyleOrNone;
#[cfg(feature = "gecko")]
use values::specified::Attr;
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum ContentItem {
/// Literal string content.
String(String),
/// `counter(name, style)`.
Counter(String, CounterStyleType),
/// `counters(name, separator, style)`.
Counters(String, String, CounterStyleType),
/// `open-quote`.
OpenQuote,
/// `close-quote`.
CloseQuote,
/// `no-open-quote`.
NoOpenQuote,
/// `no-close-quote`.
NoCloseQuote,
% if product == "gecko":
/// `attr([namespace? `|`]? ident)`
Attr(Attr),
/// `url(url)`
Url(SpecifiedUrl),
% endif
}
impl ToCss for ContentItem {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
ContentItem::String(ref s) => s.to_css(dest),
ContentItem::Counter(ref s, ref counter_style) => {
dest.write_str("counter(")?;
cssparser::serialize_identifier(&**s, dest)?;
dest.write_str(", ")?;
counter_style.to_css(dest)?;
dest.write_str(")")
}
ContentItem::Counters(ref s, ref separator, ref counter_style) => {
dest.write_str("counters(")?;
cssparser::serialize_identifier(&**s, dest)?;
dest.write_str(", ")?;
separator.to_css(dest)?;
dest.write_str(", ")?;
counter_style.to_css(dest)?;
dest.write_str(")")
}
ContentItem::OpenQuote => dest.write_str("open-quote"),
ContentItem::CloseQuote => dest.write_str("close-quote"),
ContentItem::NoOpenQuote => dest.write_str("no-open-quote"),
ContentItem::NoCloseQuote => dest.write_str("no-close-quote"),
% if product == "gecko":
ContentItem::Attr(ref attr) => {
attr.to_css(dest)
}
ContentItem::Url(ref url) => url.to_css(dest),
% endif
}
}
}
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum T {
Normal,
None,
#[cfg(feature = "gecko")]
MozAltContent,
Items(Vec<ContentItem>),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::Normal => dest.write_str("normal"),
T::None => dest.write_str("none"),
% if product == "gecko":
T::MozAltContent => dest.write_str("-moz-alt-content"),
% endif
T::Items(ref content) => {
let mut iter = content.iter();
iter.next().unwrap().to_css(dest)?;
for c in iter {
dest.write_str(" ")?;
c.to_css(dest)?;
}
Ok(())
}
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::Normal
}
#[cfg(feature = "servo")]
fn parse_counter_style(context: &ParserContext, input: &mut Parser) -> list_style_type::computed_value::T {
input.try(|input| {
input.expect_comma()?;
list_style_type::parse(context, input)
}).unwrap_or(list_style_type::computed_value::T::Decimal)
}
#[cfg(feature = "gecko")]
fn parse_counter_style(context: &ParserContext, input: &mut Parser) -> CounterStyleOrNone {
input.try(|input| {
input.expect_comma()?;
CounterStyleOrNone::parse(context, input)
}).unwrap_or(CounterStyleOrNone::decimal())
}
// normal | none | [ <string> | <counter> | open-quote | close-quote | no-open-quote |
// no-close-quote ]+
// TODO: <uri>, attr(<identifier>)
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
return Ok(SpecifiedValue::Normal)
}
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue::None)
}
% if product == "gecko":
if input.try(|input| input.expect_ident_matching("-moz-alt-content")).is_ok() {
return Ok(SpecifiedValue::MozAltContent)
}
% endif
let mut content = vec![];
loop {
% if product == "gecko":
if let Ok(mut url) = input.try(|i| SpecifiedUrl::parse(context, i)) {
url.build_image_value();
content.push(ContentItem::Url(url));
continue;
}
% endif
// FIXME: remove clone() when lifetimes are non-lexical
match input.next().map(|t| t.clone()) {
Ok(Token::QuotedString(ref value)) => {<|fim▁hole|> "counter" => Some(input.parse_nested_block(|input| {
let name = input.expect_ident()?.as_ref().to_owned();
let style = parse_counter_style(context, input);
Ok(ContentItem::Counter(name, style))
})),
"counters" => Some(input.parse_nested_block(|input| {
let name = input.expect_ident()?.as_ref().to_owned();
input.expect_comma()?;
let separator = input.expect_string()?.as_ref().to_owned();
let style = parse_counter_style(context, input);
Ok(ContentItem::Counters(name, separator, style))
})),
% if product == "gecko":
"attr" => Some(input.parse_nested_block(|input| {
Ok(ContentItem::Attr(Attr::parse_function(context, input)?))
})),
% endif
_ => None
};
match result {
Some(result) => content.push(result?),
None => return Err(input.new_custom_error(
StyleParseErrorKind::UnexpectedFunction(name.clone())
))
}
}
Ok(Token::Ident(ref ident)) => {
let valid = match_ignore_ascii_case! { &ident,
"open-quote" => { content.push(ContentItem::OpenQuote); true },
"close-quote" => { content.push(ContentItem::CloseQuote); true },
"no-open-quote" => { content.push(ContentItem::NoOpenQuote); true },
"no-close-quote" => { content.push(ContentItem::NoCloseQuote); true },
_ => false,
};
if !valid {
return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone())))
}
}
Err(_) => break,
Ok(t) => return Err(input.new_unexpected_token_error(t))
}
}
if content.is_empty() {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(SpecifiedValue::Items(content))
}
</%helpers:longhand>
<%helpers:longhand name="counter-increment" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-lists/#propdef-counter-increment">
use std::fmt;
use style_traits::ToCss;
use values::CustomIdent;
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Debug, PartialEq)]
pub struct SpecifiedValue(pub Vec<(CustomIdent, specified::Integer)>);
pub mod computed_value {
use std::fmt;
use style_traits::ToCss;
use values::CustomIdent;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct T(pub Vec<(CustomIdent, i32)>);
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
if self.0.is_empty() {
return dest.write_str("none")
}
let mut first = true;
for &(ref name, value) in &self.0 {
if !first {
dest.write_str(" ")?;
}
first = false;
name.to_css(dest)?;
dest.write_str(" ")?;
value.to_css(dest)?;
}
Ok(())
}
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
computed_value::T(self.0.iter().map(|&(ref name, ref value)| {
(name.clone(), value.to_computed_value(context))
}).collect::<Vec<_>>())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
SpecifiedValue(computed.0.iter().map(|&(ref name, ref value)| {
(name.clone(), specified::Integer::from_computed_value(&value))
}).collect::<Vec<_>>())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(Vec::new())
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
if self.0.is_empty() {
return dest.write_str("none");
}
let mut first = true;
for &(ref name, ref value) in &self.0 {
if !first {
dest.write_str(" ")?;
}
first = false;
name.to_css(dest)?;
dest.write_str(" ")?;
value.to_css(dest)?;
}
Ok(())
}
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
parse_common(context, 1, input)
}
pub fn parse_common<'i, 't>(context: &ParserContext, default_value: i32, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut counters = Vec::new();
loop {
let location = input.current_source_location();
let counter_name = match input.next() {
Ok(&Token::Ident(ref ident)) => CustomIdent::from_ident(location, ident, &["none"])?,
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(_) => break,
};
let counter_delta = input.try(|input| specified::Integer::parse(context, input))
.unwrap_or(specified::Integer::new(default_value));
counters.push((counter_name, counter_delta))
}
if !counters.is_empty() {
Ok(SpecifiedValue(counters))
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
</%helpers:longhand>
<%helpers:longhand name="counter-reset" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-lists-3/#propdef-counter-reset">
pub use super::counter_increment::{SpecifiedValue, computed_value, get_initial_value};
use super::counter_increment::parse_common;
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue,ParseError<'i>> {
parse_common(context, 0, input)
}
</%helpers:longhand><|fim▁end|>
|
content.push(ContentItem::String(value.as_ref().to_owned()))
}
Ok(Token::Function(ref name)) => {
let result = match_ignore_ascii_case! { &name,
|
<|file_name|>uses_inline_crate.rs<|end_file_name|><|fim▁begin|>#![allow(unused_assignments, unused_variables)]
// compile-flags: -C opt-level=3 # validates coverage now works with optimizations
extern crate used_inline_crate;
fn main() {
used_inline_crate::used_function();
used_inline_crate::used_inline_function();
let some_vec = vec![1, 2, 3, 4];
used_inline_crate::used_only_from_bin_crate_generic_function(&some_vec);
used_inline_crate::used_only_from_bin_crate_generic_function("used from bin uses_crate.rs");
used_inline_crate::used_from_bin_crate_and_lib_crate_generic_function(some_vec);
used_inline_crate::used_with_same_type_from_bin_crate_and_lib_crate_generic_function(
"interesting?",
);<|fim▁hole|><|fim▁end|>
|
}
|
<|file_name|>client_test.go<|end_file_name|><|fim▁begin|>package nats
import (
"nats/test"
"net"
"sync"
"testing"
)
type testClient struct {
*testing.T
// Test client
c *Client
// Channel to receive the return value of cl()
ec chan error
// Channel to pass client side of the connection to Dialer
ncc chan net.Conn
// Test server
s *test.TestServer
// WaitGroup to join goroutines after every test
sync.WaitGroup
}
func (tc *testClient) Setup(t *testing.T) {
tc.T = t
tc.c = NewClient()
tc.ec = make(chan error, 1)
tc.ncc = make(chan net.Conn)
tc.Add(1)
go func() {
tc.ec <- tc.c.Run(DumbChannelDialer{tc.ncc}, EmptyHandshake)
tc.Done()
}()
tc.ResetConnection()
}
func (tc *testClient) ResetConnection() {
// Close current test server, if any
if tc.s != nil {
tc.s.Close()
}
nc, ns := net.Pipe()
// Pass new client side of the connection to Dialer
tc.ncc <- nc
// New server
tc.s = test.NewTestServer(tc.T, ns)
}
func (tc *testClient) Teardown() {
tc.c.Stop()
tc.Wait()
}
func TestClientCloseInboxOnStop(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
sub := tc.c.NewSubscription("subject")
sub.Subscribe()
_, ok := <-sub.Inbox
if ok {
t.Errorf("Expected not OK")
}
tc.Done()
}()
tc.s.AssertRead("SUB subject 1\r\n")
tc.Teardown()
}
func TestClientSubscriptionReceivesMessage(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
sub := tc.c.NewSubscription("subject")
sub.Subscribe()
m := <-sub.Inbox
expected := "payload"
actual := string(m.Payload)
if actual != expected {
t.Errorf("Expected: %#v, got: %#v", expected, actual)
}
tc.Done()
}()
tc.s.AssertRead("SUB subject 1\r\n")
tc.s.AssertWrite("MSG subject 1 7\r\npayload\r\n")
tc.Teardown()
}
func TestClientSubscriptionUnsubscribe(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
sub := tc.c.NewSubscription("subject")
sub.Subscribe()
sub.Unsubscribe()
_, ok := <-sub.Inbox
if ok {
t.Errorf("Expected not OK")
}
tc.Done()
}()
tc.s.AssertRead("SUB subject 1\r\n")
tc.s.AssertRead("UNSUB 1\r\n")
tc.Teardown()
}
func TestClientSubscriptionWithQueue(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
sub := tc.c.NewSubscription("subject")
sub.SetQueue("queue")
sub.Subscribe()
tc.Done()
}()
tc.s.AssertRead("SUB subject queue 1\r\n")
tc.Teardown()
}
func TestClientSubscriptionWithMaximum(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
sub := tc.c.NewSubscription("subject")
sub.SetMaximum(1)
sub.Subscribe()
var n = 0
for _ = range sub.Inbox {
n += 1
}
if n != 1 {
t.Errorf("Expected to receive 1 message")
}
tc.Done()
}()
tc.s.AssertRead("SUB subject 1\r\n")
tc.s.AssertRead("UNSUB 1 1\r\n")
tc.s.AssertWrite("MSG subject 1 2\r\nhi\r\n")
tc.s.AssertWrite("MSG subject 1 2\r\nhi\r\n")
tc.s.AssertRead("UNSUB 1\r\n")
tc.Teardown()
}
func TestClientSubscriptionReceivesMessageAfterReconnect(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
sub := tc.c.NewSubscription("subject")
sub.Subscribe()
m := <-sub.Inbox
expected := "payload"
actual := string(m.Payload)
if actual != expected {
t.Errorf("Expected: %#v, got: %#v", expected, actual)
}
tc.Done()
}()
tc.s.AssertRead("SUB subject 1\r\n")
tc.ResetConnection()
tc.s.AssertRead("SUB subject 1\r\n")
tc.s.AssertWrite("MSG subject 1 7\r\npayload\r\n")
tc.Teardown()
}
func TestClientSubscriptionAdjustsMaximumAfterReconnect(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
sub := tc.c.NewSubscription("subject")
sub.SetMaximum(2)
sub.Subscribe()
var n = 0
for _ = range sub.Inbox {
n += 1
}
if n != 2 {
t.Errorf("Expected to receive 2 message")
}
tc.Done()
}()
tc.s.AssertRead("SUB subject 1\r\n")
tc.s.AssertRead("UNSUB 1 2\r\n")
tc.s.AssertWrite("MSG subject 1 2\r\nhi\r\n")
tc.ResetConnection()
tc.s.AssertRead("SUB subject 1\r\n")
tc.s.AssertRead("UNSUB 1 1\r\n")
tc.s.AssertWrite("MSG subject 1 2\r\nhi\r\n")
tc.s.AssertRead("UNSUB 1\r\n")
tc.Teardown()
}
func TestClientPublish(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
ok := tc.c.Publish("subject", []byte("message"))
if !ok {
t.Error("Expected success")
}
tc.Done()
}()
tc.s.AssertRead("PUB subject 7\r\nmessage\r\n")
tc.Teardown()
}
func TestClientRequest(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
ok := tc.c.Request("subject", []byte("message"), func(sub *Subscription) {
for _ = range sub.Inbox {
break
}
})
if !ok {
t.Error("Expected success")
}
tc.Done()
}()
tc.s.AssertMatch("SUB _INBOX\\.[0-9a-f]{26} 1\r\n")
tc.s.AssertMatch("PUB subject _INBOX\\.[0-9a-f]{26} 7\r\nmessage\r\n")
tc.Teardown()
}
func TestClientPublishAndConfirmSucceeds(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
ok := tc.c.PublishAndConfirm("subject", []byte("message"))
if !ok {
t.Error("Expected success")
}
tc.Done()
}()
tc.s.AssertRead("PUB subject 7\r\nmessage\r\n")
tc.s.AssertRead("PING\r\n")
tc.s.AssertWrite("PONG\r\n")
tc.Teardown()
}
func TestClientPublishAndConfirmFails(t *testing.T) {
var tc testClient
tc.Setup(t)
tc.Add(1)
go func() {
ok := tc.c.PublishAndConfirm("subject", []byte("message"))<|fim▁hole|>
tc.Done()
}()
tc.s.AssertRead("PUB subject 7\r\nmessage\r\n")
tc.s.AssertRead("PING\r\n")
tc.Teardown()
}<|fim▁end|>
|
if ok {
t.Error("Expected failure")
}
|
<|file_name|>sysw32fs.cpp<|end_file_name|><|fim▁begin|>/* Copyright (C) 2003-2013 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "w32prefix.h"
#include "globdefs.h"
#include "filedefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "mcio.h"
//#include "execpt.h"
bool MCFileSystemPathToNative(const char *p_path, void*& r_native_path)
{
unichar_t *t_w_path;
t_w_path = nil;
if (!MCCStringToUnicode(p_path, t_w_path))
return false;
for(uint32_t i = 0; t_w_path[i] != 0; i++)
if (t_w_path[i] == '/')
t_w_path[i] = '\\';
r_native_path = t_w_path;
return true;
}
bool MCFileSystemPathFromNative(const void *p_native_path, char*& r_path)
{
char *t_path;
t_path = nil;
if (!MCCStringFromUnicode((const unichar_t *)p_native_path, t_path))
return false;
for(uint32_t i = 0; t_path[i] != 0; i++)
if (t_path[i] == '\\')
t_path[i] = '/';
r_path = t_path;
return true;
}
bool MCFileSystemListEntries(const char *p_folder, uint32_t p_options, MCFileSystemListCallback p_callback, void *p_context)
{
bool t_success;
t_success = true;
char *t_pattern;
t_pattern = nil;
if (t_success)
t_success = MCCStringFormat(t_pattern, "%s%s", p_folder, MCCStringEndsWith(p_folder, "/") ? "*" : "/*");
void *t_native_pattern;
t_native_pattern = nil;
if (t_success)
t_success = MCFileSystemPathToNative(t_pattern, t_native_pattern);
HANDLE t_find_handle;
WIN32_FIND_DATAW t_find_data;
t_find_handle = INVALID_HANDLE_VALUE;
if (t_success)
{
t_find_handle = FindFirstFileW((LPCWSTR)t_native_pattern, &t_find_data);
if (t_find_handle == INVALID_HANDLE_VALUE)
t_success = false;
}
while(t_success)
{
char *t_entry_filename;
if (t_success)
t_success = MCFileSystemPathFromNative(t_find_data . cFileName, t_entry_filename);
MCFileSystemEntry t_entry;
if (t_success)
{
t_entry . type = (t_find_data . dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ? kMCFileSystemEntryFolder : kMCFileSystemEntryFile;
MCStringCreateWithCString(t_entry_filename, t_entry.filename);
//t_entry . filename = t_entry_filename;
t_success = p_callback(p_context, t_entry);
}
MCCStringFree(t_entry_filename);
////
if (!FindNextFileW(t_find_handle, &t_find_data))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
break;
t_success = false;
}
}
if (t_find_handle != INVALID_HANDLE_VALUE)
FindClose(t_find_handle);
MCMemoryDeallocate(t_native_pattern);
MCCStringFree(t_pattern);
return t_success;
}
bool MCFileSystemPathResolve(const char *p_path, char*& r_resolved_path)
{
return MCCStringClone(p_path, r_resolved_path);
}
bool MCFileSystemPathExists(const char *p_path, bool p_folder, bool& r_exists)
{
bool t_success;
t_success = true;
void *t_native_path;
t_native_path = nil;
if (t_success)
t_success = MCFileSystemPathToNative(p_path, t_native_path);
if (t_success)
{
DWORD t_result;
t_result = GetFileAttributesW((LPCWSTR)t_native_path);
if (t_result != INVALID_FILE_ATTRIBUTES)
{
r_exists =
((t_result & (FILE_ATTRIBUTE_DIRECTORY)) == 0 && !p_folder) ||
((t_result & (FILE_ATTRIBUTE_DIRECTORY)) != 0 && p_folder);
}
else<|fim▁hole|> if (GetLastError() == ERROR_FILE_NOT_FOUND)
r_exists = false;
else
t_success = false;
}
}
MCMemoryDeleteArray(t_native_path);
return t_success;
}<|fim▁end|>
|
{
|
<|file_name|>pyext.rs<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::slice;
use cpython::PyBytes;
use cpython::PyModule;
use cpython::PyObject;
use cpython::PyResult;
use cpython::Python;
use cpython_ext::ResultPyErrExt;
use cpython_ext::SimplePyBuf;
use revlogindex::nodemap::empty_index_buffer;
use revlogindex::NodeRevMap;
use revlogindex::RevlogEntry;
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "indexes"].join(".");
let m = PyModule::new(py, &name)?;
m.add_class::<nodemap>(py)?;
Ok(m)
}
py_class!(class nodemap |py| {
data nodemap: NodeRevMap<SimplePyBuf<RevlogEntry>, SimplePyBuf<u32>>;
def __new__(_cls, changelog: &PyObject, index: &PyObject) -> PyResult<nodemap> {
let changelog_buf = SimplePyBuf::new(py, changelog);
let index_buf = SimplePyBuf::new(py, index);
let nm = NodeRevMap::new(changelog_buf, index_buf).map_pyerr(py)?;
nodemap::create_instance(py, nm)
}
def __getitem__(&self, key: PyBytes) -> PyResult<Option<u32>> {
Ok(self.nodemap(py).node_to_rev(key.data(py)).map_pyerr(py)?)
}
def __contains__(&self, key: PyBytes) -> PyResult<bool> {
Ok(self.nodemap(py).node_to_rev(key.data(py)).map_pyerr(py)?.is_some())
}
def partialmatch(&self, hex: &str) -> PyResult<Option<PyBytes>> {
Ok(self.nodemap(py).hex_prefix_to_node(hex).map_pyerr(py)?.map(|b| PyBytes::new(py, b)))
}
def build(&self) -> PyResult<PyBytes> {<|fim▁hole|> Ok(PyBytes::new(py, slice))
}
def lag(&self) -> PyResult<u32> {
Ok(self.nodemap(py).lag())
}
@staticmethod
def emptyindexbuffer() -> PyResult<PyBytes> {
let buf = empty_index_buffer();
Ok(PyBytes::new(py, &buf))
}
});<|fim▁end|>
|
let buf = self.nodemap(py).build_incrementally().map_pyerr(py)?;
let slice = unsafe { slice::from_raw_parts(buf.as_ptr() as *const u8, buf.len() * 4) };
|
<|file_name|>SunshineNewPostsList.tsx<|end_file_name|><|fim▁begin|>import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useMulti } from '../../lib/crud/withMulti';
import React from 'react';
import { userCanDo } from '../../lib/vulcan-users/permissions';
import { useCurrentUser } from '../common/withUser';
const styles = (theme: ThemeType): JssStyles => ({
root: {
backgroundColor:"rgba(0,80,0,.08)"
}
})
const SunshineNewPostsList = ({ terms, classes }: {
terms: PostsViewTerms,
classes: ClassesType,
}) => {
const { results, totalCount } = useMulti({
terms,
collectionName: "Posts",
fragmentName: 'SunshinePostsList',
enableTotal: true,
});
const currentUser = useCurrentUser();
const { SunshineListCount, SunshineListTitle, SunshineNewPostsItem } = Components
if (results && results.length && userCanDo(currentUser, "posts.moderate.all")) {
return (
<div className={classes.root}>
<SunshineListTitle>
Unreviewed Posts <SunshineListCount count={totalCount}/>
</SunshineListTitle>
{results.map(post =>
<div key={post._id} >
<SunshineNewPostsItem post={post}/>
</div><|fim▁hole|> )
} else {
return null
}
}
const SunshineNewPostsListComponent = registerComponent('SunshineNewPostsList', SunshineNewPostsList, {styles});
declare global {
interface ComponentTypes {
SunshineNewPostsList: typeof SunshineNewPostsListComponent
}
}<|fim▁end|>
|
)}
</div>
|
<|file_name|>quaternion.rs<|end_file_name|><|fim▁begin|>// Anima Engine. The quirky game engine
// Copyright (C) 2016 Dragoș Tiselice
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use math::Vector;
/// A simple quaterion `struct` tailored specifically for graphics.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// # use anima_engine::math::Vector;
/// use std::f32::consts;
///
/// let q1 = Quaternion::new_rot(Vector::up(), consts::PI / 4.0);
/// let q2 = Quaternion::new_rot(Vector::up(), consts::PI / 2.0);
///
/// let q3 = q1 * q1;
///
/// const EPSILON: f32 = 0.00001;
///
/// assert!((q3.x - q2.x).abs() < EPSILON);
/// assert!((q3.y - q2.y).abs() < EPSILON);
/// assert!((q3.z - q2.z).abs() < EPSILON);
/// assert!((q3.w - q2.w).abs() < EPSILON);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Quaternion {
/// `f32` imaginary *i* value
pub x: f32,
/// `f32` imaginary *j* value
pub y: f32,
/// `f32` imaginary *k* value
pub z: f32,
/// `f32` real value
pub w: f32
}
impl Quaternion {
/// Creates a quaternion using 4 values.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// let q = Quaternion::new(0.0, 1.0, 2.0, 3.0);
///
/// assert_eq!(q, Quaternion { x: 0.0, y: 1.0, z: 2.0, w: 3.0 });
/// ```
pub fn new(x: f32, y: f32, z: f32, w: f32) -> Quaternion {
Quaternion { x: x, y: y, z: z, w: w }
}
/// Creates a quaternion equivalent to a rotation around a direction.
/// The rotation is measured in radians.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// # use anima_engine::math::Vector;
/// # use std::f32::consts;
/// let q1 = Quaternion::new_rot(Vector::up(), consts::PI / 2.0);
/// let q2 = Quaternion { x: 0.0, y: 0.70710677, z: 0.0, w: 0.70710677 };
///
/// const EPSILON: f32 = 0.00001;
///
/// assert!((q1.x - q2.x).abs() < EPSILON);
/// assert!((q1.y - q2.y).abs() < EPSILON);
/// assert!((q1.z - q2.z).abs() < EPSILON);
/// assert!((q1.w - q2.w).abs() < EPSILON);
/// ```
pub fn new_rot(direction: Vector, angle: f32) -> Quaternion {
let direction = direction.norm();
let sin = (angle / 2.0).sin();
Quaternion {
x: direction.x * sin,
y: direction.y * sin,
z: direction.z * sin,
w: (angle / 2.0).cos()
}
}
/// Creates a quaternion equivalent to the shortest rotation necessary to move
/// the vector representing the direction `start` to the one representing `finish`.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// # use anima_engine::math::Vector;
/// let q = Quaternion::new_sph_rot(Vector::new(1.0, 1.0, 0.0), Vector::new(1.0, 1.0, 1.0));
/// let v = Vector::new(-1.0, -1.0, 0.0);
///
/// const EPSILON: f32 = 0.00001;
///
/// assert!((v.rot(q) - Vector::new_unf(-0.8164966)).len() < EPSILON);
pub fn new_sph_rot(start: Vector, finish: Vector) -> Quaternion {
let direction = finish.cross(start);
let angle = start.angle(finish);
Quaternion::new_rot(direction, angle)
}
/// Creates an identity (0.0, 0.0, 0.0, 1.0) quaternion.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// assert_eq!(Quaternion::ident(), Quaternion { x: 0.0, y: 0.0, z: 0.0, w: 1.0 });
/// ```
pub fn ident() -> Quaternion {
Quaternion { x: 0.0, y: 0.0, z: 0.0, w: 1.0 }
}
/// Computes the conjugate of a quaternion.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// let q = Quaternion::new(1.0, 1.0, 1.0, 1.0);
///
/// assert_eq!(q.conj(), Quaternion { x: -1.0, y: -1.0, z: -1.0, w: 1.0 });
/// ```
pub fn conj(&self) -> Quaternion {
Quaternion { x: -self.x, y: -self.y, z: -self.z, w: self.w }
}
/// Computes the inverse of a quaternion.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// let q = anima_engine::math::Quaternion::new(0.0, 1.0, 2.0, 3.0);
///
/// let result = q * q.inv();
/// let identity = anima_engine::math::Quaternion::ident();
///
/// assert_eq!(result.x, identity.x);
/// ```
pub fn inv(&self) -> Quaternion {
let norm = self.x.powi(2) +
self.y.powi(2) +
self.z.powi(2) +
self.w.powi(2);
Quaternion {
x: -self.x / norm,
y: -self.y / norm,
z: -self.z / norm,
w: self.w / norm
}
}
/// Computes the dot product between two quaternions.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// let q1 = Quaternion::new(1.0, 2.0, 2.0, 1.0);
/// let q2 = Quaternion::new(3.0, 3.0, 1.0, 1.0);
///
/// assert_eq!(q1.dot(q2), 12.0);<|fim▁hole|> self.y * other.y +
self.z * other.z +
self.w * other.w
}
/// Computes the angle in radians between two quaternions.
///
/// # Examples
///
/// ```
/// # use anima_engine::math::Quaternion;
/// # use anima_engine::math::Vector;
/// # use std::f32::consts;
/// let q = Quaternion::new_rot(Vector::up(), consts::PI / 2.0);
///
/// assert_eq!(Quaternion::ident().angle(q), consts::PI / 2.0);
/// ```
pub fn angle(&self, other: Quaternion) -> f32 {
self.dot(other).acos() * 2.0
}
}
use std::ops::Mul;
use mrusty::*;
use math::Interpolate;
impl Mul for Quaternion {
type Output = Quaternion;
fn mul(self, other: Quaternion) -> Quaternion {
Quaternion {
x: other.w * self.x + other.x * self.w + other.y * self.z - other.z * self.y,
y: other.w * self.y - other.x * self.z + other.y * self.w + other.z * self.x,
z: other.w * self.z + other.x * self.y - other.y * self.x + other.z * self.w,
w: other.w * self.w - other.x * self.x - other.y * self.y - other.z * self.z
}
}
}
impl Interpolate for Quaternion {
fn interpolate(&self, other: Quaternion, ratio: f32) -> Quaternion {
let cos_htheta = self.dot(other);
let htheta = cos_htheta.acos();
let sin_htheta = htheta.sin();
if sin_htheta == 0.0 { panic!("Cannot interpolate between two opposing rotations."); }
let ratio1 = ((1.0 - ratio) * htheta).sin() / sin_htheta;
let ratio2 = (ratio * htheta).sin() / sin_htheta;
Quaternion {
x: self.x * ratio1 + other.x * ratio2,
y: self.y * ratio1 + other.y * ratio2,
z: self.z * ratio1 + other.z * ratio2,
w: self.w * ratio1 + other.w * ratio2
}
}
}
mrusty_class!(Quaternion, {
def!("initialize", |x: f64, y: f64, z: f64, w: f64| {
Quaternion::new(x as f32, y as f32, z as f32, w as f32)
});
def_self!("rotation", |mruby, _slf: Value, direction: Vector, angle: f64| {
let quaternion = Quaternion::new_rot((*direction).clone(), angle as f32);
mruby.obj(quaternion)
});
def_self!("sph_rotation", |mruby, _slf: Value, start: Vector, finish: Vector| {
let quaternion = Quaternion::new_sph_rot((*start).clone(), (*finish).clone());
mruby.obj(quaternion)
});
def_self!("identity", |mruby, _slf: Value| {
mruby.obj(Quaternion::ident())
});
def!("x", |mruby, slf: Quaternion| {
mruby.float(slf.x as f64)
});
def!("y", |mruby, slf: Quaternion| {
mruby.float(slf.y as f64)
});
def!("z", |mruby, slf: Quaternion| {
mruby.float(slf.z as f64)
});
def!("w", |mruby, slf: Quaternion| {
mruby.float(slf.w as f64)
});
def!("==", |mruby, slf: Quaternion, other: Quaternion| {
let result = slf.x == other.x &&
slf.y == other.y &&
slf.z == other.z &&
slf.w == other.w;
mruby.bool(result)
});
def!("to_s", |mruby, slf: Quaternion| {
let string = format!("<Quaternion: @x={} @y={} @z={} @w={}>",
slf.x, slf.y, slf.z, slf.w);
mruby.string(&string)
});
def!("*", |mruby, slf: Quaternion, other: Quaternion| {
mruby.obj((*slf).clone() * (*other).clone())
});
def!("conj", |mruby, slf: Quaternion| {
mruby.obj(slf.conj())
});
def!("inv", |mruby, slf: Quaternion| {
mruby.obj(slf.inv())
});
def!("dot", |mruby, slf: Quaternion, other: Quaternion| {
mruby.float(slf.dot((*other).clone()) as f64)
});
def!("angle", |mruby, slf: Quaternion, other: Quaternion| {
mruby.float(slf.angle((*other).clone()) as f64)
});
def!("interpolate", |mruby, slf: Quaternion, other: Quaternion, ratio: f64| {
mruby.obj(slf.interpolate((*other).clone(), ratio as f32))
});
});
#[cfg(test)]
mod tests {
use mrusty::*;
use super::Quaternion;
use super::super::Vector;
describe!(Quaternion, (Vector), "
context 'when roation' do
subject { Quaternion.rotation(Vector.up, Math::PI / 2) }
let(:second) { Quaternion.sph_rotation(Vector.forward, Vector.right) }
it 'returns x on #x' do
expect(subject.x).to be_within(0.001).of second.x
end
it 'returns y on #y' do
expect(subject.y).to be_within(0.001).of second.y
end
it 'returns z on #z' do
expect(subject.z).to be_within(0.001).of second.z
end
it 'returns w on #w' do
expect(subject.w).to be_within(0.001).of second.w
end
it 'computes angle on #angle' do
expect(subject.angle Quaternion.identity).to be_within(0.000001).of Math::PI / 2
end
it 'interpolates on #interpolate' do
interpolated = subject.interpolate(Quaternion.rotation(Vector.up, Math::PI), 0.5)
correct = Quaternion.rotation(Vector.up, Math::PI * 3 / 4)
expect(interpolated.x).to be_within(0.001).of correct.x
expect(interpolated.y).to be_within(0.001).of correct.y
expect(interpolated.z).to be_within(0.001).of correct.z
expect(interpolated.w).to be_within(0.001).of correct.w
end
end
context 'when unit' do
subject { Quaternion.new 1.0, 1.0, 1.0, 1.0 }
it 'returns x on #x' do
expect(subject.x).to eql 1.0
end
it 'returns y on #y' do
expect(subject.y).to eql 1.0
end
it 'returns z on #z' do
expect(subject.z).to eql 1.0
end
it 'returns w on #w' do
expect(subject.w).to eql 1.0
end
it 'converts to String on #to_s' do
expect(subject.to_s).to eql '<Quaternion: @x=1 @y=1 @z=1 @w=1>'
end
it 'returns inverse on #inv' do
expect(subject * subject.inv).to eql Quaternion.identity
end
it 'returns conjugate on #conj' do
expect(subject.conj).to eql Quaternion.new -1.0, -1.0, -1.0, 1.0
end
it 'computes dot product on #dot' do
expect(subject.dot subject).to eql 4.0
end
it 'multiplies quaternion on #*' do
expect(subject * Quaternion.identity).to eql subject
end
end
");
}<|fim▁end|>
|
/// ```
pub fn dot(&self, other: Quaternion) -> f32 {
self.x * other.x +
|
<|file_name|>notestyle.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk, Gdk,GObject,Pango
import commands
import time
import sys,os
import threading
import sqlite3
from config_note import Config
config_note = Config()
path = "/usr/share/gnome-shell/extensions/[email protected]/turbonote-adds/"
path_icon = "/usr/share/gnome-shell/extensions/[email protected]/icons/"
stay = ""
connb = sqlite3.connect(path + 'turbo.db')
a = connb.cursor()
a.execute("SELECT * FROM notestyle")
rows = a.fetchall()
f1 = (str(rows[0][0]))
f2 = (str(rows[0][1]))
f3 = (str(rows[0][2]))
f4 = (str(rows[0][3]))
f5 = str(rows[0][4])
f6 = str(rows[0][5])
connb.close()
def setF1(f):
global f1
f1 = f
def setF2(f):
global f2
f2 = f
def setF3(f):
global f3
f3 = f
def setF4(f):
global f4
f4 = f
def setF5(f):
global f5
f5 = f
def setF6(f):
global f6
f6 = f
class WindowStyle(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="SVN UPDATE")
self.set_default_size(520, 400)
self.set_border_width(15)
self.set_position(Gtk.WindowPosition.CENTER)
self.set_resizable( False )
hb = Gtk.HeaderBar()
hb.props.show_close_button = True
hb.props.title = "NOTE STYLE FOR WINDOWS VIEW"
self.set_titlebar(hb)
self.grid = Gtk.Grid()
self.add(self.grid)
self.space = Gtk.Label()
self.space.set_text(" ")
self.space2 = Gtk.Label()
self.space2.set_text(" ")
self.space3 = Gtk.Label()
self.space3.set_text(" ")
self.space4 = Gtk.Label()
self.space4.set_text(" ")
self.space5 = Gtk.Label()
self.space5.set_text(" ")
self.title_body = Gtk.Label()
self.title_body.set_text("Body Components")
self.title_title = Gtk.Label()
self.title_title.set_text("Title Components")
self.noteTextLabel = Gtk.Label("\n\n\n\n\n Select font for text note... \n\n\n\n\n")
self.noteTextTitle = Gtk.Label(" Note Title... ")
fontbt = Gtk.Button()
fontbt.set_tooltip_text("Body font")
fontbt.connect("clicked", self.on_clickedTextFont)
fontcolorbt = Gtk.Button()
fontcolorbt.set_tooltip_text("Text body color")
fontcolorbt.connect("clicked", self.on_clickedTextColor)
fontbtTitle = Gtk.Button()
fontbtTitle.set_tooltip_text("Font title")
fontbtTitle.connect("clicked", self.on_clickedTextFontTitle)
fontcolorbtTitle = Gtk.Button()
fontcolorbtTitle.set_tooltip_text("title text color")
fontcolorbtTitle.connect("clicked", self.on_clickedTextColorTitle)
bodyColor = Gtk.Button()
bodyColor.set_tooltip_text("Body Color")
bodyColor.connect("clicked", self.on_clickedTextColorBody)
bodytitleColor = Gtk.Button()
bodytitleColor.set_tooltip_text("Title color")
bodytitleColor.connect("clicked", self.on_clickedTextColorTitleBody)
save = Gtk.Button()
save.set_tooltip_text("Save Config")
save.connect("clicked", self.on_save)<|fim▁hole|>
self.colorBody = Gtk.Image()
self.colorBody.set_from_file("/usr/share/gnome-shell/extensions/[email protected]/icons/ic_action_new_eventb" + config_note.getColor() + ".png")
bodyColor.add(self.colorBody)
self.colorTextBody = Gtk.Image()
self.colorTextBody.set_from_file("/usr/share/gnome-shell/extensions/[email protected]/icons/ic_action_new_eventtb" + config_note.getColor() + ".png")
fontcolorbt.add(self.colorTextBody)
self.fontTextBody = Gtk.Image()
self.fontTextBody.set_from_file("/usr/share/gnome-shell/extensions/[email protected]/icons/ic_action_new_eventt" + config_note.getColor() + ".png")
fontbt.add(self.fontTextBody)
self.colorBodyTitle = Gtk.Image()
self.colorBodyTitle.set_from_file("/usr/share/gnome-shell/extensions/[email protected]/icons/ic_action_new_eventb" + config_note.getColor() + ".png")
fontcolorbtTitle.add(self.colorBodyTitle)
self.colorTextBodyTitle = Gtk.Image()
self.colorTextBodyTitle.set_from_file("/usr/share/gnome-shell/extensions/[email protected]/icons/ic_action_new_eventtb" + config_note.getColor() + ".png")
bodytitleColor.add(self.colorTextBodyTitle)
self.fontTextBodyTitle = Gtk.Image()
self.fontTextBodyTitle.set_from_file("/usr/share/gnome-shell/extensions/[email protected]/icons/ic_action_new_eventt" + config_note.getColor() + ".png")
fontbtTitle.add(self.fontTextBodyTitle)
self.saveimg = Gtk.Image()
self.saveimg.set_from_file("/usr/share/gnome-shell/extensions/[email protected]/icons/ic_action_save" + config_note.getColor() + ".png")
save.add(self.saveimg)
self.grid.attach(self.title_body, 0,0 , 3 , 1)
self.grid.attach(self.space2, 0,1 , 1 , 1)
self.grid.attach(bodyColor ,0,2 , 1 , 1)
self.grid.attach(fontcolorbt ,1,2 , 1 , 1)
self.grid.attach(fontbt ,2,2 , 1 , 1)
self.grid.attach(self.space, 3,2 , 1 , 3)
self.grid.attach(self.noteTextTitle, 4,0 , 1 , 2)
self.grid.attach(self.noteTextLabel, 4,1 , 1 , 8)
self.grid.attach(self.space3, 0,3 , 3 , 1)
self.grid.attach(self.title_title, 0,4 , 3 , 1)
self.grid.attach(self.space4, 0,5 , 3 , 1)
self.grid.attach(fontbtTitle, 2,6 , 1 , 1)
self.grid.attach(bodytitleColor, 1,6 , 1 , 1)
self.grid.attach(fontcolorbtTitle, 0,6, 1 , 1)
self.grid.attach(self.space5, 0,7 , 3 , 1)
self.grid.attach(save, 0,8 , 3 , 1)
font1 = Gdk.RGBA()
font2 = Gdk.RGBA()
font3 = Gdk.RGBA()
font4 = Gdk.RGBA()
connb = sqlite3.connect(path + 'turbo.db')
a = connb.cursor()
a.execute("SELECT * FROM notestyle")
rows = a.fetchall()
font1.parse(str(rows[0][0]))
font2.parse(str(rows[0][1]))
font3.parse(str(rows[0][2]))
font4.parse(str(rows[0][3]))
fontbt = str(rows[0][4])
fontbb = str(rows[0][5])
connb.close()
self.noteTextTitle.override_color(Gtk.StateFlags.NORMAL, font3)
self.noteTextTitle.override_background_color(Gtk.StateFlags.NORMAL, font1)
self.noteTextLabel.override_color(Gtk.StateFlags.NORMAL, font4)
self.noteTextLabel.override_background_color(Gtk.StateFlags.NORMAL, font2)
self.noteTextTitle.modify_font(Pango.FontDescription(fontbt))
self.noteTextLabel.modify_font(Pango.FontDescription(fontbb))
def rgb_to_hex(self,rgb):
return '#%02x%02x%02x' % rgb
def on_clickedTextColorTitleBody(self, widget):
cdia = Gtk.ColorSelectionDialog("Select color")
response = cdia.run()
if response == Gtk.ResponseType.OK:
colorsel = cdia.get_color_selection()
rgb = colorsel.get_current_rgba().to_string()
rgb = rgb.replace("rgb","").replace("(","").replace(")","").split(',')
setF1(self.rgb_to_hex((int(rgb[0]), int(rgb[1]), int(rgb[2]))))
self.noteTextTitle.override_background_color(Gtk.StateFlags.NORMAL, colorsel.get_current_rgba())
cdia.destroy()
def on_save(self, widget):
connb = sqlite3.connect(path + 'turbo.db')
a = connb.cursor()
a.execute("UPDATE notestyle SET titulo_color ='" + f1 +"',body_color='" + f2 + "',titulo_font_color ='" + f3 + "',body_font_color ='" + f4 + "',titulo_font_type='" + f5 + "',body_font_type = '" + f6 + "' where 1=1;")
connb.commit()
connb.close()
def on_clickedTextColorBody(self, widget):
cdia = Gtk.ColorSelectionDialog("Select color")
response = cdia.run()
if response == Gtk.ResponseType.OK:
colorsel = cdia.get_color_selection()
rgb = colorsel.get_current_rgba().to_string()
rgb = rgb.replace("rgb","").replace("(","").replace(")","").split(',')
setF2(self.rgb_to_hex((int(rgb[0]), int(rgb[1]), int(rgb[2]))))
self.noteTextLabel.override_background_color(Gtk.StateFlags.NORMAL, colorsel.get_current_rgba())
cdia.destroy()
def on_clickedTextColor(self, widget):
cdia = Gtk.ColorSelectionDialog("Select color")
response = cdia.run()
if response == Gtk.ResponseType.OK:
colorsel = cdia.get_color_selection()
rgb = colorsel.get_current_rgba().to_string()
rgb = rgb.replace("rgb","").replace("(","").replace(")","").split(',')
setF4(self.rgb_to_hex((int(rgb[0]), int(rgb[1]), int(rgb[2]))))
self.noteTextLabel.override_color(Gtk.StateFlags.NORMAL, colorsel.get_current_rgba())
cdia.destroy()
def on_clickedTextFont(self, widget):
fdia = Gtk.FontSelectionDialog("Select font name")
response = fdia.run()
if response == Gtk.ResponseType.OK:
font_desc = Pango.FontDescription(fdia.get_font_name())
setF6(font_desc.get_family())
if font_desc:
self.noteTextLabel.modify_font(font_desc)
fdia.destroy()
def on_clickedTextColorTitle(self, widget):
cdia = Gtk.ColorSelectionDialog("Select color")
response = cdia.run()
if response == Gtk.ResponseType.OK:
colorsel = cdia.get_color_selection()
rgb = colorsel.get_current_rgba().to_string()
rgb = rgb.replace("rgb","").replace("(","").replace(")","").split(',')
setF3(self.rgb_to_hex((int(rgb[0]), int(rgb[1]), int(rgb[2]))))
self.noteTextTitle.override_color(Gtk.StateFlags.NORMAL, colorsel.get_current_rgba())
cdia.destroy()
def on_clickedTextFontTitle(self, widget):
fdia = Gtk.FontSelectionDialog("Select font name")
response = fdia.run()
if response == Gtk.ResponseType.OK:
font_desc = Pango.FontDescription(fdia.get_font_name())
if font_desc:
setF5(font_desc.get_family())
self.noteTextTitle.modify_font(font_desc)
fdia.destroy()<|fim▁end|>
| |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>import httplib
import logging
from error import HapiError
<|fim▁hole|> pass
def get_log(name):
logger = logging.getLogger(name)
logger.addHandler(NullHandler())
return logger<|fim▁end|>
|
class NullHandler(logging.Handler):
def emit(self, record):
|
<|file_name|>fb_oauth.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Facebook OAuth interface."""
# System imports
import json
import logging
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
import oauth2 as oauth<|fim▁hole|># Project imports
from .base_auth import Base3rdPartyAuth
logger = logging.getLogger(__name__)
FACEBOOK_REQUEST_TOKEN_URL = 'https://www.facebook.com/dialog/oauth'
FACEBOOK_ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
FACEBOOK_CHECK_AUTH = 'https://graph.facebook.com/me'
consumer = oauth.Consumer(key=settings.FACEBOOK_APP_ID, secret=settings.FACEBOOK_APP_SECRET)
class FacebookOAuth(Base3rdPartyAuth):
PROVIDER = 'facebook'
BACKEND = 'draalcore.auth.backend.FacebookOAuthBackend'
def get_authorize_url(self, request):
"""Request and prepare URL for login using Facebook account."""
base_url = '{}?client_id={}&redirect_uri={}&scope={}'
return base_url.format(FACEBOOK_REQUEST_TOKEN_URL, settings.FACEBOOK_APP_ID,
quote_plus(self.get_callback_url()), 'email')
def set_user(self, response):
return self.get_user({
'username': 'fb-{}'.format(response['id']),
'email': response['email'],
'first_name': response['first_name'],
'last_name': response['last_name'],
})
def authorize(self, request):
base_url = '{}?client_id={}&redirect_uri={}&client_secret={}&code={}'
request_url = base_url.format(FACEBOOK_ACCESS_TOKEN_URL, settings.FACEBOOK_APP_ID,
self.get_callback_url(), settings.FACEBOOK_APP_SECRET,
request.GET.get('code'))
# Get the access token from Facebook
client = oauth.Client(consumer)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
# Get profile info from Facebook
base_url = '{}?access_token={}&fields=id,first_name,last_name,email'
access_token = json.loads(content)['access_token']
request_url = base_url.format(FACEBOOK_CHECK_AUTH, access_token)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
user_data = json.loads(content)
# Authenticate user
logger.debug(user_data)
user = self.set_user(user_data)
return self.authenticate(request, user.username)
self.login_failure()<|fim▁end|>
|
from django.conf import settings
|
<|file_name|>AircraftStateFilter.cpp<|end_file_name|><|fim▁begin|>/* Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2011 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "AircraftStateFilter.hpp"
#include "Navigation/Geometry/GeoVector.hpp"
#include <assert.h>
AircraftStateFilter::AircraftStateFilter(const fixed cutoff_wavelength)
:x_diff_filter(fixed_zero), y_diff_filter(fixed_zero),
alt_diff_filter(fixed_zero),
x_low_pass(cutoff_wavelength), y_low_pass(cutoff_wavelength),
alt_low_pass(cutoff_wavelength),
x(fixed_zero), y(fixed_zero) {}
void
AircraftStateFilter::Reset(const AircraftState &state)
{
last_state = state;
x = fixed_zero;
y = fixed_zero;
v_x = fixed_zero;
v_y = fixed_zero;
v_alt = fixed_zero;
x_low_pass.reset(fixed_zero);
y_low_pass.reset(fixed_zero);
alt_low_pass.reset(fixed_zero);
x_diff_filter.reset(x, fixed_zero);
y_diff_filter.reset(y, fixed_zero);
alt_diff_filter.reset(state.altitude, fixed_zero);
}
void
AircraftStateFilter::Update(const AircraftState &state)
{
fixed dt = state.time - last_state.time;
if (negative(dt) || dt > fixed(60)) {
Reset(state);
return;
}
if (!positive(dt))
return;
GeoVector vec(last_state.location, state.location);
const fixed MACH_1 = fixed_int_constant(343);
if (vec.Distance > fixed(1000) || vec.Distance / dt > MACH_1) {
Reset(state);
return;
}
x += vec.Bearing.sin() * vec.Distance;<|fim▁hole|> v_y = y_low_pass.update(y_diff_filter.update(y));
v_alt = alt_low_pass.update(alt_diff_filter.update(state.altitude));
last_state = state;
}
fixed
AircraftStateFilter::GetSpeed() const
{
return hypot(v_x, v_y);
}
Angle
AircraftStateFilter::GetBearing() const
{
return Angle::from_xy(v_y, v_x).as_bearing();
}
bool
AircraftStateFilter::Design(const fixed cutoff_wavelength)
{
bool ok = true;
ok &= x_low_pass.design(cutoff_wavelength);
ok &= y_low_pass.design(cutoff_wavelength);
ok &= alt_low_pass.design(cutoff_wavelength);
assert(ok);
return ok;
}
AircraftState
AircraftStateFilter::GetPredictedState(const fixed &in_time) const
{
AircraftState state_next = last_state;
state_next.ground_speed = GetSpeed();
state_next.vario = GetClimbRate();
state_next.altitude = last_state.altitude + state_next.vario * in_time;
state_next.location = GeoVector(state_next.ground_speed * in_time,
GetBearing()).end_point(last_state.location);
return state_next;
}<|fim▁end|>
|
y += vec.Bearing.cos() * vec.Distance;
v_x = x_low_pass.update(x_diff_filter.update(x));
|
<|file_name|>Go.java<|end_file_name|><|fim▁begin|>package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2010 Bo Zimmerman
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.
*/
@SuppressWarnings("unchecked")
public class Go extends StdCommand
{
public Go(){}
private String[] access={"GO","WALK"};
public String[] getAccessWords(){return access;}
public int energyExpenseFactor(){return 1;}
public void ridersBehind(Vector riders,
Room sourceRoom,
Room destRoom,
int directionCode,
boolean flee)
{
if(riders!=null)
for(int r=0;r<riders.size();r++)
{
Rider rider=(Rider)riders.elementAt(r);
if(rider instanceof MOB)
{
MOB rMOB=(MOB)rider;
if((rMOB.location()==sourceRoom)
||(rMOB.location()==destRoom))
{
boolean fallOff=false;
if(rMOB.location()==sourceRoom)
{
if(rMOB.riding()!=null)
rMOB.tell("You ride "+rMOB.riding().name()+" "+Directions.getDirectionName(directionCode)+".");
if(!move(rMOB,directionCode,flee,false,true,false))
fallOff=true;
}
if(fallOff)
{
if(rMOB.riding()!=null)
rMOB.tell("You fall off "+rMOB.riding().name()+"!");
rMOB.setRiding(null);
}
}
else
rMOB.setRiding(null);
}
else
if(rider instanceof Item)
{
Item rItem=(Item)rider;
if((rItem.owner()==sourceRoom)
||(rItem.owner()==destRoom))
destRoom.bringItemHere(rItem,-1,false);
else
rItem.setRiding(null);
}
}
}
public static Vector addRiders(Rider theRider,
Rideable riding,
Vector riders)
{
if((riding!=null)&&(riding.mobileRideBasis()))
for(int r=0;r<riding.numRiders();r++)
{
Rider rider=riding.fetchRider(r);
if((rider!=null)
&&(rider!=theRider)
&&(!riders.contains(rider)))
{
riders.addElement(rider);
if(rider instanceof Rideable)
addRiders(theRider,(Rideable)rider,riders);
}
}
return riders;
}
public Vector ridersAhead(Rider theRider,
Room sourceRoom,
Room destRoom,
int directionCode,
boolean flee)
{
Vector riders=new Vector();
Rideable riding=theRider.riding();
Vector rideables=new Vector();
while((riding!=null)&&(riding.mobileRideBasis()))
{
rideables.addElement(riding);
addRiders(theRider,riding,riders);
if((riding instanceof Rider)&&((Rider)riding).riding()!=theRider.riding())
riding=((Rider)riding).riding();
else
riding=null;
<|fim▁hole|> }
if(theRider instanceof Rideable)
addRiders(theRider,(Rideable)theRider,riders);
for(int r=riders.size()-1;r>=0;r--)
{
Rider R=(Rider)riders.elementAt(r);
if((R instanceof Rideable)&&(((Rideable)R).numRiders()>0))
{
if(!rideables.contains(R))
rideables.addElement(R);
riders.removeElement(R);
}
}
for(int r=0;r<rideables.size();r++)
{
riding=(Rideable)rideables.elementAt(r);
if((riding instanceof Item)
&&((sourceRoom).isContent((Item)riding)))
destRoom.bringItemHere((Item)riding,-1,false);
else
if((riding instanceof MOB)
&&((sourceRoom).isInhabitant((MOB)riding)))
{
((MOB)riding).tell("You are ridden "+Directions.getDirectionName(directionCode)+".");
if(!move(((MOB)riding),directionCode,false,false,true,false))
{
if(theRider instanceof MOB)
((MOB)theRider).tell(((MOB)riding).name()+" won't seem to let you go that way.");
r=r-1;
for(;r>=0;r--)
{
riding=(Rideable)rideables.elementAt(r);
if((riding instanceof Item)
&&((destRoom).isContent((Item)riding)))
sourceRoom.bringItemHere((Item)riding,-1,false);
else
if((riding instanceof MOB)
&&(((MOB)riding).isMonster())
&&((destRoom).isInhabitant((MOB)riding)))
sourceRoom.bringMobHere((MOB)riding,false);
}
return null;
}
}
}
return riders;
}
public boolean move(MOB mob,
int directionCode,
boolean flee,
boolean nolook,
boolean noriders)
{
return move(mob,directionCode,flee,nolook,noriders,false);
}
public boolean move(MOB mob,
int directionCode,
boolean flee,
boolean nolook,
boolean noriders,
boolean always)
{
if(directionCode<0) return false;
if(mob==null) return false;
Room thisRoom=mob.location();
if(thisRoom==null) return false;
Room destRoom=thisRoom.getRoomInDir(directionCode);
Exit exit=thisRoom.getExitInDir(directionCode);
if(destRoom==null)
{
mob.tell("You can't go that way.");
return false;
}
Exit opExit=thisRoom.getReverseExit(directionCode);
String directionName=(directionCode==Directions.GATE)&&(exit!=null)?"through "+exit.name():Directions.getDirectionName(directionCode);
String otherDirectionName=(Directions.getOpDirectionCode(directionCode)==Directions.GATE)&&(exit!=null)?exit.name():Directions.getFromDirectionName(Directions.getOpDirectionCode(directionCode));
int generalMask=always?CMMsg.MASK_ALWAYS:0;
int leaveCode=generalMask|CMMsg.MSG_LEAVE;
if(flee)
leaveCode=generalMask|CMMsg.MSG_FLEE;
CMMsg enterMsg=null;
CMMsg leaveMsg=null;
if((mob.riding()!=null)&&(mob.riding().mobileRideBasis()))
{
enterMsg=CMClass.getMsg(mob,destRoom,exit,generalMask|CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,"<S-NAME> ride(s) "+mob.riding().name()+" in from "+otherDirectionName+".");
leaveMsg=CMClass.getMsg(mob,thisRoom,opExit,leaveCode,((flee)?"You flee "+directionName+".":null),leaveCode,null,leaveCode,((flee)?"<S-NAME> flee(s) with "+mob.riding().name()+" "+directionName+".":"<S-NAME> ride(s) "+mob.riding().name()+" "+directionName+"."));
}
else
{
enterMsg=CMClass.getMsg(mob,destRoom,exit,generalMask|CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,"<S-NAME> "+CMLib.flags().dispositionString(mob,CMFlagLibrary.flag_arrives)+" from "+otherDirectionName+".");
leaveMsg=CMClass.getMsg(mob,thisRoom,opExit,leaveCode,((flee)?"You flee "+directionName+".":null),leaveCode,null,leaveCode,((flee)?"<S-NAME> flee(s) "+directionName+".":"<S-NAME> "+CMLib.flags().dispositionString(mob,CMFlagLibrary.flag_leaves)+" "+directionName+"."));
}
boolean gotoAllowed=CMSecurity.isAllowed(mob,destRoom,"GOTO");
if((exit==null)&&(!gotoAllowed))
{
mob.tell("You can't go that way.");
return false;
}
else
if(exit==null)
thisRoom.showHappens(CMMsg.MSG_OK_VISUAL,"The area to the "+directionName+" shimmers and becomes transparent.");
else
if((!exit.okMessage(mob,enterMsg))&&(!gotoAllowed))
return false;
else
if(!leaveMsg.target().okMessage(mob,leaveMsg)&&(!gotoAllowed))
return false;
else
if((opExit!=null)&&(!opExit.okMessage(mob,leaveMsg))&&(!gotoAllowed))
return false;
else
if(!enterMsg.target().okMessage(mob,enterMsg)&&(!gotoAllowed))
return false;
else
if(!mob.okMessage(mob,enterMsg)&&(!gotoAllowed))
return false;
if(mob.riding()!=null)
{
if((!mob.riding().okMessage(mob,enterMsg))&&(!gotoAllowed))
return false;
}
else
{
if(!mob.isMonster())
for(int i=0;i<energyExpenseFactor();i++)
mob.curState().expendEnergy(mob,mob.maxState(),true);
if((!flee)&&(!mob.curState().adjMovement(-1,mob.maxState()))&&(!gotoAllowed))
{
mob.tell("You are too tired.");
return false;
}
if((mob.soulMate()==null)&&(mob.playerStats()!=null)&&(mob.riding()==null)&&(mob.location()!=null))
mob.playerStats().adjHygiene(mob.location().pointsPerMove(mob));
}
Vector riders=null;
if(!noriders)
{
riders=ridersAhead(mob,(Room)leaveMsg.target(),(Room)enterMsg.target(),directionCode,flee);
if(riders==null) return false;
}
Vector enterTrailersSoFar=null;
Vector leaveTrailersSoFar=null;
if((leaveMsg.trailerMsgs()!=null)&&(leaveMsg.trailerMsgs().size()>0))
{
leaveTrailersSoFar=new Vector();
leaveTrailersSoFar.addAll(leaveMsg.trailerMsgs());
leaveMsg.trailerMsgs().clear();
}
if((enterMsg.trailerMsgs()!=null)&&(enterMsg.trailerMsgs().size()>0))
{
enterTrailersSoFar=new Vector();
enterTrailersSoFar.addAll(enterMsg.trailerMsgs());
enterMsg.trailerMsgs().clear();
}
if(exit!=null) exit.executeMsg(mob,enterMsg);
if(mob.location()!=null) mob.location().delInhabitant(mob);
((Room)leaveMsg.target()).send(mob,leaveMsg);
if(enterMsg.target()==null)
{
((Room)leaveMsg.target()).bringMobHere(mob,false);
mob.tell("You can't go that way.");
return false;
}
mob.setLocation((Room)enterMsg.target());
((Room)enterMsg.target()).addInhabitant(mob);
((Room)enterMsg.target()).send(mob,enterMsg);
if(opExit!=null) opExit.executeMsg(mob,leaveMsg);
if(!nolook)
{
CMLib.commands().postLook(mob,true);
if((!mob.isMonster())
&&(CMath.bset(mob.getBitmap(),MOB.ATT_AUTOWEATHER))
&&(((Room)enterMsg.target())!=null)
&&((thisRoom.domainType()&Room.INDOORS)>0)
&&((((Room)enterMsg.target()).domainType()&Room.INDOORS)==0)
&&(((Room)enterMsg.target()).getArea().getClimateObj().weatherType(((Room)enterMsg.target()))!=Climate.WEATHER_CLEAR)
&&(((Room)enterMsg.target()).isInhabitant(mob)))
mob.tell("\n\r"+((Room)enterMsg.target()).getArea().getClimateObj().weatherDescription(((Room)enterMsg.target())));
}
if(!noriders)
ridersBehind(riders,(Room)leaveMsg.target(),(Room)enterMsg.target(),directionCode,flee);
if(!flee)
for(int f=0;f<mob.numFollowers();f++)
{
MOB follower=mob.fetchFollower(f);
if(follower!=null)
{
if((follower.amFollowing()==mob)
&&((follower.location()==thisRoom)||(follower.location()==destRoom)))
{
if((follower.location()==thisRoom)&&(CMLib.flags().aliveAwakeMobile(follower,true)))
{
if(CMath.bset(follower.getBitmap(),MOB.ATT_AUTOGUARD))
thisRoom.show(follower,null,null,CMMsg.MSG_OK_ACTION,"<S-NAME> remain(s) on guard here.");
else
{
follower.tell("You follow "+mob.name()+" "+Directions.getDirectionName(directionCode)+".");
if(!move(follower,directionCode,false,false,false,false))
{
//follower.setFollowing(null);
}
}
}
}
//else
// follower.setFollowing(null);
}
}
if((leaveTrailersSoFar!=null)&&(leaveMsg.target() instanceof Room))
for(int t=0;t<leaveTrailersSoFar.size();t++)
((Room)leaveMsg.target()).send(mob,(CMMsg)leaveTrailersSoFar.elementAt(t));
if((enterTrailersSoFar!=null)&&(enterMsg.target() instanceof Room))
for(int t=0;t<enterTrailersSoFar.size();t++)
((Room)enterMsg.target()).send(mob,(CMMsg)enterTrailersSoFar.elementAt(t));
return true;
}
protected Command stander=null;
protected Vector ifneccvec=null;
public void standIfNecessary(MOB mob, int metaFlags)
throws java.io.IOException
{
if((ifneccvec==null)||(ifneccvec.size()!=2))
{
ifneccvec=new Vector();
ifneccvec.addElement("STAND");
ifneccvec.addElement("IFNECESSARY");
}
if(stander==null) stander=CMClass.getCommand("Stand");
if((stander!=null)&&(ifneccvec!=null))
stander.execute(mob,ifneccvec,metaFlags);
}
public boolean execute(MOB mob, Vector commands, int metaFlags)
throws java.io.IOException
{
standIfNecessary(mob,metaFlags);
if((commands.size()>3)
&&(commands.firstElement() instanceof Integer))
{
return move(mob,
((Integer)commands.elementAt(0)).intValue(),
((Boolean)commands.elementAt(1)).booleanValue(),
((Boolean)commands.elementAt(2)).booleanValue(),
((Boolean)commands.elementAt(3)).booleanValue(),false);
}
String whereStr=CMParms.combine(commands,1);
Room R=mob.location();
int direction=-1;
if(whereStr.equalsIgnoreCase("OUT"))
{
if(!CMath.bset(R.domainType(),Room.INDOORS))
{
mob.tell("You aren't indoors.");
return false;
}
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
if((R.getExitInDir(d)!=null)
&&(R.getRoomInDir(d)!=null)
&&(!CMath.bset(R.getRoomInDir(d).domainType(),Room.INDOORS)))
{
if(direction>=0)
{
mob.tell("Which way out? Try North, South, East, etc..");
return false;
}
direction=d;
}
if(direction<0)
{
mob.tell("There is no direct way out of this place. Try a direction.");
return false;
}
}
if(direction<0)
direction=Directions.getGoodDirectionCode(whereStr);
if(direction<0)
{
Environmental E=null;
if(R!=null)
E=R.fetchFromRoomFavorItems(null,whereStr,Item.WORNREQ_UNWORNONLY);
if(E instanceof Rideable)
{
Command C=CMClass.getCommand("Enter");
return C.execute(mob,commands,metaFlags);
}
if((E instanceof Exit)&&(R!=null))
{
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
if(R.getExitInDir(d)==E)
{ direction=d; break;}
}
}
String doing=(String)commands.elementAt(0);
if(direction>=0)
move(mob,direction,false,false,false,false);
else
{
boolean doneAnything=false;
if(commands.size()>2)
for(int v=1;v<commands.size();v++)
{
int num=1;
String s=(String)commands.elementAt(v);
if(CMath.s_int(s)>0)
{
num=CMath.s_int(s);
v++;
if(v<commands.size())
s=(String)commands.elementAt(v);
}
else
if(("NSEWUDnsewud".indexOf(s.charAt(s.length()-1))>=0)
&&(CMath.s_int(s.substring(0,s.length()-1))>0))
{
num=CMath.s_int(s.substring(0,s.length()-1));
s=s.substring(s.length()-1);
}
direction=Directions.getGoodDirectionCode(s);
if(direction>=0)
{
doneAnything=true;
for(int i=0;i<num;i++)
{
if(mob.isMonster())
{
if(!move(mob,direction,false,false,false,false))
return false;
}
else
{
Vector V=new Vector();
V.addElement(doing);
V.addElement(Directions.getDirectionName(direction));
mob.enqueCommand(V,metaFlags,0);
}
}
}
else
break;
}
if(!doneAnything)
mob.tell(CMStrings.capitalizeAndLower(doing)+" which direction?\n\rTry north, south, east, west, up, or down.");
}
return false;
}
public double actionsCost(MOB mob, Vector cmds){
double cost=CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCMDTIME),100.0);
if((mob!=null)&&(CMath.bset(mob.getBitmap(),MOB.ATT_AUTORUN)))
cost /= 4.0;
return cost;
}
public boolean canBeOrdered(){return true;}
}<|fim▁end|>
| |
<|file_name|>AgeDetectedIssueCode.java<|end_file_name|><|fim▁begin|>package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>AgeDetectedIssueCodeのJavaクラス。
*
* <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。
* <p>
* <pre>
* <simpleType name="AgeDetectedIssueCode">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="AGE"/>
* <enumeration value="DOSEHINDA"/>
* <enumeration value="DOSELINDA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
<|fim▁hole|>public enum AgeDetectedIssueCode {
AGE,
DOSEHINDA,
DOSELINDA;
public String value() {
return name();
}
public static AgeDetectedIssueCode fromValue(String v) {
return valueOf(v);
}
}<|fim▁end|>
|
@XmlType(name = "AgeDetectedIssueCode")
@XmlEnum
|
<|file_name|>exampleLoaderTemplate.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exampleLoaderTemplate.ui'
#
# Created: Sat Dec 17 23:46:27 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(762, 302)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setMargin(0)<|fim▁hole|> self.splitter.setObjectName(_fromUtf8("splitter"))
self.layoutWidget = QtGui.QWidget(self.splitter)
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget)
self.verticalLayout.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.exampleTree = QtGui.QTreeWidget(self.layoutWidget)
self.exampleTree.setObjectName(_fromUtf8("exampleTree"))
self.exampleTree.headerItem().setText(0, _fromUtf8("1"))
self.exampleTree.header().setVisible(False)
self.verticalLayout.addWidget(self.exampleTree)
self.loadBtn = QtGui.QPushButton(self.layoutWidget)
self.loadBtn.setObjectName(_fromUtf8("loadBtn"))
self.verticalLayout.addWidget(self.loadBtn)
self.codeView = QtGui.QTextBrowser(self.splitter)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Monospace"))
font.setPointSize(10)
self.codeView.setFont(font)
self.codeView.setObjectName(_fromUtf8("codeView"))
self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.loadBtn.setText(QtGui.QApplication.translate("Form", "Load Example", None, QtGui.QApplication.UnicodeUTF8))<|fim▁end|>
|
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.splitter = QtGui.QSplitter(Form)
self.splitter.setOrientation(QtCore.Qt.Horizontal)
|
<|file_name|>regex_debug.cpp<|end_file_name|><|fim▁begin|>/*
*
* Copyright (c) 1998-2004
* John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE: regex_debug.cpp
* VERSION: see <autoboost/version.hpp>
* DESCRIPTION: Misc. debugging helpers.
*/
#define AUTOBOOST_REGEX_SOURCE
#include <autoboost/regex/config.hpp>
//
// regex configuration information: this prints out the settings used
// when the library was built - include in debugging builds only:
//
#ifdef AUTOBOOST_REGEX_CONFIG_INFO
#define print_macro regex_lib_print_macro
#define print_expression regex_lib_print_expression
#define print_byte_order regex_lib_print_byte_order
#define print_sign regex_lib_print_sign
#define print_compiler_macros regex_lib_print_compiler_macros
#define print_stdlib_macros regex_lib_print_stdlib_macros
#define print_platform_macros regex_lib_print_platform_macros
#define print_autoboost_macros regex_lib_print_autoboost_macros
#define print_separator regex_lib_print_separator
#define OLD_MAIN regex_lib_main
#define NEW_MAIN regex_lib_main2
#define NO_RECURSE
#include <libs/regex/test/config_info/regex_config_info.cpp>
AUTOBOOST_REGEX_DECL void AUTOBOOST_REGEX_CALL print_regex_library_info()
{<|fim▁hole|>}
#endif<|fim▁end|>
|
std::cout << "\n\n";
print_separator();
std::cout << "Regex library build configuration:\n\n";
regex_lib_main2();
|
<|file_name|>deltaApp.py<|end_file_name|><|fim▁begin|>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.widget import Widget
from kivy.clock import Clock
import os
import dynamixel
import sys
import subprocess
import optparse
import yaml
import cinematica
import itertools
import collections
import time
import serial as arduinoSerial
import copy
import math
from robot import *
class Inverso(MastermindInvers):
def empezar(self):
"""
Complementa la funcion empezar del juego inverso
Se piensa un codigo aleatorio el cual el usuario ha de adivinar
"""
self.codigo = [randint(0,4) for i in range(5)]
print 'ready'
print self.codigo
def continuar(self, guess):
"""
Complementa la funcion continuar el siguiente turno del juego inverso
Calcula la respuesta del robot ante el codigo propuesta por el usuario
"""
self.guess = copy.copy(guess)
self.codigoPrueba = copy.copy(self.codigo)
self.rojas = 0
self.blancas = 0
self.buscarRojas()
self.buscarBlancas()
return self.rojas, self.blancas
class Delta(MastermindDirecte, TabbedPanel):
text_input = ObjectProperty(None)
colors = ['Negro', 'Azul', 'Verde', 'Blanco', 'Rojo']
#red = (255, 0, 0, 1) azul = (0, 100, 250, 1) amari = (255, 255, 0, 1) white = (255, 255, 255, 1) negro = (0, 0, 0, 1)
colorsrgba = [(0, 0, 0, 1),(0, 100, 250, 1),(255, 255, 0, 1),(255, 255, 255, 1),(255, 0, 0, 1)]
robot=Robot()
robot.buscarServos()
inv = Inverso()
def jugar_p_directo(self):
"""
Empieza el juego directo con un primer movimiento
Si el programa tiene una configuracion cargada, primero limpia el tablero y luego empieza
Dentro del while:
Continua un turno del juego, requiere la respuesta del usuario por pulsadores
Siempre guarda la ultima configuracion del robot para siguientes inicios
"""
self.linea = 1
choices, holes = 5, 5
self.pool = self.generate_initial_pool(choices, holes)#genera una lista con todas las posibilidades sin repetir
self.guess = [0,0,1,1,1]
self.ids.textprueba.text = "Try this:"
huecoX = 'hueco'+str(self.linea)
for y in range(5):
huecoXY=huecoX+str(y)
self.ids[huecoXY].background_color = self.colorsrgba[self.guess[y]]
Clock.schedule_once(self.esperar, 1)
checkbox = self.ids.checkbox
checkbox.bind(active=self.on_checkbox_active)
print checkbox.active
try:
######################################## cargamos la ultima configuracion
ultimoCodigo = open('ultimoCodigo', 'r')
ultimo = ultimoCodigo.readline().split('|')
codigo = [int(i) for i in ultimo[:-1]]
huecos = ultimo[5].split(',')
huecos.reverse()
matrizOcupados = [int(i) for i in huecos]
for i in range(5):
for e in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosColores[i][e][3]=p
for i in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosRobot[i][3]=p
ultimoCodigo.close()
#########################################aqui ha de venir el movimiento de bolitas!!!!
self.robot.quitar_bolitas(codigo, self.guess)
self.robot.poner_bolitas(self.guess, codigo)
self.robot.mover_robot([0, 0, -24])
except:
print 'No hay archivo ultimoCodigo = No hay bolitas puestas'
#########################################aqui ha de venir el movimiento de bolitas!!!!
ultimo = [None, None, None, None, None]
self.robot.poner_bolitas(self.guess, ultimo)
self.robot.mover_robot([0, 0, -24])
######################################### Guardamos la ultima combinacion y la matriz de huecos
ultimoCodigo = open('ultimoCodigo', 'w')
s=''
for listaHuecosColor in self.robot.listaHuecosColores:
for listaHuecoColor in listaHuecosColor:
s+='{0},'.format(listaHuecoColor[3])
for listaHuecoRobot in self.robot.listaHuecosRobot:
s+='{0},'.format(listaHuecoRobot[3])
ultimoCodigo.write('{0}|{1}|{2}|{3}|{4}|{5}'.format(self.guess[0],self.guess[1],self.guess[2],self.guess[3],self.guess[4],s[:-1]))
ultimoCodigo.close()
"""
continuar = Clock.create_trigger(self.continuar_p_directo)
continuar() #1 intento
continuar = Clock.create_trigger(self.continuar_p_directo)
continuar() #2 intento
continuar = Clock.create_trigger(self.continuar_p_directo)
continuar() #3 intento
continuar = Clock.create_trigger(self.continuar_p_directo)
continuar() #4 intento
continuar = Clock.create_trigger(self.continuar_p_directo)
continuar() #5 intento
continuar = Clock.create_trigger(self.continuar_p_directo)
continuar() #6 intento
"""
"""
while True:
self.continuar_p_directo()
"""
def continuar_p_directo(self):
######################################### respuesta del arduino
self.pulsadores = Arduino()
respuesta = self.pulsadores.codigo2()
correct = respuesta[0]
close = respuesta[1]
########################################## termina respuesta
if self.linea>7:
self.robot.perder()
return None
self.linea+=1
"""arduino.write('2')
self.respuesta=''
Clock.schedule_interval(self.respuesta_d_arduino, 1)# respuesta del arduino
respuesta = self.respuesta_d
correct = respuesta[0]
close = respuesta[1]
"""
feedback = self.Feedback(correct, close)
if self.linea >1:
self.ids['textrojo'+str(self.linea-1)].text = str(correct)
self.ids['textblanco'+str(self.linea-1)].text = str(close)
if feedback.correct == 5:
print "\nHe ganado!!"
self.ids.textprueba.text = "He ganado! (juas) (juas)"
self.ids.jugar_p_directo.text='Reiniciar (pulsadores)'
self.ids.empezar_i_directo.text='Reiniciar (interfaz)'
self.robot.celebrar()
return None
#Clock.schedule_once(self.esperar, 1)
try:
initime = time.time()
self.previousPool = copy.copy(self.pool)
self.pool = list(self.filter_pool(feedback)) #renueva la lista de posibles combinaciones restantes en base a la interaccion del usuario
print "{0} posibles opciones restantes. Pensando...\n".format(len(self.pool))
self.previousGuess = copy.copy(self.guess)
self.guess = list(self.make_guess(feedback, initime))
huecoX = 'hueco'+str(self.linea)
for y in range(5):
huecoXY=huecoX+str(y)
self.ids[huecoXY].background_color = self.colorsrgba[self.guess[y]]
#########################################aqui ha de venir el movimiento de bolitas!!!!
print self.previousGuess
print self.guess
self.robot.quitar_bolitas(self.previousGuess, self.guess)
self.robot.poner_bolitas(self.guess, self.previousGuess)
self.robot.mover_robot([0, 0, -24])
######################################### Guardamos la ultima combinacion y la matriz de huecos
ultimoCodigo = open('ultimoCodigo', 'w')
s=''
for listaHuecosColor in self.robot.listaHuecosColores:
for listaHuecoColor in listaHuecosColor:
s+='{0},'.format(listaHuecoColor[3])
for listaHuecoRobot in self.robot.listaHuecosRobot:
s+='{0},'.format(listaHuecoRobot[3])
ultimoCodigo.write('{0}|{1}|{2}|{3}|{4}|{5}'.format(self.guess[0],self.guess[1],self.guess[2],self.guess[3],self.guess[4],s[:-1]))
ultimoCodigo.close()
except:
self.ids.textprueba.text = "Te has equivocado. Cambia tu respuesta y vuelve a intentarlo. Si persiste, reinicia."
self.ids.jugar_p_directo.text = 'Reiniciar (pulsadores)'
self.ids.empezar_i_directo.text='Reiniciar (interfaz)'
self.ids.continuar_i_directo.text ='No tocar (interfaz)'
self.pool = copy.copy(self.previousPool)
def empezar_i_directo(self):
self.linea = 1
choices, holes = 5, 5
self.pool = self.generate_initial_pool(choices, holes)#genera una lista con todas las posibilidades sin repetir
self.guess = []
for i in range(holes):
self.guess =[0,0,1,1,1]
print "Try this: {0}".format(self.codeToColor(self.guess))
self.ids.textprueba.text = "Try this:"#genera una combinacion cualquiera primera
huecoX = 'hueco'+str(self.linea)
for y in range(5):
huecoXY=huecoX+str(y)
self.ids[huecoXY].background_color = self.colorsrgba[self.guess[y]]
Clock.schedule_once(self.esperar, 1)
#checkbox = self.ids.checkbox
#checkbox.bind(active=self.on_checkbox_active)
try:
######################################## cargamos la ultima configuracion
ultimoCodigo = open('ultimoCodigo', 'r')
ultimo = ultimoCodigo.readline().split('|')
codigo = [int(i) for i in ultimo[:-1]]
huecos = ultimo[5].split(',')
huecos.reverse()
matrizOcupados = [int(i) for i in huecos]
for i in range(5):
for e in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosColores[i][e][3]=p
for i in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosRobot[i][3]=p
ultimoCodigo.close()
#########################################aqui ha de venir el movimiento de bolitas!!!!
self.robot.quitar_bolitas(codigo, self.guess)
self.robot.poner_bolitas(self.guess, codigo)
self.robot.mover_robot([0, 0, -24])
except:
print 'No hay archivo ultimoCodigo = No hay bolitas puestas'
#########################################aqui ha de venir el movimiento de bolitas!!!!
ultimo = [None, None, None, None, None]
self.robot.poner_bolitas(self.guess, ultimo)
self.robot.mover_robot([0, 0, -24])
######################################### Guardamos la ultima combinacion y la matriz de huecos
ultimoCodigo = open('ultimoCodigo', 'w')
s=''
for listaHuecosColor in self.robot.listaHuecosColores:
for listaHuecoColor in listaHuecosColor:
s+='{0},'.format(listaHuecoColor[3])
for listaHuecoRobot in self.robot.listaHuecosRobot:
s+='{0},'.format(listaHuecoRobot[3])
ultimoCodigo.write('{0}|{1}|{2}|{3}|{4}|{5}'.format(self.guess[0],self.guess[1],self.guess[2],self.guess[3],self.guess[4],s[:-1]))
ultimoCodigo.close()
def continuar_i_directo(self):
"""
Continua un turno del juego, requiere la respuesta del usuario por texto de interfaz
Siempre guarda la ultima configuracion del robot para siguientes inicios
"""
if self.linea>7:
self.robot.perder()
return None
self.linea+=1
correct = int(self.ids.reds.text)
close = int(self.ids.whites.text)
feedback = self.Feedback(correct, close)
if self.linea >1:
self.ids['textrojo'+str(self.linea-1)].text = str(correct)
self.ids['textblanco'+str(self.linea-1)].text = str(close)
if feedback.correct == 5:
print "\nHe ganado!!"
self.ids.textprueba.text = "He ganado! (juas) (juas)"
self.ids.jugar_p_directo.text='Reiniciar (pulsadores)'
self.ids.empezar_i_directo.text='Reiniciar (interfaz)'
self.robot.celebrar()
return None
Clock.schedule_once(self.esperar, 1)
try:
initime = time.time()
self.previousPool = copy.copy(self.pool)
self.pool = list(self.filter_pool(feedback)) #renueva la lista de posibles combinaciones restantes en base a la interaccion del usuario
print "{0} posibles opciones restantes. Pensando...\n".format(len(self.pool))
self.previousGuess = copy.copy(self.guess)
self.guess = list(self.make_guess(feedback, initime))
huecoX = 'hueco'+str(self.linea)
for y in range(5):
huecoXY=huecoX+str(y)
self.ids[huecoXY].background_color = self.colorsrgba[self.guess[y]]
#########################################aqui ha de venir el movimiento de bolitas!!!!
print self.previousGuess
print self.guess
self.robot.quitar_bolitas(self.previousGuess, self.guess)
self.robot.poner_bolitas(self.guess, self.previousGuess)
self.robot.mover_robot([0, 0, -24])
######################################### Guardamos la ultima combinacion y la matriz de huecos
ultimoCodigo = open('ultimoCodigo', 'w')
s=''
for listaHuecosColor in self.robot.listaHuecosColores:
for listaHuecoColor in listaHuecosColor:
s+='{0},'.format(listaHuecoColor[3])
for listaHuecoRobot in self.robot.listaHuecosRobot:
s+='{0},'.format(listaHuecoRobot[3])
ultimoCodigo.write('{0}|{1}|{2}|{3}|{4}|{5}'.format(self.guess[0],self.guess[1],self.guess[2],self.guess[3],self.guess[4],s[:-1]))
ultimoCodigo.close()
except:
self.ids.textprueba.text = "Te has equivocado. Cambia tu respuesta y vuelve a intentarlo. Si persiste, reinicia."
self.ids.jugar_p_directo.text = 'Reiniciar (pulsadores)'
self.ids.empezar_i_directo.text='Reiniciar (interfaz)'
self.ids.continuar_i_directo.text ='Reintentar (interfaz)'
self.pool = copy.copy(self.previousPool)
def jugar_p_inverso(self):
"""
Empieza el juego inverso con un primer movimiento
Requiere la respuesta del usuario por pulsadores
Dentro del while:
Continua un turno del juego, requiere la respuesta del usuario por pulsadores
"""
self.linea2 = 0
self.inv.empezar()
self.linea2+=1
"""
arduino.write('3')
Clock.schedule_interval(self.respuesta_i_arduino, 1)# respuesta del arduino
guess2 = self.respuesta_i_arduino
print guess2
"""
######################################### respuesta del arduino
print 'hola'
self.pulsadores = Arduino()
guess2 = self.pulsadores.codigo5()
print guess2
rojas2, blancas2 = self.inv.continuar(guess2)
print rojas2, blancas2
self.nuevas = [None, None, None, None, None]
for i in range(rojas2):
self.nuevas[i]=4
for i in range(blancas2):
self.nuevas[i+rojas2]=3
self.viejas = [None, None, None, None, None]
huecoX = '2hueco'+str(self.linea2)
for y in range(5):
huecoXY=huecoX+str(y)
print guess2[y]
self.ids[huecoXY].background_color = self.colorsrgba[guess2[y]]
Clock.schedule_once(self.esperar, 1)
#checkbox = self.ids.checkbox
#checkbox.bind(active=self.on_checkbox_active)
try:
######################################## cargamos la ultima configuracion
ultimoCodigo = open('ultimoCodigo', 'r')
ultimo = ultimoCodigo.readline().split('|')
codigo = [int(i) for i in ultimo[:-1]]
huecos = ultimo[5].split(',')
huecos.reverse()
matrizOcupados = [int(i) for i in huecos]
for i in range(5):
for e in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosColores[i][e][3]=p
for i in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosRobot[i][3]=p<|fim▁hole|> self.robot.poner_bolitas(self.nuevas, codigo)
self.robot.mover_robot([0, 0, -24])
except:
print 'No hay archivo ultimoCodigo = No hay bolitas puestas'
#########################################aqui ha de venir el movimiento de bolitas!!!!
ultimo = [None, None, None, None, None]
self.robot.poner_bolitas(self.nuevas, ultimo)
self.robot.mover_robot([0, 0, -24])
self.ids['2textrojo'+str(self.linea2)].text = str(rojas2)
self.ids['2textblanco'+str(self.linea2)].text = str(blancas2)
if rojas2 == 5:
self.ids.textprueba2.text = "Has ganado! (jo) (jo)"
self.ids.jugar_p_inverso.text='Reiniciar (pulsadores)'
self.ids.empezar_i_inverso.text='Reiniciar (interfaz)'
self.robot.perder()
return None
"""
continuar = Clock.create_trigger(self.continuar_p_inverso)
continuar() #2 intento
continuar() #3 intento
continuar() #4 intento
continuar() #5 intento
continuar() #6 intento
continuar() #7 intento
"""
"""
while True:
self.continuar_p_inverso()
"""
def continuar_p_inverso(self):
if self.linea2>7:
self.robot.celebrar()
return None
self.linea2+=1
"""
arduino.write('3')
Clock.schedule_interval(self.respuesta_i_arduino, 1)# respuesta del arduino
guess2 = self.respuesta_i_arduino
print guess2
"""
######################################### respuesta del arduino
print 'hola'
self.pulsadores = Arduino()
guess2 = self.pulsadores.codigo5()
print guess2
rojas2, blancas2 = self.inv.continuar(guess2)
print rojas2, blancas2
self.viejas = copy.copy(self.nuevas)
self.nuevas = [None, None, None, None, None]
for i in range(rojas2):
self.nuevas[i]=4
for i in range(blancas2):
self.nuevas[i+rojas2]=3
huecoX = '2hueco'+str(self.linea2)
for y in range(5):
huecoXY=huecoX+str(y)
print guess2[y]
self.ids[huecoXY].background_color = self.colorsrgba[guess2[y]]
Clock.schedule_once(self.esperar, 1)
#########################################aqui ha de venir el movimiento de bolitas!!!!
print self.viejas
print self.nuevas
self.robot.quitar_bolitas(self.viejas, self.nuevas)
self.robot.poner_bolitas(self.nuevas, self.viejas)
self.robot.mover_robot([0, 0, -24])
######################################### Guardamos la ultima combinacion y la matriz de huecos
ultimoCodigo = open('ultimoCodigo', 'w')
s=''
for listaHuecosColor in self.robot.listaHuecosColores:
for listaHuecoColor in listaHuecosColor:
s+='{0},'.format(listaHuecoColor[3])
for listaHuecoRobot in self.robot.listaHuecosRobot:
s+='{0},'.format(listaHuecoRobot[3])
ultimoCodigo.write('{0}|{1}|{2}|{3}|{4}|{5}'.format(self.nuevas[0],self.nuevas[1],self.nuevas[2],self.nuevas[3],self.nuevas[4],s[:-1]))
ultimoCodigo.close()
self.ids['2textrojo'+str(self.linea2)].text = str(rojas2)
self.ids['2textblanco'+str(self.linea2)].text = str(blancas2)
if rojas2 == 5:
self.ids.textprueba2.text = "Has ganado! (jo) (jo)"
self.ids.jugar_p_inverso.text='Reiniciar (pulsadores)'
self.ids.empezar_i_inverso.text='Reiniciar (interfaz)'
self.robot.perder()
return None
def empezar_i_inverso(self):
"""
Empieza el juego inverso con un primer movimiento
Requiere la respuesta del usuario por por texto de interfaz
"""
self.linea2 = 0
self.inv.empezar()
self.linea2+=1
guess2 = self.ids.codigo.text
guess2 = guess2.split()
guess2 = [int(i) for i in guess2]
print guess2
rojas2, blancas2 = self.inv.continuar(guess2)
print rojas2, blancas2
self.nuevas = [None, None, None, None, None]
for i in range(rojas2):
self.nuevas[i]=4
for i in range(blancas2):
self.nuevas[i+rojas2]=3
self.viejas = [None, None, None, None, None]
huecoX = '2hueco'+str(self.linea2)
for y in range(5):
huecoXY=huecoX+str(y)
print guess2[y]
self.ids[huecoXY].background_color = self.colorsrgba[guess2[y]]
Clock.schedule_once(self.esperar, 1)
#checkbox = self.ids.checkbox
#checkbox.bind(active=self.on_checkbox_active)
try:
######################################## cargamos la ultima configuracion
ultimoCodigo = open('ultimoCodigo', 'r')
ultimo = ultimoCodigo.readline().split('|')
codigo = [int(i) for i in ultimo[:-1]]
huecos = ultimo[5].split(',')
huecos.reverse()
matrizOcupados = [int(i) for i in huecos]
for i in range(5):
for e in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosColores[i][e][3]=p
for i in range(5):
p=matrizOcupados.pop()
self.robot.listaHuecosRobot[i][3]=p
ultimoCodigo.close()
#########################################aqui ha de venir el movimiento de bolitas!!!!
self.robot.quitar_bolitas(codigo, self.nuevas)
self.robot.poner_bolitas(self.nuevas, codigo)
self.robot.mover_robot([0, 0, -24])
except:
print 'No hay archivo ultimoCodigo = No hay bolitas puestas'
#########################################aqui ha de venir el movimiento de bolitas!!!!
ultimo = [None, None, None, None, None]
self.robot.poner_bolitas(self.nuevas, ultimo)
self.robot.mover_robot([0, 0, -24])
self.ids['2textrojo'+str(self.linea2)].text = str(rojas2)
self.ids['2textblanco'+str(self.linea2)].text = str(blancas2)
if rojas2 == 5:
self.ids.textprueba2.text = "Has ganado! (jo) (jo)"
self.ids.jugar_p_inverso.text='Reiniciar (pulsadores)'
self.ids.empezar_i_inverso.text='Reiniciar (interfaz)'
self.robot.perder()
return None
def continuar_i_inverso(self):
"""
Continua un turno del juego, requiere la respuesta del usuario por texto de interfaz
"""
if self.linea2>7:
self.robot.celebrar()
return None
self.linea2+=1
guess2 = self.ids.codigo.text
guess2 = guess2.split()
guess2 = [int(i) for i in guess2]
print guess2
rojas2, blancas2 = self.inv.continuar(guess2)
print rojas2, blancas2
self.viejas = copy.copy(self.nuevas)
self.nuevas = [None, None, None, None, None]
for i in range(rojas2):
self.nuevas[i]=4
for i in range(blancas2):
self.nuevas[i+rojas2]=3
huecoX = '2hueco'+str(self.linea2)
for y in range(5):
huecoXY=huecoX+str(y)
print guess2[y]
self.ids[huecoXY].background_color = self.colorsrgba[guess2[y]]
Clock.schedule_once(self.esperar, 1)
#########################################aqui ha de venir el movimiento de bolitas!!!!
print self.viejas
print self.nuevas
self.robot.quitar_bolitas(self.viejas, self.nuevas)
self.robot.poner_bolitas(self.nuevas, self.viejas)
self.robot.mover_robot([0, 0, -24])
######################################### Guardamos la ultima combinacion y la matriz de huecos
ultimoCodigo = open('ultimoCodigo', 'w')
s=''
for listaHuecosColor in self.robot.listaHuecosColores:
for listaHuecoColor in listaHuecosColor:
s+='{0},'.format(listaHuecoColor[3])
for listaHuecoRobot in self.robot.listaHuecosRobot:
s+='{0},'.format(listaHuecoRobot[3])
ultimoCodigo.write('{0}|{1}|{2}|{3}|{4}|{5}'.format(self.nuevas[0],self.nuevas[1],self.nuevas[2],self.nuevas[3],self.nuevas[4],s[:-1]))
ultimoCodigo.close()
self.ids['2textrojo'+str(self.linea2)].text = str(rojas2)
self.ids['2textblanco'+str(self.linea2)].text = str(blancas2)
if rojas2 == 5:
self.ids.textprueba2.text = "Has ganado! (jo) (jo)"
self.ids.jugar_p_inverso.text='Reiniciar (pulsadores)'
self.ids.empezar_i_inverso.text='Reiniciar (interfaz)'
self.robot.perder()
return None
def respuesta_d_arduino(self, dt):
self.respuesta += arduino.read()
print respuesta
if len(respuesta)==4:
respuesta=[int(i) for i in self.respuesta.split('|')]
self.respuesta_d = respuesta
return False
def respuesta_i_arduino(self, dt):
respuesta = arduino.readline()
if len(respuesta)==11:
respuesta=[int(i) for i in respuesta[1:-1].split('|')]
self.respuesta_i = respuesta
return False
def esperar(self, dt):
return None
def on_checkbox_active(checkbox, value):
if value:
return True
else:
return False
class DeltaApp(App):
def build(self):
juego = Delta()
return juego
if __name__ == '__main__':
try:
arduino = arduinoSerial.Serial('/dev/ttyACM0', 115200)
except:
print "No se encuentra Arduino"
exit()
DeltaApp().run()
arduino.close()<|fim▁end|>
|
ultimoCodigo.close()
#########################################aqui ha de venir el movimiento de bolitas!!!!
self.robot.quitar_bolitas(codigo, self.nuevas)
|
<|file_name|>string.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! An owned, growable string that enforces that its contents are valid UTF-8.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::fmt;
use core::hash;
use core::iter::FromIterator;
use core::mem;
use core::ops::{self, Deref, Add, Index};
use core::ptr;
use core::slice;
use core::str::pattern::Pattern;
use rustc_unicode::str as unicode_str;
use rustc_unicode::str::Utf16Item;
use borrow::{Cow, IntoCow};
use range::RangeArgument;
use str::{self, FromStr, Utf8Error, Chars};
use vec::{DerefVec, Vec, as_vec};
/// A growable string stored as a UTF-8 encoded buffer.
#[derive(Clone, PartialOrd, Eq, Ord)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct String {
vec: Vec<u8>,
}
/// A possible error value from the `String::from_utf8` function.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct FromUtf8Error {
bytes: Vec<u8>,
error: Utf8Error,
}
/// A possible error value from the `String::from_utf16` function.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct FromUtf16Error(());
impl String {
/// Creates a new string buffer initialized with the empty string.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> String {
String {
vec: Vec::new(),
}
}
/// Creates a new string buffer with the given capacity.
/// The string will be able to hold exactly `capacity` bytes without
/// reallocating. If `capacity` is 0, the string will not allocate.
///
/// # Examples
///
/// ```
/// let mut s = String::with_capacity(10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(capacity: usize) -> String {
String {
vec: Vec::with_capacity(capacity),
}
}
/// Creates a new string buffer from the given string.
///
/// # Examples
///
/// ```
/// # #![feature(collections, core)]
/// let s = String::from_str("hello");
/// assert_eq!(&s[..], "hello");
/// ```
#[inline]
#[unstable(feature = "collections",
reason = "needs investigation to see if to_string() can match perf")]
#[cfg(not(test))]
pub fn from_str(string: &str) -> String {
String { vec: <[_]>::to_vec(string.as_bytes()) }
}
// HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
// required for this method definition, is not available. Since we don't
// require this method for testing purposes, I'll just stub it
// NB see the slice::hack module in slice.rs for more information
#[inline]
#[cfg(test)]
pub fn from_str(_: &str) -> String {
panic!("not available with cfg(test)");
}
/// Returns the vector as a string buffer, if possible, taking care not to
/// copy it.
///
/// # Failure
///
/// If the given vector is not valid UTF-8, then the original vector and the
/// corresponding error is returned.
///
/// # Examples
///
/// ```
/// let hello_vec = vec![104, 101, 108, 108, 111];
/// let s = String::from_utf8(hello_vec).unwrap();
/// assert_eq!(s, "hello");
///
/// let invalid_vec = vec![240, 144, 128];
/// let s = String::from_utf8(invalid_vec).err().unwrap();
/// let err = s.utf8_error();
/// assert_eq!(s.into_bytes(), [240, 144, 128]);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
match str::from_utf8(&vec) {
Ok(..) => Ok(String { vec: vec }),
Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
}
}
/// Converts a vector of bytes to a new UTF-8 string.
/// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
///
/// # Examples
///
/// ```
/// let input = b"Hello \xF0\x90\x80World";
/// let output = String::from_utf8_lossy(input);
/// assert_eq!(output, "Hello \u{FFFD}World");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
let mut i;
match str::from_utf8(v) {
Ok(s) => return Cow::Borrowed(s),
Err(e) => i = e.valid_up_to(),
}
const TAG_CONT_U8: u8 = 128;
const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
let total = v.len();
fn unsafe_get(xs: &[u8], i: usize) -> u8 {
unsafe { *xs.get_unchecked(i) }
}
fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
if i >= total {
0
} else {
unsafe_get(xs, i)
}
}
let mut res = String::with_capacity(total);
if i > 0 {
unsafe {
res.as_mut_vec().push_all(&v[..i])
};
}
// subseqidx is the index of the first byte of the subsequence we're
// looking at. It's used to copy a bunch of contiguous good codepoints
// at once instead of copying them one by one.
let mut subseqidx = i;
while i < total {
let i_ = i;
let byte = unsafe_get(v, i);
i += 1;
macro_rules! error { () => ({
unsafe {
if subseqidx != i_ {
res.as_mut_vec().push_all(&v[subseqidx..i_]);
}
subseqidx = i;
res.as_mut_vec().push_all(REPLACEMENT);
}
})}
if byte < 128 {
// subseqidx handles this
} else {
let w = unicode_str::utf8_char_width(byte);
match w {
2 => {
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
3 => {
match (byte, safe_get(v, i, total)) {
(0xE0 , 0xA0 ... 0xBF) => (),
(0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
(0xED , 0x80 ... 0x9F) => (),
(0xEE ... 0xEF, 0x80 ... 0xBF) => (),
_ => {
error!();
continue;
}
}
i += 1;
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
4 => {
match (byte, safe_get(v, i, total)) {
(0xF0 , 0x90 ... 0xBF) => (),
(0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
(0xF4 , 0x80 ... 0x8F) => (),
_ => {
error!();
continue;
}
}
i += 1;
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
_ => {
error!();
continue;
}
}
}
}
if subseqidx < total {
unsafe {
res.as_mut_vec().push_all(&v[subseqidx..total])
};
}
Cow::Owned(res)
}
/// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
/// if `v` contains any invalid data.
///
/// # Examples
///
/// ```
/// // 𝄞music
/// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0x0069, 0x0063];
/// assert_eq!(String::from_utf16(v).unwrap(),
/// "𝄞music".to_string());
///
/// // 𝄞mu<invalid>ic
/// v[4] = 0xD800;
/// assert!(String::from_utf16(v).is_err());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
let mut s = String::with_capacity(v.len());
for c in unicode_str::utf16_items(v) {
match c {
Utf16Item::ScalarValue(c) => s.push(c),
Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
}
}
Ok(s)
}
/// Decode a UTF-16 encoded vector `v` into a string, replacing
/// invalid data with the replacement character (U+FFFD).
///
/// # Examples
///
/// ```
/// // 𝄞mus<invalid>ic<invalid>
/// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
/// assert_eq!(String::from_utf16_lossy(v),
/// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf16_lossy(v: &[u16]) -> String {
unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
}
/// Creates a new `String` from a length, capacity, and pointer.
///
/// This is unsafe because:
///
/// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
/// * We assume that the `Vec` contains valid UTF-8.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
String {
vec: Vec::from_raw_parts(buf, length, capacity),
}
}
/// Converts a vector of bytes to a new `String` without checking if
/// it contains valid UTF-8. This is unsafe because it assumes that
/// the UTF-8-ness of the vector has already been validated.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
String { vec: bytes }
}
/// Returns the underlying byte buffer, encoded as UTF-8.
///
/// # Examples
///
/// ```
/// let s = String::from("hello");
/// let bytes = s.into_bytes();
/// assert_eq!(bytes, [104, 101, 108, 108, 111]);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_bytes(self) -> Vec<u8> {
self.vec
}
/// Extracts a string slice containing the entire string.
#[inline]
#[unstable(feature = "convert",
reason = "waiting on RFC revision")]
pub fn as_str(&self) -> &str {
self
}
/// Pushes the given string onto this string buffer.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// s.push_str("bar");
/// assert_eq!(s, "foobar");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push_str(&mut self, string: &str) {
self.vec.push_all(string.as_bytes())
}
/// Returns the number of bytes that this string buffer can hold without
/// reallocating.
///
/// # Examples
///
/// ```
/// let s = String::with_capacity(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn capacity(&self) -> usize {
self.vec.capacity()
}
/// Reserves capacity for at least `additional` more bytes to be inserted
/// in the given `String`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// s.reserve(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve(&mut self, additional: usize) {
self.vec.reserve(additional)
}
/// Reserves the minimum capacity for exactly `additional` more bytes to be
/// inserted in the given `String`. Does nothing if the capacity is already
/// sufficient.
///
/// Note that the allocator may give the collection more space than it
/// requests. Therefore capacity can not be relied upon to be precisely
/// minimal. Prefer `reserve` if future insertions are expected.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// s.reserve_exact(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve_exact(&mut self, additional: usize) {
self.vec.reserve_exact(additional)
}
/// Shrinks the capacity of this string buffer to match its length.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// s.reserve(100);
/// assert!(s.capacity() >= 100);
/// s.shrink_to_fit();
/// assert_eq!(s.capacity(), 3);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn shrink_to_fit(&mut self) {
self.vec.shrink_to_fit()
}
/// Adds the given character to the end of the string.
///
/// # Examples
///
/// ```
/// let mut s = String::from("abc");
/// s.push('1');
/// s.push('2');
/// s.push('3');
/// assert_eq!(s, "abc123");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push(&mut self, ch: char) {
if (ch as u32) < 0x80 {
self.vec.push(ch as u8);
return;
}
let cur_len = self.len();
// This may use up to 4 bytes.
self.vec.reserve(4);
unsafe {
// Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string.
let slice = slice::from_raw_parts_mut (
self.vec.as_mut_ptr().offset(cur_len as isize),
4
);
let used = ch.encode_utf8(slice).unwrap_or(0);
self.vec.set_len(cur_len + used);
}
}
/// Works with the underlying buffer as a byte slice.
///
/// # Examples
///
/// ```
/// let s = String::from("hello");
/// let b: &[_] = &[104, 101, 108, 108, 111];
/// assert_eq!(s.as_bytes(), b);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_bytes(&self) -> &[u8] {
&self.vec
}
/// Shortens a string to the specified length.
///
/// # Panics
///
/// Panics if `new_len` > current length,
/// or if `new_len` is not a character boundary.
///
/// # Examples
///
/// ```
/// let mut s = String::from("hello");
/// s.truncate(2);
/// assert_eq!(s, "he");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn truncate(&mut self, new_len: usize) {
assert!(self.is_char_boundary(new_len));
self.vec.truncate(new_len)
}
/// Removes the last character from the string buffer and returns it.
/// Returns `None` if this string buffer is empty.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('f'));
/// assert_eq!(s.pop(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> Option<char> {
let len = self.len();
if len == 0 {
return None
}
let ch = self.char_at_reverse(len);
unsafe {
self.vec.set_len(len - ch.len_utf8());
}
Some(ch)
}
/// Removes the character from the string buffer at byte position `idx` and
/// returns it.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// buffer.
///
/// # Panics
///
/// If `idx` does not lie on a character boundary, or if it is out of
/// bounds, then this function will panic.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// assert_eq!(s.remove(0), 'f');
/// assert_eq!(s.remove(1), 'o');
/// assert_eq!(s.remove(0), 'o');
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove(&mut self, idx: usize) -> char {
let len = self.len();
assert!(idx <= len);
let ch = self.char_at(idx);
let next = idx + ch.len_utf8();
unsafe {
ptr::copy(self.vec.as_ptr().offset(next as isize),
self.vec.as_mut_ptr().offset(idx as isize),
len - next);
self.vec.set_len(len - (next - idx));
}
ch
}
/// Inserts a character into the string buffer at byte position `idx`.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// buffer.
///
/// # Panics
///
/// If `idx` does not lie on a character boundary or is out of bounds, then
/// this function will panic.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(&mut self, idx: usize, ch: char) {
let len = self.len();
assert!(idx <= len);
assert!(self.is_char_boundary(idx));
self.vec.reserve(4);
let mut bits = [0; 4];
let amt = ch.encode_utf8(&mut bits).unwrap();
unsafe {
ptr::copy(self.vec.as_ptr().offset(idx as isize),
self.vec.as_mut_ptr().offset((idx + amt) as isize),
len - idx);
ptr::copy(bits.as_ptr(),
self.vec.as_mut_ptr().offset(idx as isize),
amt);
self.vec.set_len(len + amt);
}
}
/// Views the string buffer as a mutable sequence of bytes.
///
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Examples
///
/// ```
/// let mut s = String::from("hello");
/// unsafe {
/// let vec = s.as_mut_vec();
/// assert!(vec == &[104, 101, 108, 108, 111]);
/// vec.reverse();
/// }
/// assert_eq!(s, "olleh");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
&mut self.vec
}
/// Returns the number of bytes in this string.
///
/// # Examples
///
/// ```
/// let a = "foo".to_string();
/// assert_eq!(a.len(), 3);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn len(&self) -> usize { self.vec.len() }
/// Returns true if the string contains no bytes
///
/// # Examples
///
/// ```
/// let mut v = String::new();
/// assert!(v.is_empty());
/// v.push('a');
/// assert!(!v.is_empty());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Truncates the string, returning it to 0 length.
///
/// # Examples
///
/// ```
/// let mut s = "foo".to_string();
/// s.clear();
/// assert!(s.is_empty());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn clear(&mut self) {
self.vec.clear()
}
/// Create a draining iterator that removes the specified range in the string
/// and yields the removed chars from start to end. The element range is
/// removed even if the iterator is not consumed until the end.
///
/// # Panics
///
/// Panics if the starting point or end point are not on character boundaries,
/// or if they are out of bounds.
///
/// # Examples
///
/// ```
/// # #![feature(collections_drain)]
///
/// let mut s = String::from("α is alpha, β is beta");
/// let beta_offset = s.find('β').unwrap_or(s.len());
///
/// // Remove the range up until the β from the string
/// let t: String = s.drain(..beta_offset).collect();
/// assert_eq!(t, "α is alpha, ");
/// assert_eq!(s, "β is beta");
///
/// // A full range clears the string
/// s.drain(..);
/// assert_eq!(s, "");
/// ```
#[unstable(feature = "collections_drain",
reason = "recently added, matches RFC")]
pub fn drain<R>(&mut self, range: R) -> Drain where R: RangeArgument<usize> {
// Memory safety
//
// The String version of Drain does not have the memory safety issues
// of the vector version. The data is just plain bytes.
// Because the range removal happens in Drop, if the Drain iterator is leaked,
// the removal will not happen.
let len = self.len();
let start = *range.start().unwrap_or(&0);
let end = *range.end().unwrap_or(&len);
// Take out two simultaneous borrows. The &mut String won't be accessed
// until iteration is over, in Drop.
let self_ptr = self as *mut _;
// slicing does the appropriate bounds checks
let chars_iter = self[start..end].chars();
Drain {
start: start,
end: end,
iter: chars_iter,
string: self_ptr,
}
}
}
impl FromUtf8Error {
/// Consumes this error, returning the bytes that were attempted to make a
/// `String` with.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_bytes(self) -> Vec<u8> { self.bytes }
/// Access the underlying UTF8-error that was the cause of this error.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn utf8_error(&self) -> Utf8Error { self.error }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for FromUtf8Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for FromUtf16Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl FromIterator<char> for String {
fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
let mut buf = String::new();
buf.extend(iter);
buf
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> FromIterator<&'a str> for String {
fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
let mut buf = String::new();
buf.extend(iter);
buf
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Extend<char> for String {
fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
let iterator = iterable.into_iter();
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for ch in iterator {
self.push(ch)
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Extend<&'a str> for String {
fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
let iterator = iterable.into_iter();
// A guess that at least one byte per iterator element will be needed.
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for s in iterator {
self.push_str(s)
}
}
}
/// A convenience impl that delegates to the impl for `&str`
impl<'a, 'b> Pattern<'a> for &'b String {
type Searcher = <&'b str as Pattern<'a>>::Searcher;
fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
self[..].into_searcher(haystack)
}
#[inline]
fn is_contained_in(self, haystack: &'a str) -> bool {
self[..].is_contained_in(haystack)
}
#[inline]
fn is_prefix_of(self, haystack: &'a str) -> bool {
self[..].is_prefix_of(haystack)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for String {
#[inline]
fn eq(&self, other: &String) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &String) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
macro_rules! impl_eq {
($lhs:ty, $rhs: ty) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
}
}
impl_eq! { String, str }
impl_eq! { String, &'a str }
impl_eq! { Cow<'a, str>, str }
impl_eq! { Cow<'a, str>, String }
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
#[inline]
fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
#[inline]
fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Default for String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> String {
String::new()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for String {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for String {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for String {
#[inline]
fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
(**self).hash(hasher)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Add<&'a str> for String {
type Output = String;
#[inline]
fn add(mut self, other: &str) -> String {
self.push_str(other);
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::Range<usize>> for String {
type Output = str;
#[inline]
fn index(&self, index: ops::Range<usize>) -> &str {
&self[..][index]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeTo<usize>> for String {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeTo<usize>) -> &str {
&self[..][index]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFrom<usize>> for String {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeFrom<usize>) -> &str {
&self[..][index]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for String {
type Output = str;
#[inline]
fn index(&self, _index: ops::RangeFull) -> &str {
unsafe { mem::transmute(&*self.vec) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for String {
type Target = str;
#[inline]
fn deref(&self) -> &str {
unsafe { mem::transmute(&self.vec[..]) }
}
}
/// Wrapper type providing a `&String` reference via `Deref`.
#[unstable(feature = "collections")]
pub struct DerefString<'a> {
x: DerefVec<'a, u8>
}
impl<'a> Deref for DerefString<'a> {
type Target = String;
#[inline]
fn deref<'b>(&'b self) -> &'b String {
unsafe { mem::transmute(&*self.x) }
}
}
/// Converts a string slice to a wrapper type providing a `&String` reference.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::string::as_string;
///
/// // Let's pretend we have a function that requires `&String`
/// fn string_consumer(s: &String) {
/// assert_eq!(s, "foo");
/// }
///
/// // Provide a `&String` from a `&str` without allocating
/// string_consumer(&as_string("foo"));
/// ```
#[unstable(feature = "collections")]
pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
DerefString { x: as_vec(x.as_bytes()) }
}
/// Error returned from `String::from_str`
#[unstable(feature = "str_parse_error", reason = "may want to be replaced with \
Void if it ever exists")]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ParseError(());
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for String {
type Err = ParseError;
#[inline]
fn from_str(s: &str) -> Result<String, ParseError> {
Ok(String::from_str(s))
}
}
/// A generic trait for converting a value to a string<|fim▁hole|> /// Converts the value of `self` to an owned string
#[stable(feature = "rust1", since = "1.0.0")]
fn to_string(&self) -> String;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> ToString for T {
#[inline]
fn to_string(&self) -> String {
use core::fmt::Write;
let mut buf = String::new();
let _ = buf.write_fmt(format_args!("{}", self));
buf.shrink_to_fit();
buf
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for String {
#[inline]
fn as_ref(&self) -> &str {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<[u8]> for String {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<&'a str> for String {
#[cfg(not(test))]
#[inline]
fn from(s: &'a str) -> String {
String { vec: <[_]>::to_vec(s.as_bytes()) }
}
// HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
// required for this method definition, is not available. Since we don't
// require this method for testing purposes, I'll just stub it
// NB see the slice::hack module in slice.rs for more information
#[inline]
#[cfg(test)]
fn from(_: &str) -> String {
panic!("not available with cfg(test)");
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<&'a str> for Cow<'a, str> {
#[inline]
fn from(s: &'a str) -> Cow<'a, str> {
Cow::Borrowed(s)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<String> for Cow<'a, str> {
#[inline]
fn from(s: String) -> Cow<'a, str> {
Cow::Owned(s)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Into<Vec<u8>> for String {
fn into(self) -> Vec<u8> {
self.into_bytes()
}
}
#[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
impl IntoCow<'static, str> for String {
#[inline]
fn into_cow(self) -> Cow<'static, str> {
Cow::Owned(self)
}
}
#[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
impl<'a> IntoCow<'a, str> for &'a str {
#[inline]
fn into_cow(self) -> Cow<'a, str> {
Cow::Borrowed(self)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Write for String {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
self.push_str(s);
Ok(())
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.push(c);
Ok(())
}
}
/// A draining iterator for `String`.
#[unstable(feature = "collections_drain", reason = "recently added")]
pub struct Drain<'a> {
/// Will be used as &'a mut String in the destructor
string: *mut String,
/// Start of part to remove
start: usize,
/// End of part to remove
end: usize,
/// Current remaining range to remove
iter: Chars<'a>,
}
unsafe impl<'a> Sync for Drain<'a> {}
unsafe impl<'a> Send for Drain<'a> {}
#[unstable(feature = "collections_drain", reason = "recently added")]
impl<'a> Drop for Drain<'a> {
fn drop(&mut self) {
unsafe {
// Use Vec::drain. "Reaffirm" the bounds checks to avoid
// panic code being inserted again.
let self_vec = (*self.string).as_mut_vec();
if self.start <= self.end && self.end <= self_vec.len() {
self_vec.drain(self.start..self.end);
}
}
}
}
#[unstable(feature = "collections_drain", reason = "recently added")]
impl<'a> Iterator for Drain<'a> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<char> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
#[unstable(feature = "collections_drain", reason = "recently added")]
impl<'a> DoubleEndedIterator for Drain<'a> {
#[inline]
fn next_back(&mut self) -> Option<char> {
self.iter.next_back()
}
}<|fim▁end|>
|
#[stable(feature = "rust1", since = "1.0.0")]
pub trait ToString {
|
<|file_name|>MonolithApplication.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2017 the original author or authors.
*
* 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.
*/
package example.sos.monolith;
import example.sos.monolith.catalog.Catalog;
import example.sos.monolith.catalog.Product;
import example.sos.monolith.inventory.Inventory;
import example.sos.monolith.orders.OrderManager;
<|fim▁hole|>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* @author Oliver Gierke
*/
@SpringBootApplication
public class MonolithApplication {
public static void main(String... args) {
SpringApplication.run(MonolithApplication.class, args);
}
@Bean
CommandLineRunner onStartup(Catalog catalog, Inventory inventory, OrderManager orders) {
return args -> {
Product iPad = catalog.save(new Product("iPad", new BigDecimal(699.99)));
Product iPhone = catalog.save(new Product("iPhone", new BigDecimal(899.99)));
inventory.addItemFor(iPad, 10);
inventory.addItemFor(iPhone, 15);
};
}
}<|fim▁end|>
|
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;
|
<|file_name|>EffectChams.cpp<|end_file_name|><|fim▁begin|>/*
* EffectChams.cpp
*
* Created on: Apr 16, 2017
* Author: nullifiedcat
*/
#include <visual/EffectChams.hpp>
#include <MiscTemporary.hpp>
#include <settings/Bool.hpp>
#include "common.hpp"
#include "Backtrack.hpp"
namespace effect_chams
{
static settings::Boolean flat{ "chams.flat", "false" };
static settings::Boolean health{ "chams.health", "false" };
static settings::Boolean teammates{ "chams.show.teammates", "false" };
static settings::Boolean disguised{ "chams.show.disguised", "true" };
static settings::Boolean players{ "chams.show.players", "true" };
static settings::Boolean medkits{ "chams.show.medkits", "false" };
static settings::Boolean ammobox{ "chams.show.ammoboxes", "false" };
static settings::Boolean buildings{ "chams.show.buildings", "true" };
static settings::Boolean stickies{ "chams.show.stickies", "true" };
static settings::Boolean teammate_buildings{ "chams.show.teammate-buildings", "false" };
static settings::Boolean recursive{ "chams.recursive", "true" };
static settings::Boolean weapons_white{ "chams.white-weapons", "true" };
static settings::Boolean legit{ "chams.legit", "false" };
static settings::Boolean singlepass{ "chams.single-pass", "false" };
static settings::Boolean chamsself{ "chams.self", "true" };
static settings::Boolean disco_chams{ "chams.disco", "false" };
settings::Boolean enable{ "chams.enable", "false" };
CatCommand fix_black_chams("fix_black_chams", "Fix Black Chams", []() {
effect_chams::g_EffectChams.Shutdown();
effect_chams::g_EffectChams.Init();
});
void EffectChams::Init()
{
#if !ENFORCE_STREAM_SAFETY
if (init)
return;
logging::Info("Init EffectChams...");
{
KeyValues *kv = new KeyValues("UnlitGeneric");
kv->SetString("$basetexture", "vgui/white_additive");
kv->SetInt("$ignorez", 0);
mat_unlit.Init("__cathook_echams_unlit", kv);
}
{
KeyValues *kv = new KeyValues("UnlitGeneric");
kv->SetString("$basetexture", "vgui/white_additive");
kv->SetInt("$ignorez", 1);
mat_unlit_z.Init("__cathook_echams_unlit_z", kv);
}
{
KeyValues *kv = new KeyValues("VertexLitGeneric");
kv->SetString("$basetexture", "vgui/white_additive");
kv->SetInt("$ignorez", 0);
kv->SetInt("$halflambert", 1);
mat_lit.Init("__cathook_echams_lit", kv);
}
{
KeyValues *kv = new KeyValues("VertexLitGeneric");
kv->SetString("$basetexture", "vgui/white_additive");
kv->SetInt("$ignorez", 1);
kv->SetInt("$halflambert", 1);
mat_lit_z.Init("__cathook_echams_lit_z", kv);
}
logging::Info("Init done!");
init = true;
#endif
}
void EffectChams::BeginRenderChams()
{
#if !ENFORCE_STREAM_SAFETY
drawing = true;
CMatRenderContextPtr ptr(GET_RENDER_CONTEXT);
g_IVRenderView->SetBlend(1.0f);
#endif
}
void EffectChams::EndRenderChams()
{
#if !ENFORCE_STREAM_SAFETY
drawing = false;
CMatRenderContextPtr ptr(GET_RENDER_CONTEXT);
g_IVModelRender->ForcedMaterialOverride(nullptr);
#endif
}
static rgba_t data[PLAYER_ARRAY_SIZE] = { colors::empty };
void EffectChams::SetEntityColor(CachedEntity *ent, rgba_t color)
{
if (ent->m_IDX > MAX_PLAYERS || ent->m_IDX < 0)
return;
data[ent->m_IDX] = color;
}
static Timer t{};
static int prevcolor = -1;
rgba_t EffectChams::ChamsColor(IClientEntity *entity)
{
if (!isHackActive() || !*effect_chams::enable)
return colors::empty;
CachedEntity *ent = ENTITY(entity->entindex());
if (disco_chams)
{
static rgba_t disco{ 0, 0, 0, 0 };
if (t.test_and_set(200))
{
int color = rand() % 20;
while (color == prevcolor)
color = rand() % 20;
prevcolor = color;
switch (color)
{
case 2:
disco = colors::pink;
break;
case 3:
disco = colors::red;
break;
case 4:
disco = colors::blu;
break;
case 5:
disco = colors::red_b;
break;
case 6:
disco = colors::blu_b;
break;
case 7:
disco = colors::red_v;
break;
case 8:
disco = colors::blu_v;
break;
case 9:
disco = colors::red_u;
break;
case 10:
disco = colors::blu_u;
break;
case 0:
case 1:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
float color1 = rand() % 256;
float color2 = rand() % 256;
float color3 = rand() % 256;
disco = { color1, color2, color3, 255.0f };
}
}
return disco;
}
if (ent->m_IDX <= MAX_PLAYERS && ent->m_IDX >= 0)
{
if (data[entity->entindex()] != colors::empty)
{
auto toret = data[entity->entindex()];
data[entity->entindex()] = colors::empty;
return toret;
}
}
if (CE_BAD(ent))
return colors::white;
if (re::C_BaseCombatWeapon::IsBaseCombatWeapon(entity))
{
IClientEntity *owner = re::C_TFWeaponBase::GetOwnerViaInterface(entity);
if (owner)
{
return ChamsColor(owner);
}
}
switch (ent->m_Type())
{
case ENTITY_BUILDING:
if (!ent->m_bEnemy() && !(teammates || teammate_buildings) && ent != LOCAL_E)
{
return colors::empty;
}
if (health)
{
return colors::Health_dimgreen(ent->m_iHealth(), ent->m_iMaxHealth());
}
break;
case ENTITY_PLAYER:
if (!players)
return colors::empty;
if (health)
{
return colors::Health_dimgreen(ent->m_iHealth(), ent->m_iMaxHealth());
}
break;
default:
break;
}
return colors::EntityF(ent);
}
bool EffectChams::ShouldRenderChams(IClientEntity *entity)
{
#if ENFORCE_STREAM_SAFETY
return false;
#endif
if (!isHackActive() || !*effect_chams::enable || CE_BAD(LOCAL_E))
return false;
if (entity->entindex() < 0)
return false;
CachedEntity *ent = ENTITY(entity->entindex());
if (!chamsself && ent->m_IDX == LOCAL_E->m_IDX)
return false;
switch (ent->m_Type())
{
case ENTITY_BUILDING:
if (!buildings)<|fim▁hole|> if (!ent->m_bEnemy() && !(teammate_buildings || teammates))
return false;
if (ent->m_iHealth() == 0 || !ent->m_iHealth())
return false;
if (CE_BYTE(LOCAL_E, netvar.m_bCarryingObject) && ent->m_IDX == HandleToIDX(CE_INT(LOCAL_E, netvar.m_hCarriedObject)))
return false;
return true;
case ENTITY_PLAYER:
if (!players)
return false;
if (!disguised && IsPlayerDisguised(ent))
return false;
if (!teammates && !ent->m_bEnemy() && playerlist::IsDefault(ent))
return false;
if (CE_BYTE(ent, netvar.iLifeState))
return false;
return true;
break;
case ENTITY_PROJECTILE:
if (!ent->m_bEnemy())
return false;
if (stickies && ent->m_iClassID() == CL_CLASS(CTFGrenadePipebombProjectile))
{
return true;
}
break;
case ENTITY_GENERIC:
switch (ent->m_ItemType())
{
case ITEM_HEALTH_LARGE:
case ITEM_HEALTH_MEDIUM:
case ITEM_HEALTH_SMALL:
return *medkits;
case ITEM_AMMO_LARGE:
case ITEM_AMMO_MEDIUM:
case ITEM_AMMO_SMALL:
return *ammobox;
default:
break;
}
break;
default:
break;
}
return false;
}
void EffectChams::RenderChamsRecursive(IClientEntity *entity)
{
#if !ENFORCE_STREAM_SAFETY
if (!isHackActive() || !*effect_chams::enable)
return;
entity->DrawModel(1);
if (!*recursive)
return;
IClientEntity *attach;
int passes = 0;
attach = g_IEntityList->GetClientEntity(*(int *) ((uintptr_t) entity + netvar.m_Collision - 24) & 0xFFF);
while (attach && passes++ < 32)
{
if (attach->ShouldDraw())
{
if (entity->GetClientClass()->m_ClassID == RCC_PLAYER && re::C_BaseCombatWeapon::IsBaseCombatWeapon(attach))
{
if (weapons_white)
{
rgba_t mod_original;
g_IVRenderView->GetColorModulation(mod_original.rgba);
g_IVRenderView->SetColorModulation(colors::white);
attach->DrawModel(1);
g_IVRenderView->SetColorModulation(mod_original.rgba);
}
else
{
attach->DrawModel(1);
}
}
else
attach->DrawModel(1);
}
attach = g_IEntityList->GetClientEntity(*(int *) ((uintptr_t) attach + netvar.m_Collision - 20) & 0xFFF);
}
#endif
}
void EffectChams::RenderChams(IClientEntity *entity)
{
#if !ENFORCE_STREAM_SAFETY
if (!isHackActive() || !*effect_chams::enable)
return;
CMatRenderContextPtr ptr(GET_RENDER_CONTEXT);
if (ShouldRenderChams(entity))
{
rgba_t color = ChamsColor(entity);
rgba_t color_2 = color * 0.6f;
if (!legit)
{
mat_unlit_z->AlphaModulate(1.0f);
ptr->DepthRange(0.0f, 0.01f);
g_IVRenderView->SetColorModulation(color_2);
g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit_z : mat_lit_z);
RenderChamsRecursive(entity);
}
if (legit || !singlepass)
{
mat_unlit->AlphaModulate(1.0f);
g_IVRenderView->SetColorModulation(color);
ptr->DepthRange(0.0f, 1.0f);
g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit : mat_lit);
RenderChamsRecursive(entity);
}
}
#endif
}
void EffectChams::Render(int x, int y, int w, int h)
{
#if !ENFORCE_STREAM_SAFETY
PROF_SECTION(DRAW_chams);
if (!isHackActive() || disable_visuals)
return;
if (!effect_chams::enable && !(hacks::tf2::backtrack::chams && hacks::tf2::backtrack::isBacktrackEnabled))
return;
if (g_Settings.bInvalid)
return;
if (!init && effect_chams::enable)
Init();
if (!isHackActive() || (g_IEngine->IsTakingScreenshot() && clean_screenshots))
return;
if (hacks::tf2::backtrack::chams && hacks::tf2::backtrack::isBacktrackEnabled)
{
CMatRenderContextPtr ptr(GET_RENDER_CONTEXT);
BeginRenderChams();
// Don't mark as normal chams drawing
drawing = false;
for (int i = 1; i <= g_IEngine->GetMaxClients(); i++)
{
CachedEntity *ent = ENTITY(i);
if (CE_BAD(ent) || i == g_IEngine->GetLocalPlayer() || !ent->m_bAlivePlayer() || ent->m_Type() != ENTITY_PLAYER)
continue;
// Entity won't draw in some cases so help the chams a bit
hacks::tf2::backtrack::isDrawing = true;
RAW_ENT(ent)->DrawModel(1);
hacks::tf2::backtrack::isDrawing = false;
}
EndRenderChams();
}
if (!effect_chams::enable)
return;
CMatRenderContextPtr ptr(GET_RENDER_CONTEXT);
BeginRenderChams();
for (int i = 1; i <= HIGHEST_ENTITY; i++)
{
IClientEntity *entity = g_IEntityList->GetClientEntity(i);
if (!entity || entity->IsDormant() || CE_BAD(ENTITY(i)))
continue;
RenderChams(entity);
}
EndRenderChams();
#endif
}
EffectChams g_EffectChams;
CScreenSpaceEffectRegistration *g_pEffectChams = nullptr;
static InitRoutine init([]() {
EC::Register(
EC::LevelShutdown, []() { g_EffectChams.Shutdown(); }, "chams");
if (g_ppScreenSpaceRegistrationHead && g_pScreenSpaceEffects)
{
effect_chams::g_pEffectChams = new CScreenSpaceEffectRegistration("_cathook_chams", &effect_chams::g_EffectChams);
g_pScreenSpaceEffects->EnableScreenSpaceEffect("_cathook_chams");
}
});
} // namespace effect_chams<|fim▁end|>
|
return false;
|
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Pngwriter(CMakePackage):
"""PNGwriter is a very easy to use open source graphics library that uses
PNG as its output format. The interface has been designed to be as simple
and intuitive as possible. It supports plotting and reading pixels in the
RGB (red, green, blue), HSV (hue, saturation, value/brightness) and CMYK<|fim▁hole|> (cyan, magenta, yellow, black) colour spaces, basic shapes, scaling,
bilinear interpolation, full TrueType antialiased and rotated text support,
bezier curves, opening existing PNG images and more.
"""
homepage = "http://pngwriter.sourceforge.net/"
url = "https://github.com/pngwriter/pngwriter/archive/0.5.6.tar.gz"
git = "https://github.com/pngwriter/pngwriter.git"
maintainers = ['ax3l']
version('develop', branch='dev')
version('master', branch='master')
version('0.7.0', sha256='82d46eef109f434f95eba9cf5908710ae4e75f575fd3858178ad06e800152825')
version('0.6.0', sha256='5107c6be0bfadf76ba4d01a553f7e060b5a7763ca7d9374ef3e7e59746b3911e')
version('0.5.6', sha256='0c5f3c1fd6f2470e88951f4b8add64cf5f5a7e7038115dba69604139359b08f1')
depends_on('libpng')
depends_on('zlib')
depends_on('freetype')
def cmake_args(self):
spec = self.spec
args = []
if spec.satisfies('@0.7.0:'):
args += ['-DPNGwriter_USE_FREETYPE:BOOL=ON']
return args<|fim▁end|>
| |
<|file_name|>problema2crocha.py<|end_file_name|><|fim▁begin|>#Hecho en python 3.5
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
librosCodigo = {"Francés":[13735,13808],"Español":[24925,15027],"Portugés":[14904,16384],"Inglés":[10422,1013]}
dic_idiomas={}
#hola dos
for idioma in librosCodigo.keys():
diccionario_largo_palabras={}
for indeCo in librosCodigo[idioma]:
texto= strip_headers(load_etext(indeCo))
dic_idiomas[idioma]= diccionario_largo_palabras
for caracter_especial in ['"',"...","¿","?","=","_","[","]","(",")",",",".",":",";","!","¡","«","»","*","~","' "," '","- "," -","--"]:
texto=texto.replace(caracter_especial," ")
palabras=texto.split()<|fim▁hole|> for palabra in palabras:
largo_palabra = len(palabra)
if largo_palabra in diccionario_largo_palabras:
diccionario_largo_palabras[largo_palabra] = diccionario_largo_palabras[largo_palabra]+1
else:
diccionario_largo_palabras[largo_palabra]= 1
print (dic_idiomas)<|fim▁end|>
| |
<|file_name|>FileSystemCommandOptions.java<|end_file_name|><|fim▁begin|>/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.wire;
/**
* Class to represent {@link FileSystemCommand} options.
*/
public final class FileSystemCommandOptions {
private PersistCommandOptions mPersistCommandOptions;
/**
* Creates a new instance of {@link FileSystemCommandOptions}.
*/
public FileSystemCommandOptions() {}
/**
* @return the persist options
*/
public PersistCommandOptions getPersistOptions() {
return mPersistCommandOptions;
}
/**
* Set the persist options.
*
* @param persistCommandOptions the persist options
*/<|fim▁hole|> }
}<|fim▁end|>
|
public void setPersistOptions(PersistCommandOptions persistCommandOptions) {
mPersistCommandOptions = persistCommandOptions;
|
<|file_name|>spellcheck_ui.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'spellcheck.ui'
#
# Created: Thu Jul 30 01:27:24 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(579, 352)
self.gridLayout_2 = QtGui.QGridLayout(Form)
self.gridLayout_2.setMargin(0)
self.gridLayout_2.setSpacing(0)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.fr_main = QtGui.QFrame(Form)
self.fr_main.setStyleSheet(_fromUtf8("QFrame#fr_main {\n"
" background-color: qlineargradient(spread:pad, x1:1, y1:1, x2:1, y2:0, stop:0 rgba(82, 82, 82, 255), stop:0.0590909 rgba(111, 111, 111, 255), stop:0.922727 rgba(99, 99, 99, 255), stop:1 rgba(151, 151, 151, 255));\n"
"border-radius:8px;\n"
"}"))
self.fr_main.setFrameShape(QtGui.QFrame.NoFrame)
self.fr_main.setFrameShadow(QtGui.QFrame.Raised)
self.fr_main.setObjectName(_fromUtf8("fr_main"))
self.gridLayout_4 = QtGui.QGridLayout(self.fr_main)
self.gridLayout_4.setMargin(6)
self.gridLayout_4.setSpacing(4)
self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))
self.te_text = QtGui.QPlainTextEdit(self.fr_main)
self.te_text.setReadOnly(True)
self.te_text.setObjectName(_fromUtf8("te_text"))
self.gridLayout_4.addWidget(self.te_text, 2, 0, 1, 4)
self.frame = QtGui.QFrame(self.fr_main)
self.frame.setFrameShape(QtGui.QFrame.NoFrame)
self.frame.setFrameShadow(QtGui.QFrame.Raised)
self.frame.setObjectName(_fromUtf8("frame"))
self.gridLayout = QtGui.QGridLayout(self.frame)
self.gridLayout.setMargin(0)
self.gridLayout.setHorizontalSpacing(8)
self.gridLayout.setVerticalSpacing(4)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
spacerItem = QtGui.QSpacerItem(313, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)
self.b_cancel = QtGui.QPushButton(self.frame)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("../../style/img/close_hover.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.b_cancel.setIcon(icon)
self.b_cancel.setObjectName(_fromUtf8("b_cancel"))
self.gridLayout.addWidget(self.b_cancel, 0, 2, 1, 1)
self.b_ok = QtGui.QPushButton(self.frame)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.b_ok.setFont(font)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("../../style/img/checkmark.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.b_ok.setIcon(icon1)
self.b_ok.setObjectName(_fromUtf8("b_ok"))
self.gridLayout.addWidget(self.b_ok, 0, 3, 1, 1)
self.l_count = QtGui.QLabel(self.frame)
self.l_count.setStyleSheet(_fromUtf8("color: rgb(184, 215, 255);"))
self.l_count.setObjectName(_fromUtf8("l_count"))
self.gridLayout.addWidget(self.l_count, 0, 0, 1, 1)
self.gridLayout_4.addWidget(self.frame, 3, 0, 1, 4)
self.frame_2 = QtGui.QFrame(self.fr_main)
self.frame_2.setFrameShape(QtGui.QFrame.NoFrame)
self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
self.frame_2.setObjectName(_fromUtf8("frame_2"))
self.gridLayout_3 = QtGui.QGridLayout(self.frame_2)<|fim▁hole|> self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
self.label_2 = QtGui.QLabel(self.frame_2)
font = QtGui.QFont()
font.setItalic(True)
self.label_2.setFont(font)
self.label_2.setStyleSheet(_fromUtf8("color: rgb(250, 255, 187);"))
self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout_3.addWidget(self.label_2, 0, 5, 1, 1)
self.b_redo = QtGui.QPushButton(self.frame_2)
self.b_redo.setMaximumSize(QtCore.QSize(26, 24))
self.b_redo.setText(_fromUtf8(""))
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8("../../style/img/redo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.b_redo.setIcon(icon2)
self.b_redo.setObjectName(_fromUtf8("b_redo"))
self.gridLayout_3.addWidget(self.b_redo, 0, 3, 1, 1)
self.b_undo = QtGui.QPushButton(self.frame_2)
self.b_undo.setMaximumSize(QtCore.QSize(26, 24))
self.b_undo.setText(_fromUtf8(""))
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8("../../style/img/undo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.b_undo.setIcon(icon3)
self.b_undo.setObjectName(_fromUtf8("b_undo"))
self.gridLayout_3.addWidget(self.b_undo, 0, 2, 1, 1)
self.label = QtGui.QLabel(self.frame_2)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setStyleSheet(_fromUtf8("color:white;"))
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout_3.addWidget(self.label, 0, 0, 1, 1)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout_3.addItem(spacerItem1, 0, 4, 1, 1)
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.gridLayout_3.addItem(spacerItem2, 0, 1, 1, 1)
self.gridLayout_4.addWidget(self.frame_2, 1, 0, 1, 4)
self.gridLayout_2.addWidget(self.fr_main, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QObject.connect(self.b_undo, QtCore.SIGNAL(_fromUtf8("clicked()")), self.te_text.undo)
QtCore.QObject.connect(self.b_redo, QtCore.SIGNAL(_fromUtf8("clicked()")), self.te_text.redo)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.b_cancel.setText(_translate("Form", "cancel", None))
self.b_ok.setText(_translate("Form", "apply changes", None))
self.l_count.setText(_translate("Form", "0 changes", None))
self.label_2.setText(_translate("Form", "Right click on word for spelling suggestions", None))
self.b_redo.setToolTip(_translate("Form", "redo", None))
self.b_undo.setToolTip(_translate("Form", "undo", None))
self.label.setText(_translate("Form", "Spellcheck", None))<|fim▁end|>
|
self.gridLayout_3.setSpacing(4)
self.gridLayout_3.setContentsMargins(4, 0, 4, 0)
|
<|file_name|>test_data_root.py<|end_file_name|><|fim▁begin|># This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
from twisted.internet import defer
from twisted.trial import unittest
from buildbot.data import connector
from buildbot.data import root
from buildbot.test.util import endpoint
class RootEndpoint(endpoint.EndpointMixin, unittest.TestCase):
endpointClass = root.RootEndpoint
resourceTypeClass = root.Root
<|fim▁hole|> {'name': u'abc'},
]
def tearDown(self):
self.tearDownEndpoint()
@defer.inlineCallbacks
def test_get(self):
rootlinks = yield self.callGet(('',))
[self.validateData(root) for root in rootlinks]
self.assertEqual(rootlinks, [
{'name': u'abc'},
])
class SpecEndpoint(endpoint.EndpointMixin, unittest.TestCase):
endpointClass = root.SpecEndpoint
resourceTypeClass = root.Spec
def setUp(self):
self.setUpEndpoint()
# replace fakeConnector with real DataConnector
self.master.data.disownServiceParent()
self.master.data = connector.DataConnector()
self.master.data.setServiceParent(self.master)
def tearDown(self):
self.tearDownEndpoint()
@defer.inlineCallbacks
def test_get(self):
specs = yield self.callGet(('application.spec',))
[self.validateData(s) for s in specs]
for s in specs:
# only test an endpoint that is reasonably stable
if s['path'] != "master":
continue
self.assertEqual(s,
{'path': 'master',
'type': 'master',
'type_spec': {'fields': [{'name': 'active',
'type': 'boolean',
'type_spec': {'name': 'boolean'}},
{'name': 'masterid',
'type': 'integer',
'type_spec': {'name': 'integer'}},
{'name': 'link',
'type': 'link',
'type_spec': {'name': 'link'}},
{'name': 'name',
'type': 'string',
'type_spec': {'name': 'string'}},
{'name': 'last_active',
'type': 'datetime',
'type_spec': {'name': 'datetime'}}],
'type': 'master'},
'plural': 'masters'})<|fim▁end|>
|
def setUp(self):
self.setUpEndpoint()
self.master.data.rootLinks = [
|
<|file_name|>changepassword.spec.js<|end_file_name|><|fim▁begin|>'use strict';
describe('E2E testing: Change password', function () {
var constants = require('../../../testConstants');
var loginPage = require('../../pages/loginPage');
var header = require('../../pages/pageHeader');
var changePasswordPage = require('../../pages/changePasswordPage');
var expectedCondition = protractor.ExpectedConditions;
var CONDITION_TIMEOUT = 3000;
var newPassword = '12345678';
it('setup: login as user, go to change password page', function () {
loginPage.loginAsUser();
changePasswordPage.get();
});
it('refuses to allow form submission if the confirm input does not match', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys('blah12345');
expect(changePasswordPage.submitButton.isEnabled()).toBeFalsy();
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
it('allows form submission if the confirm input matches', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys(newPassword);
expect(changePasswordPage.submitButton.isEnabled()).toBeTruthy();
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
/* cant test this yet because I don't know how to test for HTML 5 form validation - cjh 2014-06
it('should not allow a password less than 7 characters', function() {
var shortPassword = '12345';
changePasswordPage.password.sendKeys(shortPassword);
changePasswordPage.confirm.sendKeys(shortPassword);
expect(changePasswordPage.submitButton.isEnabled()).toBe(false);
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
*/
it('can successfully changes user\'s password after form submission', function () {
changePasswordPage.password.sendKeys(newPassword);<|fim▁hole|> changePasswordPage.confirm.sendKeys(newPassword);
browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage),
CONDITION_TIMEOUT);
browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton),
CONDITION_TIMEOUT);
changePasswordPage.submitButton.click();
expect(changePasswordPage.noticeList.count()).toBe(1);
expect(changePasswordPage.noticeList.first().getText()).toContain('Password Updated');
loginPage.logout();
loginPage.login(constants.memberUsername, newPassword);
browser.wait(expectedCondition.visibilityOf(header.myProjects.button), CONDITION_TIMEOUT);
expect(header.myProjects.button.isDisplayed()).toBe(true);
// reset password back to original
changePasswordPage.get();
changePasswordPage.password.sendKeys(constants.memberPassword);
changePasswordPage.confirm.sendKeys(constants.memberPassword);
browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage),
CONDITION_TIMEOUT);
browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton),
CONDITION_TIMEOUT);
changePasswordPage.submitButton.click();
});
});<|fim▁end|>
| |
<|file_name|>htmltextareaelement.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::element::RawLayoutElementHelpers;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::globalscope::GlobalScope;
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::keyboardevent::KeyboardEvent;
use dom::node::{ChildrenMutation, Node, NodeDamage, UnbindContext};
use dom::node::{document_from_node, window_from_node};
use dom::nodelist::NodeList;
use dom::validation::Validatable;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use script_traits::ScriptToConstellationChan;
use std::cell::Cell;
use std::default::Default;
use std::ops::Range;
use style::attr::AttrValue;
use style::element_state::*;
use textinput::{KeyReaction, Lines, SelectionDirection, TextInput};
#[dom_struct]
pub struct HTMLTextAreaElement {
htmlelement: HTMLElement,
#[ignore_malloc_size_of = "#7193"]
textinput: DomRefCell<TextInput<ScriptToConstellationChan>>,
placeholder: DomRefCell<DOMString>,
// https://html.spec.whatwg.org/multipage/#concept-textarea-dirty
value_changed: Cell<bool>,
form_owner: MutNullableDom<HTMLFormElement>,
}
pub trait LayoutHTMLTextAreaElementHelpers {
#[allow(unsafe_code)]
unsafe fn get_value_for_layout(self) -> String;
#[allow(unsafe_code)]
unsafe fn selection_for_layout(self) -> Option<Range<usize>>;
#[allow(unsafe_code)]
fn get_cols(self) -> u32;
#[allow(unsafe_code)]
fn get_rows(self) -> u32;
}
impl LayoutHTMLTextAreaElementHelpers for LayoutDom<HTMLTextAreaElement> {
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn get_value_for_layout(self) -> String {
let text = (*self.unsafe_get()).textinput.borrow_for_layout().get_content();
String::from(if text.is_empty() {
(*self.unsafe_get()).placeholder.borrow_for_layout().clone()
} else {
text
})
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn selection_for_layout(self) -> Option<Range<usize>> {
if !(*self.unsafe_get()).upcast::<Element>().focus_state() {
return None;
}
let textinput = (*self.unsafe_get()).textinput.borrow_for_layout();
Some(textinput.get_absolute_selection_range())
}
#[allow(unsafe_code)]
fn get_cols(self) -> u32 {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("cols"))
.map_or(DEFAULT_COLS, AttrValue::as_uint)
}
}
#[allow(unsafe_code)]
fn get_rows(self) -> u32 {<|fim▁hole|> }
}
}
// https://html.spec.whatwg.org/multipage/#attr-textarea-cols-value
static DEFAULT_COLS: u32 = 20;
// https://html.spec.whatwg.org/multipage/#attr-textarea-rows-value
static DEFAULT_ROWS: u32 = 2;
impl HTMLTextAreaElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> HTMLTextAreaElement {
let chan = document.window().upcast::<GlobalScope>().script_to_constellation_chan().clone();
HTMLTextAreaElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE,
local_name, prefix, document),
placeholder: DomRefCell::new(DOMString::new()),
textinput: DomRefCell::new(TextInput::new(
Lines::Multiple, DOMString::new(), chan, None, None, SelectionDirection::None)),
value_changed: Cell::new(false),
form_owner: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLTextAreaElement> {
Node::reflect_node(Box::new(HTMLTextAreaElement::new_inherited(local_name, prefix, document)),
document,
HTMLTextAreaElementBinding::Wrap)
}
fn update_placeholder_shown_state(&self) {
let has_placeholder = !self.placeholder.borrow().is_empty();
let has_value = !self.textinput.borrow().is_empty();
let el = self.upcast::<Element>();
el.set_placeholder_shown_state(has_placeholder && !has_value);
el.set_placeholder_shown_state(has_placeholder);
}
}
impl HTMLTextAreaElementMethods for HTMLTextAreaElement {
// TODO A few of these attributes have default values and additional
// constraints
// https://html.spec.whatwg.org/multipage/#dom-textarea-cols
make_uint_getter!(Cols, "cols", DEFAULT_COLS);
// https://html.spec.whatwg.org/multipage/#dom-textarea-cols
make_limited_uint_setter!(SetCols, "cols", DEFAULT_COLS);
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#attr-fe-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#attr-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-textarea-placeholder
make_getter!(Placeholder, "placeholder");
// https://html.spec.whatwg.org/multipage/#dom-textarea-placeholder
make_setter!(SetPlaceholder, "placeholder");
// https://html.spec.whatwg.org/multipage/#attr-textarea-readonly
make_bool_getter!(ReadOnly, "readonly");
// https://html.spec.whatwg.org/multipage/#attr-textarea-readonly
make_bool_setter!(SetReadOnly, "readonly");
// https://html.spec.whatwg.org/multipage/#dom-textarea-required
make_bool_getter!(Required, "required");
// https://html.spec.whatwg.org/multipage/#dom-textarea-required
make_bool_setter!(SetRequired, "required");
// https://html.spec.whatwg.org/multipage/#dom-textarea-rows
make_uint_getter!(Rows, "rows", DEFAULT_ROWS);
// https://html.spec.whatwg.org/multipage/#dom-textarea-rows
make_limited_uint_setter!(SetRows, "rows", DEFAULT_ROWS);
// https://html.spec.whatwg.org/multipage/#dom-textarea-wrap
make_getter!(Wrap, "wrap");
// https://html.spec.whatwg.org/multipage/#dom-textarea-wrap
make_setter!(SetWrap, "wrap");
// https://html.spec.whatwg.org/multipage/#dom-textarea-type
fn Type(&self) -> DOMString {
DOMString::from("textarea")
}
// https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue
fn DefaultValue(&self) -> DOMString {
self.upcast::<Node>().GetTextContent().unwrap()
}
// https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue
fn SetDefaultValue(&self, value: DOMString) {
self.upcast::<Node>().SetTextContent(Some(value));
// if the element's dirty value flag is false, then the element's
// raw value must be set to the value of the element's textContent IDL attribute
if !self.value_changed.get() {
self.reset();
}
}
// https://html.spec.whatwg.org/multipage/#dom-textarea-value
fn Value(&self) -> DOMString {
self.textinput.borrow().get_content()
}
// https://html.spec.whatwg.org/multipage/#dom-textarea-value
fn SetValue(&self, value: DOMString) {
// TODO move the cursor to the end of the field
self.textinput.borrow_mut().set_content(value);
self.value_changed.set(true);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> DomRoot<NodeList> {
self.upcast::<HTMLElement>().labels()
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection
fn SetSelectionDirection(&self, direction: DOMString) {
self.textinput.borrow_mut().selection_direction = SelectionDirection::from(direction);
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection
fn SelectionDirection(&self) -> DOMString {
DOMString::from(self.textinput.borrow().selection_direction)
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend
fn SetSelectionEnd(&self, end: u32) {
let selection_start = self.SelectionStart();
self.textinput.borrow_mut().set_selection_range(selection_start, end);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend
fn SelectionEnd(&self) -> u32 {
self.textinput.borrow().get_absolute_insertion_point() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart
fn SetSelectionStart(&self, start: u32) {
let selection_end = self.SelectionEnd();
self.textinput.borrow_mut().set_selection_range(start, selection_end);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart
fn SelectionStart(&self) -> u32 {
self.textinput.borrow().get_selection_start()
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-setselectionrange
fn SetSelectionRange(&self, start: u32, end: u32, direction: Option<DOMString>) {
let direction = direction.map_or(SelectionDirection::None, |d| SelectionDirection::from(d));
self.textinput.borrow_mut().selection_direction = direction;
self.textinput.borrow_mut().set_selection_range(start, end);
let window = window_from_node(self);
let _ = window.user_interaction_task_source().queue_event(
&self.upcast(),
atom!("select"),
EventBubbles::Bubbles,
EventCancelable::NotCancelable,
&window);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
}
impl HTMLTextAreaElement {
pub fn reset(&self) {
// https://html.spec.whatwg.org/multipage/#the-textarea-element:concept-form-reset-control
self.SetValue(self.DefaultValue());
self.value_changed.set(false);
}
}
impl VirtualMethods for HTMLTextAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match *attr.local_name() {
local_name!("disabled") => {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
el.set_read_write_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
if !el.disabled_state() && !el.read_write_state() {
el.set_read_write_state(true);
}
}
}
},
local_name!("placeholder") => {
{
let mut placeholder = self.placeholder.borrow_mut();
placeholder.clear();
if let AttributeMutation::Set(_) = mutation {
placeholder.push_str(&attr.value());
}
}
self.update_placeholder_shown_state();
},
local_name!("readonly") => {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_read_write_state(false);
},
AttributeMutation::Removed => {
el.set_read_write_state(!el.disabled_state());
}
}
},
local_name!("form") => {
self.form_attribute_mutated(mutation);
},
_ => {},
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match *name {
local_name!("cols") => AttrValue::from_limited_u32(value.into(), DEFAULT_COLS),
local_name!("rows") => AttrValue::from_limited_u32(value.into(), DEFAULT_ROWS),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
if !self.value_changed.get() {
self.reset();
}
}
// copied and modified from htmlinputelement.rs
fn handle_event(&self, event: &Event) {
if let Some(s) = self.super_type() {
s.handle_event(event);
}
if event.type_() == atom!("click") && !event.DefaultPrevented() {
//TODO: set the editing position for text inputs
document_from_node(self).request_focus(self.upcast());
} else if event.type_() == atom!("keydown") && !event.DefaultPrevented() {
if let Some(kevent) = event.downcast::<KeyboardEvent>() {
// This can't be inlined, as holding on to textinput.borrow_mut()
// during self.implicit_submission will cause a panic.
let action = self.textinput.borrow_mut().handle_keydown(kevent);
match action {
KeyReaction::TriggerDefaultAction => (),
KeyReaction::DispatchInput => {
self.value_changed.set(true);
self.update_placeholder_shown_state();
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
event.mark_as_handled();
}
KeyReaction::RedrawSelection => {
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
event.mark_as_handled();
}
KeyReaction::Nothing => (),
}
}
} else if event.type_() == atom!("keypress") && !event.DefaultPrevented() {
if event.IsTrusted() {
let window = window_from_node(self);
let _ = window.user_interaction_task_source()
.queue_event(&self.upcast(),
atom!("input"),
EventBubbles::Bubbles,
EventCancelable::NotCancelable,
&window);
}
}
}
fn pop(&self) {
self.super_type().unwrap().pop();
// https://html.spec.whatwg.org/multipage/#the-textarea-element:stack-of-open-elements
self.reset();
}
}
impl FormControl for HTMLTextAreaElement {
fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
self.form_owner.get()
}
fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
self.form_owner.set(form);
}
fn to_element<'a>(&'a self) -> &'a Element {
self.upcast::<Element>()
}
}
impl Validatable for HTMLTextAreaElement {}<|fim▁end|>
|
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("rows"))
.map_or(DEFAULT_ROWS, AttrValue::as_uint)
|
<|file_name|>joexx_traits.t.cpp<|end_file_name|><|fim▁begin|>// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<|fim▁hole|>// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------<|fim▁end|>
| |
<|file_name|>appflowcollector.py<|end_file_name|><|fim▁begin|>#
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# 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.
#
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util
class appflowcollector(base_resource) :
""" Configuration for AppFlow collector resource. """
def __init__(self) :
self._name = ""
self._ipaddress = ""
self._port = 0
self._netprofile = ""
self._newname = ""
self.___count = 0
@property
def name(self) :
"""Name for the collector. Must begin with an ASCII alphabetic or underscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at
(@), equals (=), and hyphen (-) characters.
Only four collectors can be configured.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my appflow collector" or 'my appflow collector').<br/>Minimum length = 1<br/>Maximum length = 127.
"""
try :
return self._name
except Exception as e:<|fim▁hole|> """Name for the collector. Must begin with an ASCII alphabetic or underscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at
(@), equals (=), and hyphen (-) characters.
Only four collectors can be configured.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my appflow collector" or 'my appflow collector').<br/>Minimum length = 1<br/>Maximum length = 127
"""
try :
self._name = name
except Exception as e:
raise e
@property
def ipaddress(self) :
"""IPv4 address of the collector.
"""
try :
return self._ipaddress
except Exception as e:
raise e
@ipaddress.setter
def ipaddress(self, ipaddress) :
"""IPv4 address of the collector.
"""
try :
self._ipaddress = ipaddress
except Exception as e:
raise e
@property
def port(self) :
"""UDP port on which the collector listens.<br/>Default value: 4739.
"""
try :
return self._port
except Exception as e:
raise e
@port.setter
def port(self, port) :
"""UDP port on which the collector listens.<br/>Default value: 4739
"""
try :
self._port = port
except Exception as e:
raise e
@property
def netprofile(self) :
"""Netprofile to associate with the collector. The IP address defined in the profile is used as the source IP address for AppFlow traffic for this collector. If you do not set this parameter, the NetScaler IP (NSIP) address is used as the source IP address.<br/>Maximum length = 128.
"""
try :
return self._netprofile
except Exception as e:
raise e
@netprofile.setter
def netprofile(self, netprofile) :
"""Netprofile to associate with the collector. The IP address defined in the profile is used as the source IP address for AppFlow traffic for this collector. If you do not set this parameter, the NetScaler IP (NSIP) address is used as the source IP address.<br/>Maximum length = 128
"""
try :
self._netprofile = netprofile
except Exception as e:
raise e
@property
def newname(self) :
"""New name for the collector. Must begin with an ASCII alphabetic or underscore (_) character, and must
contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at(@), equals (=), and hyphen (-) characters.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my appflow coll" or 'my appflow coll').<br/>Minimum length = 1.
"""
try :
return self._newname
except Exception as e:
raise e
@newname.setter
def newname(self, newname) :
"""New name for the collector. Must begin with an ASCII alphabetic or underscore (_) character, and must
contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at(@), equals (=), and hyphen (-) characters.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my appflow coll" or 'my appflow coll').<br/>Minimum length = 1
"""
try :
self._newname = newname
except Exception as e:
raise e
def _get_nitro_response(self, service, response) :
""" converts nitro response into object and returns the object array in case of get request.
"""
try :
result = service.payload_formatter.string_to_resource(appflowcollector_response, response, self.__class__.__name__)
if(result.errorcode != 0) :
if (result.errorcode == 444) :
service.clear_session(self)
if result.severity :
if (result.severity == "ERROR") :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
else :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
return result.appflowcollector
except Exception as e :
raise e
def _get_object_name(self) :
""" Returns the value of object identifier argument
"""
try :
if (self.name) :
return str(self.name)
return None
except Exception as e :
raise e
@classmethod
def add(cls, client, resource) :
""" Use this API to add appflowcollector.
"""
try :
if type(resource) is not list :
addresource = appflowcollector()
addresource.name = resource.name
addresource.ipaddress = resource.ipaddress
addresource.port = resource.port
addresource.netprofile = resource.netprofile
return addresource.add_resource(client)
else :
if (resource and len(resource) > 0) :
addresources = [ appflowcollector() for _ in range(len(resource))]
for i in range(len(resource)) :
addresources[i].name = resource[i].name
addresources[i].ipaddress = resource[i].ipaddress
addresources[i].port = resource[i].port
addresources[i].netprofile = resource[i].netprofile
result = cls.add_bulk_request(client, addresources)
return result
except Exception as e :
raise e
@classmethod
def delete(cls, client, resource) :
""" Use this API to delete appflowcollector.
"""
try :
if type(resource) is not list :
deleteresource = appflowcollector()
if type(resource) != type(deleteresource):
deleteresource.name = resource
else :
deleteresource.name = resource.name
return deleteresource.delete_resource(client)
else :
if type(resource[0]) != cls :
if (resource and len(resource) > 0) :
deleteresources = [ appflowcollector() for _ in range(len(resource))]
for i in range(len(resource)) :
deleteresources[i].name = resource[i]
else :
if (resource and len(resource) > 0) :
deleteresources = [ appflowcollector() for _ in range(len(resource))]
for i in range(len(resource)) :
deleteresources[i].name = resource[i].name
result = cls.delete_bulk_request(client, deleteresources)
return result
except Exception as e :
raise e
@classmethod
def rename(cls, client, resource, new_name) :
""" Use this API to rename a appflowcollector resource.
"""
try :
renameresource = appflowcollector()
if type(resource) == cls :
renameresource.name = resource.name
else :
renameresource.name = resource
return renameresource.rename_resource(client,new_name)
except Exception as e :
raise e
@classmethod
def get(cls, client, name="", option_="") :
""" Use this API to fetch all the appflowcollector resources that are configured on netscaler.
"""
try :
if not name :
obj = appflowcollector()
response = obj.get_resources(client, option_)
else :
if type(name) != cls :
if type(name) is not list :
obj = appflowcollector()
obj.name = name
response = obj.get_resource(client, option_)
else :
if name and len(name) > 0 :
response = [appflowcollector() for _ in range(len(name))]
obj = [appflowcollector() for _ in range(len(name))]
for i in range(len(name)) :
obj[i] = appflowcollector()
obj[i].name = name[i]
response[i] = obj[i].get_resource(client, option_)
return response
except Exception as e :
raise e
@classmethod
def get_filtered(cls, client, filter_) :
""" Use this API to fetch filtered set of appflowcollector resources.
filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj = appflowcollector()
option_ = options()
option_.filter = filter_
response = obj.getfiltered(client, option_)
return response
except Exception as e :
raise e
@classmethod
def count(cls, client) :
""" Use this API to count the appflowcollector resources configured on NetScaler.
"""
try :
obj = appflowcollector()
option_ = options()
option_.count = True
response = obj.get_resources(client, option_)
if response :
return response[0].__dict__['___count']
return 0
except Exception as e :
raise e
@classmethod
def count_filtered(cls, client, filter_) :
""" Use this API to count filtered the set of appflowcollector resources.
Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj = appflowcollector()
option_ = options()
option_.count = True
option_.filter = filter_
response = obj.getfiltered(client, option_)
if response :
return response[0].__dict__['___count']
return 0
except Exception as e :
raise e
class appflowcollector_response(base_response) :
def __init__(self, length=1) :
self.appflowcollector = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.appflowcollector = [appflowcollector() for _ in range(length)]<|fim▁end|>
|
raise e
@name.setter
def name(self, name) :
|
<|file_name|>electron-publish.d.ts<|end_file_name|><|fim▁begin|>declare module "electron-publish/out/multiProgress" {
export class MultiProgress {
private readonly stream
private cursor
private totalLines
private isLogListenerAdded
private barCount
createBar(format: string, options: any): any
private allocateLines(count)
private moveCursor(index)
terminate(): void
}
}
declare module "electron-publish" {
/// <reference types="node" />
import { CancellationToken } from "electron-builder-http/out/CancellationToken"
import { Stats } from "fs-extra-p"
import { ClientRequest } from "http"
import ProgressBar from "progress-ex"
import { MultiProgress } from "electron-publish/out/multiProgress"
export type PublishPolicy = "onTag" | "onTagOrDraft" | "always" | "never"
export interface PublishOptions {
publish?: PublishPolicy | null
draft?: boolean
prerelease?: boolean
}
export interface PublishContext {
readonly cancellationToken: CancellationToken
readonly progress: MultiProgress | null
}
export abstract class Publisher {
protected readonly context: PublishContext
constructor(context: PublishContext)
readonly abstract providerName: string<|fim▁hole|> abstract toString(): string
}
export abstract class HttpPublisher extends Publisher {
protected readonly context: PublishContext
private readonly useSafeArtifactName
constructor(context: PublishContext, useSafeArtifactName?: boolean)
upload(file: string, safeArtifactName?: string): Promise<any>
uploadData(data: Buffer, fileName: string): Promise<any>
protected abstract doUpload(fileName: string, dataLength: number, requestProcessor: (request: ClientRequest, reject: (error: Error) => void) => void, file?: string): Promise<any>
}
}
declare module "electron-publish/out/BintrayPublisher" {
/// <reference types="node" />
import { BintrayOptions } from "electron-builder-http/out/publishOptions"
import { ClientRequest } from "http"
import { HttpPublisher, PublishContext, PublishOptions } from "electron-publish"
export class BintrayPublisher extends HttpPublisher {
private readonly version
private readonly options
private _versionPromise
private readonly client
readonly providerName: string
constructor(context: PublishContext, info: BintrayOptions, version: string, options?: PublishOptions)
private init()
protected doUpload(fileName: string, dataLength: number, requestProcessor: (request: ClientRequest, reject: (error: Error) => void) => void): Promise<any>
deleteRelease(): Promise<any>
toString(): string
}
}
declare module "electron-publish/out/gitHubPublisher" {
/// <reference types="node" />
import { GithubOptions } from "electron-builder-http/out/publishOptions"
import { ClientRequest } from "http"
import { HttpPublisher, PublishContext, PublishOptions } from "electron-publish"
export interface Release {
id: number
tag_name: string
draft: boolean
prerelease: boolean
published_at: string
upload_url: string
}
export class GitHubPublisher extends HttpPublisher {
private readonly info
private readonly version
private readonly options
private tag
private _releasePromise
private readonly token
readonly providerName: string
readonly releasePromise: Promise<Release | null>
constructor(context: PublishContext, info: GithubOptions, version: string, options?: PublishOptions)
private getOrCreateRelease()
protected doUpload(fileName: string, dataLength: number, requestProcessor: (request: ClientRequest, reject: (error: Error) => void) => void): Promise<void>
private createRelease()
getRelease(): Promise<any>
deleteRelease(): Promise<any>
private githubRequest<T>(path, token, data?, method?)
toString(): string
}
}<|fim▁end|>
|
abstract upload(file: string, safeArtifactName?: string): Promise<any>
protected createProgressBar(fileName: string, fileStat: Stats): ProgressBar | null
protected createReadStreamAndProgressBar(file: string, fileStat: Stats, progressBar: ProgressBar | null, reject: (error: Error) => void): NodeJS.ReadableStream
|
<|file_name|>index_mut.rs<|end_file_name|><|fim▁begin|>#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::ops::Index;
use core::ops::IndexMut;
struct Pixel<T> {<|fim▁hole|> b: T
}
impl Index<usize> for Pixel<T> {
type Output = T;
fn index<'a>(&'a self, index: usize) -> &'a Self::Output {
match index {
0 => &self.r,
1 => &self.g,
2 | _ => &self.b
}
}
}
impl IndexMut<usize> for Pixel<T> {
fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Output {
match index {
0 => &mut self.r,
1 => &mut self.g,
2 | _ => &mut self.b
}
}
}
type T = u8;
#[test]
fn index_test1() {
let mut pixel: Pixel<T> = Pixel { r: 0xff, g: 0x92, b: 0x24 };
pixel[0] = 0x01;
pixel[1] = 0x98;
pixel[2] = 0x58;
assert_eq!(pixel[0], 0x01);
assert_eq!(pixel[1], 0x98);
assert_eq!(pixel[2], 0x58);
assert_eq!(pixel[3], 0x58);
}
}<|fim▁end|>
|
r: T,
g: T,
|
<|file_name|>students.routing.ts<|end_file_name|><|fim▁begin|>import { Routes, RouterModule } from '@angular/router';
import { StudentsHomeComponent } from './index';
import { StudentsComponent } from './index';
import { StudentsProfileComponent } from './index';
import { StudentsSponsorLettersComponent } from './index';
import { SponsorLettersAddComponent } from './index';
import { CanActivateViaStudentAuthGuard } from '../app.routing-guards';
const routes: Routes = [
{<|fim▁hole|> {
path: '',
pathMatch: 'full',
component: StudentsHomeComponent
},
{
path: 'home',
component: StudentsHomeComponent
},
{
path: 'profile/:id',
component: StudentsProfileComponent
},
{
path: 'sponsor-letters/:id',
component: StudentsSponsorLettersComponent
},
{
path: 'sponsor-letters-add/:studentId/:sponsorId',
component: SponsorLettersAddComponent
}
]
}
];
export const StudentsRouting = RouterModule.forChild(routes);<|fim▁end|>
|
path: 'students',
component: StudentsComponent,
canActivate: [CanActivateViaStudentAuthGuard],
children: [
|
<|file_name|>Valeur_.java<|end_file_name|><|fim▁begin|>package com.github.cunvoas.iam.persistance.entity;
import com.github.cunvoas.iam.persistance.entity.RessourceValeur;
import javax.annotation.Generated;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.0.v20130507-rNA", date="2014-12-29T14:58:17")
@StaticMetamodel(Valeur.class)
public class Valeur_ {
<|fim▁hole|> public static volatile ListAttribute<Valeur, RessourceValeur> ressourceValues;
}<|fim▁end|>
|
public static volatile SingularAttribute<Valeur, Integer> id;
public static volatile SingularAttribute<Valeur, String> valeur;
|
<|file_name|>explicit.py<|end_file_name|><|fim▁begin|>"""
Sample a specific geometry or set of geometries.
"""
import numpy as np
import nomad.core.glbl as glbl
import nomad.core.trajectory as trajectory
import nomad.core.log as log
def set_initial_coords(wfn):
"""Takes initial position and momentum from geometry specified in input"""
coords = glbl.properties['init_coords']
ndim = coords.shape[-1]<|fim▁hole|> log.print_message('string',[' Initial coordinates taken from input file(s).\n'])
for coord in coords:
itraj = trajectory.Trajectory(glbl.properties['n_states'], ndim,
width=glbl.properties['crd_widths'],
mass=glbl.properties['crd_masses'],
parent=0, kecoef=glbl.modules['integrals'].kecoef)
# set position and momentum
itraj.update_x(np.array(coord[0]))
itraj.update_p(np.array(coord[1]))
# add a single trajectory specified by geometry.dat
wfn.add_trajectory(itraj)<|fim▁end|>
| |
<|file_name|>xlib_window_system.rs<|end_file_name|><|fim▁begin|>#[macro_use]
extern crate log;
extern crate libc;
extern crate x11;
extern crate wtftw_core;
use std::borrow::ToOwned;
use wtftw_core::config::GeneralConfig;
use libc::{ c_char, c_uchar, c_int, c_uint, c_long, c_ulong };
use x11::xlib;
use x11::xinerama;
use std::env::vars;
use std::str;
use std::ptr::null;
use std::ptr::null_mut;
use std::mem::transmute;
use std::mem::uninitialized;
use std::str::from_utf8;
use std::slice::from_raw_parts;
use std::ffi::CString;
use std::ffi::CStr;
use wtftw_core::window_system::*;
use wtftw_core::window_manager::*;
const KEYPRESS : usize = 2;
const BUTTONPRESS : usize = 4;
const BUTTONRELEASE : usize = 5;
const MOTIONOTIFY : usize = 6;
const ENTERNOTIFY : usize = 7;
const LEAVENOTIFY : usize = 8;
const DESTROYNOTIFY : usize = 17;
const UNMAPNOTIFY : usize = 18;
const MAPREQUEST : usize = 20;
const CONFIGURENOTIFY : usize = 22;
const CONFIGUREREQUEST : usize = 23;
const PROPERTYNOTIFY : usize = 28;
const CLIENTMESSAGE : usize = 33;
const BADWINDOW : i32 = 3;
/// A custom error handler to prevent xlib from crashing the whole WM.
/// Necessary because a few events may call the error routine.
unsafe extern fn error_handler(_: *mut xlib::Display, _: *mut xlib::XErrorEvent) -> c_int {
return 0;
}
/// The xlib interface. Holds a pointer to the display,
/// the root window's id and a generic vent so
/// we don't have to allocate it every time.
//#[derive(Clone, Copy)]
pub struct XlibWindowSystem {
display: *mut xlib::Display,
root: Window,
}
impl XlibWindowSystem {
/// Creates a new xlib interface on the default display (i.e. ${DISPLAY})
/// and creates a root window spanning all screens (including xlib::Xinerama).
pub fn new() -> XlibWindowSystem {
unsafe {
let display = xlib::XOpenDisplay(null());
if display == null_mut() {
error!("No display found at {}",
vars()
.find(|&(ref d, _)| *d == "DISPLAY".to_owned())
.map(|(_, v)| v)
.unwrap());
panic!("Exiting");
}
let screen = xlib::XDefaultScreenOfDisplay(display);
let root = xlib::XRootWindowOfScreen(screen);
xlib::XSetErrorHandler(Some(error_handler));
xlib::XSelectInput(display, root, 0x5A0034);
xlib::XSync(display, 0);
xlib::XUngrabButton(display, 0, 0x8000, root);
let res = XlibWindowSystem {
display: display,
root: root as u64,
};
let name = (*CString::new(&b"wtftw"[..]).unwrap()).as_ptr();
let wmcheck = res.get_atom("_NET_SUPPORTING_WM_CHECK");
let wmname = res.get_atom("_NET_WM_NAME");
let utf8 = res.get_atom("UTF8_STRING");
let xa_window = res.get_atom("xlib::XA_WINDOW");
let mut root_cpy = root;
let root_ptr : *mut Window = &mut root_cpy;
xlib::XChangeProperty(display, root, wmcheck, xa_window, 32, 0, root_ptr as *mut c_uchar, 1);
xlib::XChangeProperty(display, root, wmname, utf8, 8, 0, name as *mut c_uchar, 5);
res
}
}
fn get_property(&self, atom: Window, window: Window) -> Option<Vec<u64>> {
unsafe {
let mut actual_type_return : c_ulong = 0;
let mut actual_format_return : c_int = 0;
let mut nitems_return : c_ulong = 0;
let mut bytes_after_return : c_ulong = 0;
let mut prop_return : *mut c_uchar = uninitialized();
let r = xlib::XGetWindowProperty(self.display, window as c_ulong, atom as c_ulong, 0, 0xFFFFFFFF, 0, 0,
&mut actual_type_return,
&mut actual_format_return,
&mut nitems_return,
&mut bytes_after_return,
&mut prop_return);
if r != 0 {
None
} else {
if actual_format_return == 0 {
None
} else {
Some(from_raw_parts(prop_return as *const c_ulong, nitems_return as usize).iter()
.map(|&c| c as u64)
.collect())
}
}
}
}
fn get_property_from_string(&self, s: &str, window: Window) -> Option<Vec<u64>> {
unsafe {
match CString::new(s.as_bytes()) {
Ok(b) => {
let atom = xlib::XInternAtom(self.display, b.as_ptr(), 0);
self.get_property(atom as u64, window)
},
_ => None
}
}
}
fn get_atom(&self, s: &str) -> u64 {
unsafe {
match CString::new(s) {
Ok(b) => xlib::XInternAtom(self.display, b.as_ptr(), 0) as u64,
_ => panic!("Invalid atom! {}", s)
}
}
}
fn get_protocols(&self, window: Window) -> Vec<u64> {
unsafe {
let mut protocols : *mut c_ulong = uninitialized();
let mut num = 0;
xlib::XGetWMProtocols(self.display, window as c_ulong, &mut protocols, &mut num);
from_raw_parts(&(protocols as *const c_ulong), num as usize).iter()
.map(|&c| c as u64)
.collect::<Vec<_>>()
}
}
fn change_property(&self, window: Window, property: u64, typ: u64, mode: c_int, dat: &mut [c_ulong]) {
unsafe {
let ptr : *mut u8 = transmute(dat.as_mut_ptr());
xlib::XChangeProperty(self.display, window as c_ulong, property as c_ulong, typ as c_ulong, 32, mode, ptr, 2);
}
}
fn set_button_grab(&self, grab: bool, window: Window) {
if grab {
debug!("grabbing mouse buttons for {}", window);
for &button in (vec!(1, 2, 3)).iter() {
unsafe { xlib::XGrabButton(self.display, button, 0x8000, window as c_ulong, 0, 4, 1, 0, 0, 0); }
}
} else {
debug!("ungrabbing mouse buttons for {}", window);
unsafe { xlib::XUngrabButton(self.display, 0, 0x8000, window as c_ulong); }
}
}
fn set_focus(&self, window: Window, window_manager: &WindowManager) {
debug!("setting focus to {}", window);
for &other_window in window_manager.workspaces.visible_windows().iter() {
self.set_button_grab(true, other_window);
}
if window != self.root {
self.set_button_grab(false, window);
}
}
}
impl WindowSystem for XlibWindowSystem {
fn get_partial_strut(&self, window: Window) -> Option<Vec<u64>> {
self.get_property_from_string("_NET_WM_STRUT_PARTIAL", window)
}
fn get_strut(&self, window: Window) -> Option<Vec<u64>> {
self.get_property_from_string("_NET_WM_STRUT", window)
}
fn is_dock(&self, window: Window) -> bool {
let dock = self.get_atom("_NET_WM_WINDOW_TYPE_DOCK");
let desk = self.get_atom("_NET_WM_WINDOW_TYPE_DESKTOP");
if let Some(rs) = self.get_property_from_string("_NET_WM_WINDOW_TYPE", window) {
rs.iter().any(|&x| x == dock || x == desk)
} else {
false
}
}
fn get_string_from_keycode(&self, key: u32) -> String {
unsafe {
let keysym = xlib::XKeycodeToKeysym(self.display, key as u8, 0);
let keyname : *mut c_char = xlib::XKeysymToString(keysym);
match from_utf8(CStr::from_ptr(transmute(keyname)).to_bytes()) {
Ok(x) => x.to_owned(),
_ => panic!("Invalid keycode!")
}
}
}
fn get_keycode_from_string(&self, key: &str) -> u64 {
unsafe {
match CString::new(key.as_bytes()) {
Ok(b) => xlib::XStringToKeysym(b.as_ptr()) as u64,
_ => panic!("Invalid key string!")
}
}
}
fn get_root(&self) -> Window {
self.root
}
fn get_screen_infos(&self) -> Vec<Rectangle> {
unsafe {
let mut num : c_int = 0;
let screen_ptr : *const xinerama::XineramaScreenInfo = xinerama::XineramaQueryScreens(self.display, &mut num);
// If xinerama is not active, just return the default display
// dimensions and "emulate" xinerama.
if num == 0 {
return vec!(Rectangle(0, 0,
self.get_display_width(0),
self.get_display_height(0)));
}
let screens = from_raw_parts(screen_ptr, num as usize).to_vec();
screens.into_iter().map(
|s| {
Rectangle(
s.x_org as i32,
s.y_org as i32,
s.width as u32,
s.height as u32)}).collect()
}
}
fn get_number_of_screens(&self) -> usize {
unsafe {
xlib::XScreenCount(self.display) as usize
}
}
fn get_display_width(&self, screen: usize) -> u32 {
unsafe {
xlib::XDisplayWidth(self.display, screen as i32) as u32
}
}
fn get_display_height(&self, screen: usize) -> u32 {
unsafe {
xlib::XDisplayHeight(self.display, screen as i32) as u32
}
}
fn get_window_name(&self, window: Window) -> String {
if window == self.root { return "root".to_owned(); }
unsafe {
let mut name : *mut c_char = uninitialized();
if xlib::XFetchName(self.display, window as c_ulong, &mut name) == BADWINDOW || name.is_null() {
"Unknown".to_owned()
} else {
str::from_utf8_unchecked(CStr::from_ptr(name as *const c_char).to_bytes()).to_owned()
}
}
}
fn get_class_name(&self, _: Window) -> String {
//unsafe {
//let mut class_hint : xlib::XClassHint = uninitialized();
//let result = if xlib::XGetClassHint(self.display, window as c_ulong, &mut class_hint) != 0 || class_hint.res_class.is_null() {
"unknown".to_owned()
//} else {
//debug!("getting class name");
//String::from_str(str::from_utf8_unchecked(ffi::c_str_to_bytes(&(class_hint.res_class as *const c_char))))
//};
//debug!("class name is {}", result);
//result
//}
}
fn get_windows(&self) -> Vec<Window> {
unsafe {
let mut unused : c_ulong = 0;
let mut children : *mut c_ulong = uninitialized();
let children_ptr : *mut *mut c_ulong = &mut children;
let mut num_children : c_uint = 0;
xlib::XQueryTree(self.display, self.root as c_ulong,
&mut unused, &mut unused, children_ptr,
&mut num_children);
let const_children : *const u64 = children as *const u64;
debug!("Found {} windows", num_children);
from_raw_parts(const_children, num_children as usize).iter()
.filter(|&&c| c != self.root)
.map(|c| *c)
.collect()
}
}
fn set_window_border_width(&self, window: Window, border_width: u32) {
if window == self.root { return; }
unsafe {
xlib::XSetWindowBorderWidth(self.display, window as c_ulong, border_width);
}
}
fn get_window_border_width(&self, window: Window) -> u32 {
unsafe {
let mut attributes : xlib::XWindowAttributes = uninitialized();
xlib::XGetWindowAttributes(self.display, window as c_ulong, &mut attributes);
attributes.border_width as u32
}
}
fn set_window_border_color(&self, window: Window, border_color: u32) {
if window == self.root { return; }
unsafe {
xlib::XSetWindowBorder(self.display, window as c_ulong, border_color as c_ulong);
}
}
fn resize_window(&self, window: Window, width: u32, height: u32) {
unsafe {
xlib::XResizeWindow(self.display, window as c_ulong, width, height);
}
}
fn move_window(&self, window: Window, x: i32, y: i32) {
unsafe {
xlib::XMoveWindow(self.display, window as c_ulong, x, y);
}
}
fn set_initial_properties(&self, window: Window) {
unsafe {
let atom = self.get_atom("WM_STATE");
self.change_property(window as u64, atom, atom, 0, &mut [3, 0]);
xlib::XSelectInput(self.display, window as c_ulong, 0x420010);
}
}
fn show_window(&self, window: Window) {
unsafe {
let atom = self.get_atom("WM_STATE");
self.change_property(window, atom, atom, 0, &mut [1, 0]);
xlib::XMapWindow(self.display, window as c_ulong);
}
}
fn hide_window(&self, window: Window) {
unsafe {
xlib::XSelectInput(self.display, window as c_ulong, 0x400010);
xlib::XUnmapWindow(self.display, window as c_ulong);
xlib::XSelectInput(self.display, window as c_ulong, 0x420010);
let atom = self.get_atom("WM_STATE");
self.change_property(window as u64, atom, atom, 0, &mut [3, 0]);
}
}
fn focus_window(&self, window: Window, window_manager: &WindowManager) {
unsafe {
self.set_focus(window, window_manager);
xlib::XSetInputFocus(self.display, window as c_ulong, 1, 0);
}
}
fn get_focused_window(&self) -> Window {
unsafe {
let mut window = 0;
let mut tmp = 0;
xlib::XGetInputFocus(self.display, &mut window, &mut tmp) as Window
}
}
fn configure_window(&self, window: Window, window_changes: WindowChanges, mask: u64, is_floating: bool) {
unsafe {
let result = if is_floating {
let mut xlib_window_changes = xlib::XWindowChanges {
x: window_changes.x as i32,
y: window_changes.y as i32,
width: window_changes.width as i32,
height: window_changes.height as i32,
border_width: window_changes.border_width as i32,
sibling: window_changes.sibling as c_ulong,
stack_mode: window_changes.stack_mode as i32
};
xlib::XConfigureWindow(self.display, window as c_ulong, mask as u32, &mut xlib_window_changes);
} else {
let Rectangle(x, y, w, h) = self.get_geometry(window);
let mut attributes : xlib::XWindowAttributes = uninitialized();
xlib::XGetWindowAttributes(self.display, window as c_ulong, &mut attributes);
let mut configure_event : xlib::XConfigureEvent = uninitialized();
configure_event.type_ = CONFIGURENOTIFY as i32;
configure_event.x = attributes.x;
configure_event.y = attributes.y;
configure_event.width = attributes.width;
configure_event.height = attributes.height;
configure_event.border_width = attributes.border_width;
configure_event.above = 0;
configure_event.override_redirect = attributes.override_redirect;
let mut event = xlib::XEvent::from(configure_event);
debug!("sending configure notification for window {}: ({}, {}) {}x{} redirect: {}",
window, x, y, w, h, attributes.override_redirect);
xlib::XSendEvent(self.display, window as c_ulong, 0, 0, &mut event);
};
xlib::XSync(self.display, 0);
result
}
}
fn flush(&self) {
unsafe {
xlib::XFlush(self.display);
}
}
fn event_pending(&self) -> bool {
unsafe {
xlib::XPending(self.display) != 0
}
}
fn get_event(&self) -> WindowSystemEvent {
let mut event = xlib::XEvent { pad : [0; 24] };
unsafe {
xlib::XNextEvent(self.display, &mut event);
}
let event_type = event.get_type();
match event_type as usize {
CLIENTMESSAGE => {
let event = xlib::XClientMessageEvent::from(event);
let data : [i32; 5] = [
event.data.get_long(0) as i32,
event.data.get_long(1) as i32,
event.data.get_long(2) as i32,
event.data.get_long(3) as i32,
event.data.get_long(4) as i32 ];
WindowSystemEvent::ClientMessageEvent(event.window as u64, event.message_type, event.format, data)
},
PROPERTYNOTIFY => {
let event = xlib::XPropertyEvent::from(event);
WindowSystemEvent::PropertyMessageEvent(event.window == self.root, event.window as u64, event.atom)
},
CONFIGUREREQUEST => {
let event = xlib::XConfigureRequestEvent::from(event);
let window_changes = WindowChanges {
x: event.x as u32,
y: event.y as u32,
width: event.width as u32,
height: event.height as u32,
border_width: event.border_width as u32,
sibling: event.above as Window,
stack_mode: event.detail as u32
};
WindowSystemEvent::ConfigurationRequest(event.window as u64, window_changes, event.value_mask as u64)
},
CONFIGURENOTIFY => {
let event = xlib::XConfigureEvent::from(event);
WindowSystemEvent::ConfigurationNotification(event.window as u64)
},
MAPREQUEST => {
let event = xlib::XMapRequestEvent::from(event);
WindowSystemEvent::WindowCreated(event.window as u64)
},
UNMAPNOTIFY => {
let event = xlib::XUnmapEvent::from(event);
WindowSystemEvent::WindowUnmapped(event.window as u64, event.send_event > 0)
},
DESTROYNOTIFY => {
let event = xlib::XDestroyWindowEvent::from(event);
WindowSystemEvent::WindowDestroyed(event.window as u64)
},
ENTERNOTIFY => {
let event = xlib::XEnterWindowEvent::from(event);
if event.detail != 2 {
WindowSystemEvent::Enter(event.window as u64)
} else {
WindowSystemEvent::UnknownEvent
}
},
LEAVENOTIFY => {
let event = xlib::XLeaveWindowEvent::from(event);
if event.detail != 2 {
WindowSystemEvent::Leave(event.window as u64)
} else {
WindowSystemEvent::UnknownEvent
}
},
BUTTONPRESS => {
let event = xlib::XButtonEvent::from(event);
let button = MouseCommand {
button: event.button,
mask: KeyModifiers::from_bits(0xEF & event.state as u32).unwrap()
};
WindowSystemEvent::ButtonPressed(event.window as u64, event.subwindow as u64, button,
event.x_root as u32, event.y_root as u32)
},
BUTTONRELEASE => {
WindowSystemEvent::ButtonReleased
},
KEYPRESS => {
unsafe {
let event = xlib::XKeyEvent::from(event);
let key = KeyCommand {
key: xlib::XKeycodeToKeysym(self.display, event.keycode as u8, 0) as u64,
mask: KeyModifiers::from_bits(0xEF & event.state as u32).unwrap()
};
WindowSystemEvent::KeyPressed(event.window as u64, key)
}
},
MOTIONOTIFY => {
let event = xlib::XMotionEvent::from(event);
WindowSystemEvent::MouseMotion(event.x_root as u32, event.y_root as u32)
},
_ => {
debug!("unknown event is {}", event_type);
WindowSystemEvent::UnknownEvent
}
}
}
fn grab_keys(&self, keys: Vec<KeyCommand>) {
for &key in keys.iter() {
unsafe {
xlib::XGrabKey(self.display, xlib::XKeysymToKeycode(self.display, key.key as c_ulong) as i32,
key.mask.get_mask(), self.root as c_ulong, 1, 1, 1);
xlib::XGrabKey(self.display, xlib::XKeysymToKeycode(self.display, key.key as c_ulong) as i32,
key.mask.get_mask() | 0x10, self.root as c_ulong, 1, 1, 1);
}
}
}
fn grab_button(&self, button: MouseCommand) {
unsafe {
xlib::XGrabButton(self.display, button.button, button.mask.get_mask(),
self.root as c_ulong, 0, 4, 1, 0, 0, 0);
}
}
fn grab_pointer(&self) {
unsafe {
xlib::XGrabPointer(self.display, self.root as c_ulong, 0, 0x48, 1, 1, 0, 0, 0);
}
}
fn ungrab_pointer(&self) {
unsafe {
xlib::XUngrabPointer(self.display, 0);
}
}
fn remove_enter_events(&self) {
unsafe {
let mut event = xlib::XEvent { pad : [0; 24] };
xlib::XSync(self.display, 0);
while xlib::XCheckMaskEvent(self.display, 16, &mut event) != 0 { }
}
}
fn remove_motion_events(&self) {
unsafe {
let mut event = xlib::XEvent { pad : [0; 24] };<|fim▁hole|>
fn get_geometry(&self, window: Window) -> Rectangle {
unsafe {
let mut attributes : xlib::XWindowAttributes = uninitialized();
xlib::XGetWindowAttributes(self.display, window as c_ulong, &mut attributes);
Rectangle(attributes.x as i32, attributes.y as i32, attributes.width as u32, attributes.height as u32)
}
}
fn get_size_hints(&self, window: Window) -> SizeHint {
unsafe {
let mut size_hint : xlib::XSizeHints = uninitialized();
let mut tmp : c_long = 0;
xlib::XGetWMNormalHints(self.display, window as c_ulong, &mut size_hint, &mut tmp);
let min_size = if size_hint.flags & xlib::PMinSize == xlib::PMinSize {
Some((size_hint.min_width as u32, size_hint.min_height as u32))
} else {
None
};
let max_size = if size_hint.flags & xlib::PMaxSize == xlib::PMaxSize {
Some((size_hint.max_width as u32, size_hint.max_height as u32))
} else {
None
};
SizeHint { min_size: min_size, max_size: max_size }
}
}
fn restack_windows(&self, w: Vec<Window>) {
unsafe {
let mut windows = w.iter().map(|&x| x as c_ulong).collect::<Vec<_>>();
xlib::XRestackWindows(self.display, (&mut windows[..]).as_mut_ptr(), windows.len() as i32);
}
}
fn close_client(&self, window: Window) {
unsafe {
xlib::XKillClient(self.display, window as c_ulong);
}
}
fn kill_client(&self, window: Window) {
unsafe {
let wmdelete = self.get_atom("WM_DELETE_WINDOW");
let wmprotocols = self.get_atom("WM_PROTOCOLS");
let protocols = self.get_protocols(window);
debug!("supported protocols: {:?} (wmdelete = {:?})", protocols, wmdelete);
if protocols.iter().any(|&x| x == wmdelete) {
let mut data : xlib::ClientMessageData = uninitialized();
data.set_long(0, (wmdelete >> 32) as i64);
data.set_long(0, (wmdelete & 0xFFFFFFFF) as i64);
let mut event = xlib::XEvent::from(xlib::XClientMessageEvent {
type_: 33,
serial: 0,
send_event: 0,
display: null_mut(),
window: window as c_ulong,
message_type: wmprotocols as c_ulong,
format: 32,
data: data
});
xlib::XSendEvent(self.display, window as c_ulong, 0, 0, &mut event);
} else {
xlib::XKillClient(self.display, window as c_ulong);
}
}
}
fn update_server_state(&self, manager: &WindowManager) {
let i32_type = self.get_atom("32");
let current_desktop : i32 = manager.workspaces.current.workspace.id as i32;
let number_desktops : i32 = manager.workspaces.workspaces().len() as i32;
let window = manager.workspaces.peek();
let current_desktop_ptr : *const i32 = ¤t_desktop;
let number_desktops_ptr : *const i32 = &number_desktops;
unsafe {
xlib::XSelectInput(self.display, self.root, 0x1A0034);
xlib::XChangeProperty(self.display, self.root, self.get_atom("_NET_CURRENT_DESKTOP"), i32_type,
32, 0, current_desktop_ptr as *mut c_uchar, 1);
xlib::XChangeProperty(self.display, self.root, self.get_atom("_NET_NUMBER_OF_DESKTOPS"), i32_type,
32, 0, number_desktops_ptr as *mut c_uchar, 1);
if let Some(win) = window {
let win_ptr : *const u64 = &win;
xlib::XChangeProperty(self.display, self.root, self.get_atom("_NET_ACTIVE_WINDOW"), i32_type,
32, 0, win_ptr as *mut c_uchar, 2);
}
xlib::XSync(self.display, 0);
xlib::XSelectInput(self.display, self.root, 0x5A0034);
}
}
fn get_pointer(&self, window: Window) -> (u32, u32) {
let mut tmp_win : c_ulong = 0;
let mut x : c_int = 0;
let mut y : c_int = 0;
let mut tmp : c_int = 0;
let mut tmp2 : c_uint = 0;
unsafe {
xlib::XQueryPointer(self.display, window as c_ulong, &mut tmp_win, &mut tmp_win,
&mut x, &mut y, &mut tmp, &mut tmp, &mut tmp2);
}
(x as u32, y as u32)
}
fn warp_pointer(&self, window: Window, x: u32, y: u32) {
unsafe {
xlib::XWarpPointer(self.display, 0, window, 0, 0, 0, 0, x as i32, y as i32);
}
}
fn overrides_redirect(&self, window: Window) -> bool {
unsafe {
let mut attributes : xlib::XWindowAttributes = uninitialized();
xlib::XGetWindowAttributes(self.display, window as c_ulong, &mut attributes);
attributes.override_redirect != 0
}
}
fn process_message(&self, window_manager: &WindowManager, config: &GeneralConfig, window: Window, atom: c_ulong) -> WindowManager {
if atom == self.get_atom("_NET_CURRENT_DESKTOP") {
let prop = self.get_property(atom, window).unwrap();
window_manager.view(self, prop[0] as u32, config)
} else {
window_manager.clone()
}
}
}<|fim▁end|>
|
xlib::XSync(self.display, 0);
while xlib::XCheckMaskEvent(self.display, 0x40, &mut event) != 0 { }
}
}
|
<|file_name|>angular-sanitize.js<|end_file_name|><|fim▁begin|>/**
* @license AngularJS v1.5.9
* (c) 2010-2016 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular) {'use strict';
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $sanitizeMinErr = angular.$$minErr('$sanitize');
var bind;
var extend;
var forEach;
var isDefined;
var lowercase;
var noop;
var htmlParser;
var htmlSanitizeWriter;
/**
* @ngdoc module
* @name ngSanitize
* @description
*
* # ngSanitize
*
* The `ngSanitize` module provides functionality to sanitize HTML.
*
*
* <div doc-module-components="ngSanitize"></div>
*
* See {@link ngSanitize.$sanitize `$sanitize`} for usage.
*/
/**
* @ngdoc service
* @name $sanitize
* @kind function
*
* @description
* Sanitizes an html string by stripping all potentially dangerous tokens.
*
* The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
* then serialized back to properly escaped html string. This means that no unsafe input can make
* it into the returned string.
*
* The whitelist for URL sanitization of attribute values is configured using the functions
* `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider
* `$compileProvider`}.
*
* The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}.
*
* @param {string} html HTML input.
* @returns {string} Sanitized HTML.
*
* @example
<example module="sanitizeExample" deps="angular-sanitize.js" name="sanitize-service">
<file name="index.html">
<script>
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
}]);
</script>
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Directive</td>
<td>How</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="bind-html-with-sanitize">
<td>ng-bind-html</td>
<td>Automatically uses $sanitize</td>
<td><pre><div ng-bind-html="snippet"><br/></div></pre></td>
<td><div ng-bind-html="snippet"></div></td>
</tr>
<tr id="bind-html-with-trust">
<td>ng-bind-html</td>
<td>Bypass $sanitize by explicitly trusting the dangerous value</td>
<td>
<pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()">
</div></pre>
</td>
<td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
</tr>
<tr id="bind-default">
<td>ng-bind</td>
<td>Automatically escapes</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should sanitize the html snippet by default', function() {
expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should inline raw snippet if bound to a trusted value', function() {
expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should escape snippet without any filter', function() {
expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
toBe('new <b>text</b>');
expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe(
'new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe(
"new <b onclick=\"alert(1)\">text</b>");
});
</file>
</example>
*/
/**
* @ngdoc provider
* @name $sanitizeProvider
* @this
*
* @description
* Creates and configures {@link $sanitize} instance.
*/
function $SanitizeProvider() {
var svgEnabled = false;
this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
if (svgEnabled) {
extend(validElements, svgElements);
}
return function(html) {
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
return !/^unsafe:/.test($$sanitizeUri(uri, isImage));
}));
return buf.join('');
};
}];
/**
* @ngdoc method
* @name $sanitizeProvider#enableSvg
* @kind function
*
* @description
* Enables a subset of svg to be supported by the sanitizer.
*
* <div class="alert alert-warning">
* <p>By enabling this setting without taking other precautions, you might expose your
* application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned
* outside of the containing element and be rendered over other elements on the page (e.g. a login
* link). Such behavior can then result in phishing incidents.</p>
*
* <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg
* tags within the sanitized content:</p>
*
* <br>
*
* <pre><code>
* .rootOfTheIncludedContent svg {
* overflow: hidden !important;
* }
* </code></pre>
* </div>
*
* @param {boolean=} flag Enable or disable SVG support in the sanitizer.
* @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
* without an argument or self for chaining otherwise.
*/
this.enableSvg = function(enableSvg) {
if (isDefined(enableSvg)) {
svgEnabled = enableSvg;
return this;
} else {
return svgEnabled;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////
// Private stuff
//////////////////////////////////////////////////////////////////////////////////////////////////
bind = angular.bind;
extend = angular.extend;
forEach = angular.forEach;
isDefined = angular.isDefined;
lowercase = angular.lowercase;
noop = angular.noop;
htmlParser = htmlParserImpl;
htmlSanitizeWriter = htmlSanitizeWriterImpl;
// Regular Expressions for parsing tags and attributes
var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g;
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = toMap('area,br,col,hr,img,wbr');
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'),
optionalEndTagInlineElements = toMap('rp,rt'),
optionalEndTagElements = extend({},
optionalEndTagInlineElements,
optionalEndTagBlockElements);
// Safe Block Elements - HTML5<|fim▁hole|> 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul'));
// Inline Elements - HTML5
var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' +
'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' +
'samp,small,span,strike,strong,sub,sup,time,tt,u,var'));
// SVG Elements
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
// Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
// They can potentially allow for arbitrary javascript to be executed. See #11290
var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' +
'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' +
'radialGradient,rect,stop,svg,switch,text,title,tspan');
// Blocked Elements (will be stripped)
var blockedElements = toMap('script,style');
var validElements = extend({},
voidElements,
blockElements,
inlineElements,
optionalEndTagElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href');
var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
'valign,value,vspace,width');
// SVG attributes (without "id" and "name" attributes)
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);
var validAttrs = extend({},
uriAttrs,
svgAttrs,
htmlAttrs);
function toMap(str, lowercaseKeys) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) {
obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true;
}
return obj;
}
var inertBodyElement;
(function(window) {
var doc;
if (window.document && window.document.implementation) {
doc = window.document.implementation.createHTMLDocument('inert');
} else {
throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document');
}
var docElement = doc.documentElement || doc.getDocumentElement();
var bodyElements = docElement.getElementsByTagName('body');
// usually there should be only one body element in the document, but IE doesn't have any, so we need to create one
if (bodyElements.length === 1) {
inertBodyElement = bodyElements[0];
} else {
var html = doc.createElement('html');
inertBodyElement = doc.createElement('body');
html.appendChild(inertBodyElement);
doc.appendChild(html);
}
})(window);
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParserImpl(html, handler) {
if (html === null || html === undefined) {
html = '';
} else if (typeof html !== 'string') {
html = '' + html;
}
inertBodyElement.innerHTML = html;
//mXSS protection
var mXSSAttempts = 5;
do {
if (mXSSAttempts === 0) {
throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable');
}
mXSSAttempts--;
// strip custom-namespaced attributes on IE<=11
if (window.document.documentMode) {
stripCustomNsAttrs(inertBodyElement);
}
html = inertBodyElement.innerHTML; //trigger mXSS
inertBodyElement.innerHTML = html;
} while (html !== inertBodyElement.innerHTML);
var node = inertBodyElement.firstChild;
while (node) {
switch (node.nodeType) {
case 1: // ELEMENT_NODE
handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes));
break;
case 3: // TEXT NODE
handler.chars(node.textContent);
break;
}
var nextNode;
if (!(nextNode = node.firstChild)) {
if (node.nodeType === 1) {
handler.end(node.nodeName.toLowerCase());
}
nextNode = node.nextSibling;
if (!nextNode) {
while (nextNode == null) {
node = node.parentNode;
if (node === inertBodyElement) break;
nextNode = node.nextSibling;
if (node.nodeType === 1) {
handler.end(node.nodeName.toLowerCase());
}
}
}
}
node = nextNode;
}
while ((node = inertBodyElement.firstChild)) {
inertBodyElement.removeChild(node);
}
}
function attrToMap(attrs) {
var map = {};
for (var i = 0, ii = attrs.length; i < ii; i++) {
var attr = attrs[i];
map[attr.name] = attr.value;
}
return map;
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns {string} escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(SURROGATE_PAIR_REGEXP, function(value) {
var hi = value.charCodeAt(0);
var low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(NON_ALPHANUMERIC_REGEXP, function(value) {
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.join('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriterImpl(buf, uriValidator) {
var ignoreCurrentElement = false;
var out = bind(buf, buf.push);
return {
start: function(tag, attrs) {
tag = lowercase(tag);
if (!ignoreCurrentElement && blockedElements[tag]) {
ignoreCurrentElement = tag;
}
if (!ignoreCurrentElement && validElements[tag] === true) {
out('<');
out(tag);
forEach(attrs, function(value, key) {
var lkey = lowercase(key);
var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
if (validAttrs[lkey] === true &&
(uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out('>');
}
},
end: function(tag) {
tag = lowercase(tag);
if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
out('</');
out(tag);
out('>');
}
// eslint-disable-next-line eqeqeq
if (tag == ignoreCurrentElement) {
ignoreCurrentElement = false;
}
},
chars: function(chars) {
if (!ignoreCurrentElement) {
out(encodeEntities(chars));
}
}
};
}
/**
* When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare
* ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want
* to allow any of these custom attributes. This method strips them all.
*
* @param node Root element to process
*/
function stripCustomNsAttrs(node) {
if (node.nodeType === window.Node.ELEMENT_NODE) {
var attrs = node.attributes;
for (var i = 0, l = attrs.length; i < l; i++) {
var attrNode = attrs[i];
var attrName = attrNode.name.toLowerCase();
if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) {
node.removeAttributeNode(attrNode);
i--;
l--;
}
}
}
var nextNode = node.firstChild;
if (nextNode) {
stripCustomNsAttrs(nextNode);
}
nextNode = node.nextSibling;
if (nextNode) {
stripCustomNsAttrs(nextNode);
}
}
}
function sanitizeText(chars) {
var buf = [];
var writer = htmlSanitizeWriter(buf, noop);
writer.chars(chars);
return buf.join('');
}
// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
/**
* @ngdoc filter
* @name linky
* @kind function
*
* @description
* Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
* plain email address links.
*
* Requires the {@link ngSanitize `ngSanitize`} module to be installed.
*
* @param {string} text Input text.
* @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in.
* @param {object|function(url)} [attributes] Add custom attributes to the link element.
*
* Can be one of:
*
* - `object`: A map of attributes
* - `function`: Takes the url as a parameter and returns a map of attributes
*
* If the map of attributes contains a value for `target`, it overrides the value of
* the target parameter.
*
*
* @returns {string} Html-linkified and {@link $sanitize sanitized} text.
*
* @usage
<span ng-bind-html="linky_expression | linky"></span>
*
* @example
<example module="linkyExample" deps="angular-sanitize.js" name="linky-filter">
<file name="index.html">
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<th>Filter</th>
<th>Source</th>
<th>Rendered</th>
</tr>
<tr id="linky-filter">
<td>linky filter</td>
<td>
<pre><div ng-bind-html="snippet | linky"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippet | linky"></div>
</td>
</tr>
<tr id="linky-target">
<td>linky target</td>
<td>
<pre><div ng-bind-html="snippetWithSingleURL | linky:'_blank'"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div>
</td>
</tr>
<tr id="linky-custom-attributes">
<td>linky custom attributes</td>
<td>
<pre><div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</file>
<file name="script.js">
angular.module('linkyExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.snippet =
'Pretty text with some links:\n' +
'http://angularjs.org/,\n' +
'mailto:[email protected],\n' +
'[email protected],\n' +
'and one more: ftp://127.0.0.1/.';
$scope.snippetWithSingleURL = 'http://angularjs.org/';
}]);
</file>
<file name="protractor.js" type="protractor">
it('should linkify the snippet with urls', function() {
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, [email protected], ' +
'[email protected], and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
});
it('should not linkify snippet without the linky filter', function() {
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, mailto:[email protected], ' +
'[email protected], and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new http://link.');
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('new http://link.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
.toBe('new http://link.');
});
it('should work with the target property', function() {
expect(element(by.id('linky-target')).
element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
toBe('http://angularjs.org/');
expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
});
it('should optionally add custom attributes', function() {
expect(element(by.id('linky-custom-attributes')).
element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
toBe('http://angularjs.org/');
expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
});
</file>
</example>
*/
angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
var LINKY_URL_REGEXP =
/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
MAILTO_REGEXP = /^mailto:/i;
var linkyMinErr = angular.$$minErr('linky');
var isDefined = angular.isDefined;
var isFunction = angular.isFunction;
var isObject = angular.isObject;
var isString = angular.isString;
return function(text, target, attributes) {
if (text == null || text === '') return text;
if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text);
var attributesFn =
isFunction(attributes) ? attributes :
isObject(attributes) ? function getAttributesObject() {return attributes;} :
function getEmptyAttributesObject() {return {};};
var match;
var raw = text;
var html = [];
var url;
var i;
while ((match = raw.match(LINKY_URL_REGEXP))) {
// We can not end in these as they are sometimes found at the end of the sentence
url = match[0];
// if we did not match ftp/http/www/mailto then assume mailto
if (!match[2] && !match[4]) {
url = (match[3] ? 'http://' : 'mailto:') + url;
}
i = match.index;
addText(raw.substr(0, i));
addLink(url, match[0].replace(MAILTO_REGEXP, ''));
raw = raw.substring(i + match[0].length);
}
addText(raw);
return $sanitize(html.join(''));
function addText(text) {
if (!text) {
return;
}
html.push(sanitizeText(text));
}
function addLink(url, text) {
var key, linkAttributes = attributesFn(url);
html.push('<a ');
for (key in linkAttributes) {
html.push(key + '="' + linkAttributes[key] + '" ');
}
if (isDefined(target) && !('target' in linkAttributes)) {
html.push('target="',
target,
'" ');
}
html.push('href="',
url.replace(/"/g, '"'),
'">');
addText(text);
html.push('</a>');
}
};
}]);
})(window, window.angular);<|fim▁end|>
|
var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' +
|
<|file_name|>Parameters.go<|end_file_name|><|fim▁begin|>package HologramGo
type Parameters struct {
items []string
values []string<|fim▁hole|><|fim▁end|>
|
}
|
<|file_name|>replication_helper_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008 Jan lehnardt <[email protected]>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Simple functional test for the replication notification trigger"""
import time
from couchdb import client
def set_up_database(server, database):
"""Deletes and creates a `database` on a `server`"""<|fim▁hole|>
return server.create(database)
def run_tests():
"""Inserts a doc into database a, waits and tries to read it back from
database b
"""
# set things up
database = 'replication_notification_test'
server_a = client.Server('http://localhost:5984')
server_b = client.Server('http://localhost:5985')
# server_c = client.Server('http://localhost:5986')
db_a = set_up_database(server_a, database)
db_b = set_up_database(server_b, database)
# db_c = set_up_database(server_c, database)
doc = {'jan':'cool'}
docId = 'testdoc'
# add doc to node a
print 'Inserting document in to database "a"'
db_a[docId] = doc
# wait a bit. Adjust depending on your --wait-threshold setting
time.sleep(5)
# read doc from node b and compare to a
try:
db_b[docId] == db_a[docId] # == db_c[docId]
print 'SUCCESS at reading it back from database "b"'
except client.ResourceNotFound:
print 'FAILURE at reading it back from database "b"'
def main():
print 'Running functional replication test...'
run_tests()
print 'Done.'
if __name__ == '__main__':
main()<|fim▁end|>
|
if database in server:
del server[database]
|
<|file_name|>HttpSession.java<|end_file_name|><|fim▁begin|>package jdt.mantis.appmanager;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;<|fim▁hole|>import java.util.List;
public class HttpSession {
private CloseableHttpClient httpclient;
private ApplicationManager app;
public HttpSession(ApplicationManager app) {
//powstaje nowa sesja
this.app = app;
//powstaje nowy klient (sesja) do pracy po protokole http, objekt wysyłający zapotrzebowania na serwer
httpclient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
}
public boolean login(String username, String password) throws IOException {
//adres na jajki wysylane jest zapytanie
HttpPost post = new HttpPost(app.getProperty("web.baseUrl") + "login.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
//inicjalizacja zbioru parametrow
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("secure_session", "on"));
params.add(new BasicNameValuePair("return", "index.php"));
//parametry zapakowują się zgodnie z określonymi zasadami i lokują się we wczesniej strworzone zapytanie
post.setEntity(new UrlEncodedFormEntity(params));
//wysyłka zapytania httpclient.execute(post) a wynikiem jest odp od serwera
CloseableHttpResponse response = httpclient.execute(post);
//Analizujemy odp od serwera
String body = getTextFrom(response);
//sprawdzanie czy uzytkownik sie zalogowal, czy kod strony zawiera taka linijke
return body.contains(String.format("<span class=\"user-info\">%s</span>", username));
}
//metoda do otrzymywania tekstu z odp serwera
private String getTextFrom(CloseableHttpResponse response) throws IOException {
try {
return EntityUtils.toString(response.getEntity());
} finally {
response.close();
}
}
//jaki uzytkownik jest teraz zalogowany
public boolean isLoggedInAs(String username) throws IOException {
//wchodzimy na strone glowna
HttpGet get = new HttpGet(app.getProperty("web.baseUrl") + "/index.php");
// wykonujemy zapytanie i otzymujemy odpowiedz
CloseableHttpResponse response = httpclient.execute(get);
String body = getTextFrom(response);
return body.contains(String.format("<span class=\"user-info\">%s</span>", username));
}
}<|fim▁end|>
|
import java.io.IOException;
import java.util.ArrayList;
|
<|file_name|>fvtk.py<|end_file_name|><|fim▁begin|>''' Fvtk module implements simple visualization functions using VTK.
The main idea is the following:
A window can have one or more renderers. A renderer can have none, one or more actors. Examples of actors are a sphere, line, point etc.
You basically add actors in a renderer and in that way you can visualize the forementioned objects e.g. sphere, line ...
Examples
---------
>>> from dipy.viz import fvtk
>>> r=fvtk.ren()
>>> a=fvtk.axes()
>>> fvtk.add(r,a)
>>> #fvtk.show(r)
For more information on VTK there many neat examples in
http://www.vtk.org/Wiki/VTK/Tutorials/External_Tutorials
'''
from __future__ import division, print_function, absolute_import
from dipy.utils.six.moves import xrange
import types
import numpy as np
from dipy.core.ndindex import ndindex
# Conditional import machinery for vtk
from ..utils.optpkg import optional_package
# Allow import, but disable doctests if we don't have vtk
vtk, have_vtk, setup_module = optional_package('vtk')
colors, have_vtk_colors, _ = optional_package('vtk.util.colors')
cm, have_matplotlib, _ = optional_package('matplotlib.cm')
if have_matplotlib:
get_cmap = cm.get_cmap
else:
from dipy.data import get_cmap
# a track buffer used only with picking tracks
track_buffer = []
# indices buffer for the tracks
ind_buffer = []
# tempory renderer used only with picking tracks
tmp_ren = None
if have_vtk:
major_version = vtk.vtkVersion.GetVTKMajorVersion()
# Create a text mapper and actor to display the results of picking.
textMapper = vtk.vtkTextMapper()
tprop = textMapper.GetTextProperty()
tprop.SetFontFamilyToArial()
tprop.SetFontSize(10)
# tprop.BoldOn()
# tprop.ShadowOn()
tprop.SetColor(1, 0, 0)
textActor = vtk.vtkActor2D()
textActor.VisibilityOff()
textActor.SetMapper(textMapper)
# Create a cell picker.
picker = vtk.vtkCellPicker()
def ren():
'''Create a renderer.
Returns
-------
v : vtkRenderer() object
Renderer.
Examples
--------
>>> from dipy.viz import fvtk
>>> import numpy as np
>>> r=fvtk.ren()
>>> lines=[np.random.rand(10,3)]
>>> c=fvtk.line(lines, fvtk.colors.red)
>>> fvtk.add(r,c)
>>> #fvtk.show(r)
'''
return vtk.vtkRenderer()
def add(ren, a):
''' Add a specific actor
'''
if isinstance(a, vtk.vtkVolume):
ren.AddVolume(a)
else:
ren.AddActor(a)
def rm(ren, a):
''' Remove a specific actor
'''
ren.RemoveActor(a)
def clear(ren):
''' Remove all actors from the renderer
'''
ren.RemoveAllViewProps()
def rm_all(ren):
''' Remove all actors from the renderer
'''
clear(ren)
def _arrow(pos=(0, 0, 0), color=(1, 0, 0), scale=(1, 1, 1), opacity=1):
''' Internal function for generating arrow actors.
'''
arrow = vtk.vtkArrowSource()
# arrow.SetTipLength(length)
arrowm = vtk.vtkPolyDataMapper()
if major_version <= 5:
arrowm.SetInput(arrow.GetOutput())
else:
arrowm.SetInputData(arrow.GetOutput())
arrowa = vtk.vtkActor()
arrowa.SetMapper(arrowm)
arrowa.GetProperty().SetColor(color)
arrowa.GetProperty().SetOpacity(opacity)
arrowa.SetScale(scale)
return arrowa
def axes(scale=(1, 1, 1), colorx=(1, 0, 0), colory=(0, 1, 0), colorz=(0, 0, 1),
opacity=1):
""" Create an actor with the coordinate's system axes where
red = x, green = y, blue =z.
Parameters
----------
scale : tuple (3,)
axes size e.g. (100, 100, 100)
colorx : tuple (3,)
x-axis color. Default red.
colory : tuple (3,)
y-axis color. Default blue.
colorz : tuple (3,)
z-axis color. Default green.
Returns
-------
vtkAssembly
"""
arrowx = _arrow(color=colorx, scale=scale, opacity=opacity)
arrowy = _arrow(color=colory, scale=scale, opacity=opacity)
arrowz = _arrow(color=colorz, scale=scale, opacity=opacity)
arrowy.RotateZ(90)
arrowz.RotateY(-90)
ass = vtk.vtkAssembly()
ass.AddPart(arrowx)
ass.AddPart(arrowy)
ass.AddPart(arrowz)
return ass
def _lookup(colors):
''' Internal function
Creates a lookup table with given colors.
Parameters
------------
colors : array, shape (N,3)
Colormap where every triplet is encoding red, green and blue e.g.
::
r1,g1,b1
r2,g2,b2
...
rN,gN,bN
where
::
0=<r<=1,
0=<g<=1,
0=<b<=1,
Returns
----------
vtkLookupTable
'''
colors = np.asarray(colors, dtype=np.float32)
if colors.ndim > 2:
raise ValueError('Incorrect shape of array in colors')
if colors.ndim == 1:
N = 1
if colors.ndim == 2:
N = colors.shape[0]
lut = vtk.vtkLookupTable()
lut.SetNumberOfColors(N)
lut.Build()
if colors.ndim == 2:
scalar = 0
for (r, g, b) in colors:
lut.SetTableValue(scalar, r, g, b, 1.0)
scalar += 1
if colors.ndim == 1:
lut.SetTableValue(0, colors[0], colors[1], colors[2], 1.0)
return lut
def streamtube(lines, colors, opacity=1, linewidth=0.15, tube_sides=8,
lod=True, lod_points=10 ** 4, lod_points_size=5):
""" Uses streamtubes to visualize polylines
Parameters
----------
lines : list
list of N curves represented as 2D ndarrays
colors : array (N, 3) or tuple (3,)
opacity : float
linewidth : float
tube_sides : int
lod : bool
use vtkLODActor rather than vtkActor
lod_points : int
number of points to be used when LOD is in effect
lod_points_size : int
size of points when lod is in effect
Examples
--------
>>> from dipy.viz import fvtk
>>> r=fvtk.ren()
>>> lines=[np.random.rand(10, 3), np.random.rand(20, 3)]
>>> colors=np.random.rand(2, 3)
>>> c=fvtk.streamtube(lines, colors)
>>> fvtk.add(r,c)
>>> #fvtk.show(r)
Notes
-----
Streamtubes can be heavy on GPU when loading many streamlines and therefore,
you may experience slow rendering time depending on system GPU. A solution
to this problem is to reduce the number of points in each streamline. In Dipy
we provide an algorithm that will reduce the number of points on the straighter
parts of the streamline but keep more points on the curvier parts. This can
be used in the following way
from dipy.tracking.distances import approx_polygon_track
lines = [approx_polygon_track(line, 0.2) for line in lines]
"""
points = vtk.vtkPoints()
colors = np.asarray(colors)
if colors.ndim == 1:
colors = np.tile(colors, (len(lines), 1))
# Create the polyline.
streamlines = vtk.vtkCellArray()
cols = vtk.vtkUnsignedCharArray()
cols.SetName("Cols")
cols.SetNumberOfComponents(3)
len_lines = len(lines)
prior_line_shape = 0
for i in range(len_lines):
line = lines[i]
streamlines.InsertNextCell(line.shape[0])
for j in range(line.shape[0]):
points.InsertNextPoint(*line[j])
streamlines.InsertCellPoint(j + prior_line_shape)
color = (255 * colors[i]).astype('ubyte')
cols.InsertNextTuple3(*color)
prior_line_shape += line.shape[0]
profileData = vtk.vtkPolyData()
profileData.SetPoints(points)
profileData.SetLines(streamlines)
profileData.GetPointData().AddArray(cols)
# Add thickness to the resulting line.
profileTubes = vtk.vtkTubeFilter()
profileTubes.SetNumberOfSides(tube_sides)
if major_version <= 5:
profileTubes.SetInput(profileData)
else:
profileTubes.SetInputData(profileData)
#profileTubes.SetInput(profileData)
profileTubes.SetRadius(linewidth)
profileMapper = vtk.vtkPolyDataMapper()
profileMapper.SetInputConnection(profileTubes.GetOutputPort())
profileMapper.ScalarVisibilityOn()
profileMapper.SetScalarModeToUsePointFieldData()
profileMapper.SelectColorArray("Cols")
profileMapper.GlobalImmediateModeRenderingOn()
if lod:
profile = vtk.vtkLODActor()
profile.SetNumberOfCloudPoints(lod_points)
profile.GetProperty().SetPointSize(lod_points_size)
else:
profile = vtk.vtkActor()
profile.SetMapper(profileMapper)
profile.GetProperty().SetAmbient(0) # .3
profile.GetProperty().SetSpecular(0) # .3
profile.GetProperty().SetSpecularPower(10)
profile.GetProperty().SetInterpolationToGouraud()
profile.GetProperty().BackfaceCullingOn()
profile.GetProperty().SetOpacity(opacity)
return profile
def line(lines, colors, opacity=1, linewidth=1):
''' Create an actor for one or more lines.
Parameters
------------
lines : list of arrays representing lines as 3d points for example
lines=[np.random.rand(10,3),np.random.rand(20,3)]
represents 2 lines the first with 10 points and the second with 20 points in x,y,z coordinates.
colors : array, shape (N,3)
Colormap where every triplet is encoding red, green and blue e.g.
::
r1,g1,b1
r2,g2,b2
...
rN,gN,bN
where
::
0=<r<=1,
0=<g<=1,
0=<b<=1
opacity : float, optional
``0 <= transparency <= 1``
linewidth : float, optional
Line thickness.
Returns
----------
v : vtkActor object
Line.
Examples
----------
>>> from dipy.viz import fvtk
>>> r=fvtk.ren()
>>> lines=[np.random.rand(10,3), np.random.rand(20,3)]
>>> colors=np.random.rand(2,3)
>>> c=fvtk.line(lines, colors)
>>> fvtk.add(r,c)
>>> #fvtk.show(r)
'''
if not isinstance(lines, types.ListType):
lines = [lines]
points = vtk.vtkPoints()
lines_ = vtk.vtkCellArray()
linescalars = vtk.vtkFloatArray()
# lookuptable=vtk.vtkLookupTable()
lookuptable = _lookup(colors)
scalarmin = 0
colors = np.asarray(colors)
if colors.ndim == 2:
scalarmax = colors.shape[0] - 1
if colors.ndim == 1:
scalarmax = 0
curPointID = 0
m = (0.0, 0.0, 0.0)
n = (1.0, 0.0, 0.0)
scalar = 0
# many colors
if colors.ndim == 2:
for Line in lines:
inw = True
mit = iter(Line)
nit = iter(Line)
next(nit)
while(inw):
try:
m = next(mit)
n = next(nit)
# scalar=sp.rand(1)
linescalars.SetNumberOfComponents(1)
points.InsertNextPoint(m)
linescalars.InsertNextTuple1(scalar)
points.InsertNextPoint(n)
linescalars.InsertNextTuple1(scalar)
lines_.InsertNextCell(2)
lines_.InsertCellPoint(curPointID)
lines_.InsertCellPoint(curPointID + 1)
curPointID += 2
except StopIteration:
break
scalar += 1
# one color only
if colors.ndim == 1:
for Line in lines:
inw = True
mit = iter(Line)
nit = iter(Line)
next(nit)
while(inw):
try:
m = next(mit)
n = next(nit)
# scalar=sp.rand(1)
linescalars.SetNumberOfComponents(1)
points.InsertNextPoint(m)
linescalars.InsertNextTuple1(scalar)
points.InsertNextPoint(n)
linescalars.InsertNextTuple1(scalar)
lines_.InsertNextCell(2)
lines_.InsertCellPoint(curPointID)
lines_.InsertCellPoint(curPointID + 1)
curPointID += 2
except StopIteration:
break
polydata = vtk.vtkPolyData()
polydata.SetPoints(points)
polydata.SetLines(lines_)
polydata.GetPointData().SetScalars(linescalars)
mapper = vtk.vtkPolyDataMapper()
if major_version <= 5:
mapper.SetInput(polydata)
else:
mapper.SetInputData(polydata)
mapper.SetLookupTable(lookuptable)
mapper.SetColorModeToMapScalars()
mapper.SetScalarRange(scalarmin, scalarmax)
mapper.SetScalarModeToUsePointData()
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetLineWidth(linewidth)
actor.GetProperty().SetOpacity(opacity)
return actor
def dots(points, color=(1, 0, 0), opacity=1, dot_size=5):
""" Create one or more 3d points
Parameters
----------
points : ndarray, (N, 3)
color : tuple (3,)
opacity : float
dot_size : int
Returns
--------
vtkActor
See Also
---------
dipy.viz.fvtk.point
"""
if points.ndim == 2:
points_no = points.shape[0]
else:
points_no = 1
polyVertexPoints = vtk.vtkPoints()
polyVertexPoints.SetNumberOfPoints(points_no)
aPolyVertex = vtk.vtkPolyVertex()
aPolyVertex.GetPointIds().SetNumberOfIds(points_no)
cnt = 0
if points.ndim > 1:
for point in points:
polyVertexPoints.InsertPoint(cnt, point[0], point[1], point[2])
aPolyVertex.GetPointIds().SetId(cnt, cnt)
cnt += 1
else:
polyVertexPoints.InsertPoint(cnt, points[0], points[1], points[2])
aPolyVertex.GetPointIds().SetId(cnt, cnt)
cnt += 1
aPolyVertexGrid = vtk.vtkUnstructuredGrid()
aPolyVertexGrid.Allocate(1, 1)
aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(),
aPolyVertex.GetPointIds())
aPolyVertexGrid.SetPoints(polyVertexPoints)
aPolyVertexMapper = vtk.vtkDataSetMapper()
if major_version <= 5:
aPolyVertexMapper.SetInput(aPolyVertexGrid)
else:
aPolyVertexMapper.SetInputData(aPolyVertexGrid)
aPolyVertexActor = vtk.vtkActor()
aPolyVertexActor.SetMapper(aPolyVertexMapper)
aPolyVertexActor.GetProperty().SetColor(color)
aPolyVertexActor.GetProperty().SetOpacity(opacity)
aPolyVertexActor.GetProperty().SetPointSize(dot_size)
return aPolyVertexActor
def point(points, colors, opacity=1, point_radius=0.1, theta=8, phi=8):
""" Visualize points as sphere glyphs
Parameters
----------
points : ndarray, shape (N, 3)
colors : ndarray (N,3) or tuple (3,)
point_radius : float
theta : int
phi : int
Returns
-------
vtkActor
Examples
--------
>>> from dipy.viz import fvtk
>>> ren = fvtk.ren()
>>> pts = np.random.rand(5, 3)
>>> point_actor = fvtk.point(pts, fvtk.colors.coral)
>>> fvtk.add(ren, point_actor)
>>> #fvtk.show(ren)
"""
if np.array(colors).ndim == 1:
# return dots(points,colors,opacity)
colors = np.tile(colors, (len(points), 1))
scalars = vtk.vtkUnsignedCharArray()
scalars.SetNumberOfComponents(3)
pts = vtk.vtkPoints()
cnt_colors = 0
for p in points:
pts.InsertNextPoint(p[0], p[1], p[2])
scalars.InsertNextTuple3(
round(255 * colors[cnt_colors][0]), round(255 * colors[cnt_colors][1]), round(255 * colors[cnt_colors][2]))
cnt_colors += 1
src = vtk.vtkSphereSource()
src.SetRadius(point_radius)
src.SetThetaResolution(theta)
src.SetPhiResolution(phi)
polyData = vtk.vtkPolyData()
polyData.SetPoints(pts)
polyData.GetPointData().SetScalars(scalars)
glyph = vtk.vtkGlyph3D()
glyph.SetSourceConnection(src.GetOutputPort())
if major_version <= 5:
glyph.SetInput(polyData)
else:
glyph.SetInputData(polyData)
glyph.SetColorModeToColorByScalar()
glyph.SetScaleModeToDataScalingOff()
mapper = vtk.vtkPolyDataMapper()
if major_version <= 5:
mapper.SetInput(glyph.GetOutput())
else:
mapper.SetInputData(glyph.GetOutput())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetOpacity(opacity)
return actor
def label(ren, text='Origin', pos=(0, 0, 0), scale=(0.2, 0.2, 0.2),
color=(1, 1, 1)):
''' Create a label actor.
This actor will always face the camera
Parameters
----------
ren : vtkRenderer() object
Renderer as returned by ``ren()``.
text : str
Text for the label.
pos : (3,) array_like, optional
Left down position of the label.
scale : (3,) array_like
Changes the size of the label.
color : (3,) array_like
Label color as ``(r,g,b)`` tuple.
Returns
-------
l : vtkActor object
Label.
Examples
--------
>>> from dipy.viz import fvtk
>>> r=fvtk.ren()
>>> l=fvtk.label(r)
>>> fvtk.add(r,l)
>>> #fvtk.show(r)
'''
atext = vtk.vtkVectorText()
atext.SetText(text)
textm = vtk.vtkPolyDataMapper()
if major_version <= 5:
textm.SetInput(atext.GetOutput())
else:
textm.SetInputData(atext.GetOutput())
texta = vtk.vtkFollower()
texta.SetMapper(textm)
texta.SetScale(scale)
texta.GetProperty().SetColor(color)
texta.SetPosition(pos)
ren.AddActor(texta)
texta.SetCamera(ren.GetActiveCamera())
return texta
def volume(vol, voxsz=(1.0, 1.0, 1.0), affine=None, center_origin=1,
info=0, maptype=0, trilinear=1, iso=0, iso_thr=100,
opacitymap=None, colormap=None):
''' Create a volume and return a volumetric actor using volumetric
rendering.
This function has many different interesting capabilities. The maptype,
opacitymap and colormap are the most crucial parameters here.
Parameters
----------
vol : array, shape (N, M, K), dtype uint8
An array representing the volumetric dataset that we want to visualize
using volumetric rendering.
voxsz : (3,) array_like
Voxel size.
affine : (4, 4) ndarray
As given by volumeimages.
center_origin : int {0,1}
It considers that the center of the volume is the
point ``(-vol.shape[0]/2.0+0.5,-vol.shape[1]/2.0+0.5,-vol.shape[2]/2.0+0.5)``.
info : int {0,1}
If 1 it prints out some info about the volume, the method and the
dataset.
trilinear : int {0,1}
Use trilinear interpolation, default 1, gives smoother rendering. If
you want faster interpolation use 0 (Nearest).
maptype : int {0,1}
The maptype is a very important parameter which affects the raycasting algorithm in use for the rendering.
The options are:
If 0 then vtkVolumeTextureMapper2D is used.
If 1 then vtkVolumeRayCastFunction is used.
iso : int {0,1}
If iso is 1 and maptype is 1 then we use
``vtkVolumeRayCastIsosurfaceFunction`` which generates an isosurface at
the predefined iso_thr value. If iso is 0 and maptype is 1
``vtkVolumeRayCastCompositeFunction`` is used.
iso_thr : int
If iso is 1 then then this threshold in the volume defines the value
which will be used to create the isosurface.
opacitymap : (2, 2) ndarray
The opacity map assigns a transparency coefficient to every point in
the volume. The default value uses the histogram of the volume to
calculate the opacitymap.
colormap : (4, 4) ndarray
The color map assigns a color value to every point in the volume.
When None from the histogram it uses a red-blue colormap.
Returns
-------
v : vtkVolume
Volume.
Notes
--------
What is the difference between TextureMapper2D and RayCastFunction? Coming
soon... See VTK user's guide [book] & The Visualization Toolkit [book] and
VTK's online documentation & online docs.
What is the difference between RayCastIsosurfaceFunction and
RayCastCompositeFunction? Coming soon... See VTK user's guide [book] &
The Visualization Toolkit [book] and VTK's online documentation &
online docs.
What about trilinear interpolation?
Coming soon... well when time permits really ... :-)
Examples
--------
First example random points.
>>> from dipy.viz import fvtk
>>> import numpy as np
>>> vol=100*np.random.rand(100,100,100)
>>> vol=vol.astype('uint8')
>>> vol.min(), vol.max()
(0, 99)
>>> r = fvtk.ren()
>>> v = fvtk.volume(vol)
>>> fvtk.add(r,v)
>>> #fvtk.show(r)
Second example with a more complicated function
>>> from dipy.viz import fvtk
>>> import numpy as np
>>> x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
>>> s = np.sin(x*y*z)/(x*y*z)
>>> r = fvtk.ren()
>>> v = fvtk.volume(s)
>>> fvtk.add(r,v)
>>> #fvtk.show(r)
If you find this function too complicated you can always use mayavi.
Please do not forget to use the -wthread switch in ipython if you are
running mayavi.
from enthought.mayavi import mlab
import numpy as np
x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
s = np.sin(x*y*z)/(x*y*z)
mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
mlab.show()
More mayavi demos are available here:
http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html
'''
if vol.ndim != 3:
raise ValueError('3d numpy arrays only please')
if info:
print('Datatype', vol.dtype, 'converted to uint8')
vol = np.interp(vol, [vol.min(), vol.max()], [0, 255])
vol = vol.astype('uint8')
if opacitymap is None:
bin, res = np.histogram(vol.ravel())
res2 = np.interp(res, [vol.min(), vol.max()], [0, 1])
opacitymap = np.vstack((res, res2)).T
opacitymap = opacitymap.astype('float32')
'''
opacitymap=np.array([[ 0.0, 0.0],
[50.0, 0.9]])
'''
if info:
print('opacitymap', opacitymap)
if colormap is None:
bin, res = np.histogram(vol.ravel())
res2 = np.interp(res, [vol.min(), vol.max()], [0, 1])
zer = np.zeros(res2.shape)
colormap = np.vstack((res, res2, zer, res2[::-1])).T
colormap = colormap.astype('float32')
'''
colormap=np.array([[0.0, 0.5, 0.0, 0.0],
[64.0, 1.0, 0.5, 0.5],
[128.0, 0.9, 0.2, 0.3],
[196.0, 0.81, 0.27, 0.1],
[255.0, 0.5, 0.5, 0.5]])
'''
if info:
print('colormap', colormap)
im = vtk.vtkImageData()
if major_version <= 5:
im.SetScalarTypeToUnsignedChar()
im.SetDimensions(vol.shape[0], vol.shape[1], vol.shape[2])
# im.SetOrigin(0,0,0)
# im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])
if major_version <= 5:
im.AllocateScalars()
else:
im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 3)
for i in range(vol.shape[0]):
for j in range(vol.shape[1]):
for k in range(vol.shape[2]):
im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])
if affine is not None:
aff = vtk.vtkMatrix4x4()
aff.DeepCopy((affine[0, 0], affine[0, 1], affine[0, 2], affine[0, 3], affine[1, 0], affine[1, 1], affine[1, 2], affine[1, 3], affine[2, 0], affine[
2, 1], affine[2, 2], affine[2, 3], affine[3, 0], affine[3, 1], affine[3, 2], affine[3, 3]))
# aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],0,affine[1,0],affine[1,1],affine[1,2],0,affine[2,0],affine[2,1],affine[2,2],0,affine[3,0],affine[3,1],affine[3,2],1))
# aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],127.5,affine[1,0],affine[1,1],affine[1,2],-127.5,affine[2,0],affine[2,1],affine[2,2],-127.5,affine[3,0],affine[3,1],affine[3,2],1))
reslice = vtk.vtkImageReslice()
if major_version <= 5:
reslice.SetInput(im)
else:
reslice.SetInputData(im)
# reslice.SetOutputDimensionality(2)
# reslice.SetOutputOrigin(127,-145,147)
reslice.SetResliceAxes(aff)
# reslice.SetOutputOrigin(-127,-127,-127)
# reslice.SetOutputExtent(-127,128,-127,128,-127,128)
# reslice.SetResliceAxesOrigin(0,0,0)
# print 'Get Reslice Axes Origin ', reslice.GetResliceAxesOrigin()
# reslice.SetOutputSpacing(1.0,1.0,1.0)
reslice.SetInterpolationModeToLinear()
# reslice.UpdateWholeExtent()
# print 'reslice GetOutputOrigin', reslice.GetOutputOrigin()
# print 'reslice GetOutputExtent',reslice.GetOutputExtent()
# print 'reslice GetOutputSpacing',reslice.GetOutputSpacing()
changeFilter = vtk.vtkImageChangeInformation()
if major_version <= 5:
changeFilter.SetInput(reslice.GetOutput())
else:
changeFilter.SetInputData(reslice.GetOutput())
# changeFilter.SetInput(im)
if center_origin:
changeFilter.SetOutputOrigin(
-vol.shape[0] / 2.0 + 0.5, -vol.shape[1] / 2.0 + 0.5, -vol.shape[2] / 2.0 + 0.5)
print('ChangeFilter ', changeFilter.GetOutputOrigin())
opacity = vtk.vtkPiecewiseFunction()
for i in range(opacitymap.shape[0]):
opacity.AddPoint(opacitymap[i, 0], opacitymap[i, 1])
color = vtk.vtkColorTransferFunction()
for i in range(colormap.shape[0]):
color.AddRGBPoint(
colormap[i, 0], colormap[i, 1], colormap[i, 2], colormap[i, 3])
if(maptype == 0):
property = vtk.vtkVolumeProperty()
property.SetColor(color)
property.SetScalarOpacity(opacity)
if trilinear:
property.SetInterpolationTypeToLinear()
else:
property.SetInterpolationTypeToNearest()
if info:
print('mapper VolumeTextureMapper2D')
mapper = vtk.vtkVolumeTextureMapper2D()
if affine is None:
if major_version <= 5:
mapper.SetInput(im)
else:
mapper.SetInputData(im)
else:
if major_version <= 5:
mapper.SetInput(changeFilter.GetOutput())
else:
mapper.SetInputData(changeFilter.GetOutput())
if (maptype == 1):
property = vtk.vtkVolumeProperty()
property.SetColor(color)
property.SetScalarOpacity(opacity)
property.ShadeOn()
if trilinear:
property.SetInterpolationTypeToLinear()
else:
property.SetInterpolationTypeToNearest()
if iso:
isofunc = vtk.vtkVolumeRayCastIsosurfaceFunction()
isofunc.SetIsoValue(iso_thr)
else:<|fim▁hole|> if info:
print('mapper VolumeRayCastMapper')
mapper = vtk.vtkVolumeRayCastMapper()
if iso:
mapper.SetVolumeRayCastFunction(isofunc)
if info:
print('Isosurface')
else:
mapper.SetVolumeRayCastFunction(compositeFunction)
# mapper.SetMinimumImageSampleDistance(0.2)
if info:
print('Composite')
if affine is None:
if major_version <= 5:
mapper.SetInput(im)
else:
mapper.SetInputData(im)
else:
# mapper.SetInput(reslice.GetOutput())
if major_version <= 5:
mapper.SetInput(changeFilter.GetOutput())
else:
mapper.SetInputData(changeFilter.GetOutput())
# Return mid position in world space
# im2=reslice.GetOutput()
# index=im2.FindPoint(vol.shape[0]/2.0,vol.shape[1]/2.0,vol.shape[2]/2.0)
# print 'Image Getpoint ' , im2.GetPoint(index)
volum = vtk.vtkVolume()
volum.SetMapper(mapper)
volum.SetProperty(property)
if info:
print('Origin', volum.GetOrigin())
print('Orientation', volum.GetOrientation())
print('OrientationW', volum.GetOrientationWXYZ())
print('Position', volum.GetPosition())
print('Center', volum.GetCenter())
print('Get XRange', volum.GetXRange())
print('Get YRange', volum.GetYRange())
print('Get ZRange', volum.GetZRange())
print('Volume data type', vol.dtype)
return volum
def contour(vol, voxsz=(1.0, 1.0, 1.0), affine=None, levels=[50],
colors=[np.array([1.0, 0.0, 0.0])], opacities=[0.5]):
""" Take a volume and draw surface contours for any any number of
thresholds (levels) where every contour has its own color and opacity
Parameters
----------
vol : (N, M, K) ndarray
An array representing the volumetric dataset for which we will draw
some beautiful contours .
voxsz : (3,) array_like
Voxel size.
affine : None
Not used.
levels : array_like
Sequence of thresholds for the contours taken from image values needs
to be same datatype as `vol`.
colors : (N, 3) ndarray
RGB values in [0,1].
opacities : array_like
Opacities of contours.
Returns
-------
vtkAssembly
Examples
--------
>>> import numpy as np
>>> from dipy.viz import fvtk
>>> A=np.zeros((10,10,10))
>>> A[3:-3,3:-3,3:-3]=1
>>> r=fvtk.ren()
>>> fvtk.add(r,fvtk.contour(A,levels=[1]))
>>> #fvtk.show(r)
"""
im = vtk.vtkImageData()
if major_version <= 5:
im.SetScalarTypeToUnsignedChar()
im.SetDimensions(vol.shape[0], vol.shape[1], vol.shape[2])
# im.SetOrigin(0,0,0)
# im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])
if major_version <= 5:
im.AllocateScalars()
else:
im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 3)
for i in range(vol.shape[0]):
for j in range(vol.shape[1]):
for k in range(vol.shape[2]):
im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])
ass = vtk.vtkAssembly()
# ass=[]
for (i, l) in enumerate(levels):
# print levels
skinExtractor = vtk.vtkContourFilter()
if major_version <= 5:
skinExtractor.SetInput(im)
else:
skinExtractor.SetInputData(im)
skinExtractor.SetValue(0, l)
skinNormals = vtk.vtkPolyDataNormals()
skinNormals.SetInputConnection(skinExtractor.GetOutputPort())
skinNormals.SetFeatureAngle(60.0)
skinMapper = vtk.vtkPolyDataMapper()
skinMapper.SetInputConnection(skinNormals.GetOutputPort())
skinMapper.ScalarVisibilityOff()
skin = vtk.vtkActor()
skin.SetMapper(skinMapper)
skin.GetProperty().SetOpacity(opacities[i])
# print colors[i]
skin.GetProperty().SetColor(colors[i][0], colors[i][1], colors[i][2])
# skin.Update()
ass.AddPart(skin)
del skin
del skinMapper
del skinExtractor
return ass
lowercase_cm_name = {'blues':'Blues', 'accent':'Accent'}
def create_colormap(v, name='jet', auto=True):
"""Create colors from a specific colormap and return it
as an array of shape (N,3) where every row gives the corresponding
r,g,b value. The colormaps we use are similar with those of pylab.
Parameters
----------
v : (N,) array
vector of values to be mapped in RGB colors according to colormap
name : str.
Name of the colormap. Currently implemented: 'jet', 'blues',
'accent', 'bone' and matplotlib colormaps if you have matplotlib
installed.
auto : bool,
if auto is True then v is interpolated to [0, 10] from v.min()
to v.max()
Notes
-----
Dipy supports a few colormaps for those who do not use Matplotlib, for
more colormaps consider downloading Matplotlib.
"""
if v.ndim > 1:
msg = 'This function works only with 1d arrays. Use ravel()'
raise ValueError(msg)
if auto:
v = np.interp(v, [v.min(), v.max()], [0, 1])
else:
v = np.clip(v, 0, 1)
# For backwards compatibility with lowercase names
newname = lowercase_cm_name.get(name) or name
colormap = get_cmap(newname)
if colormap is None:
e_s = "Colormap '%s' is not yet implemented " % name
raise ValueError(e_s)
rgba = colormap(v)
rgb = rgba[:, :3].copy()
return rgb
def _makeNd(array, ndim):
"""Pads as many 1s at the beginning of array's shape as are need to give
array ndim dimensions."""
new_shape = (1,) * (ndim - array.ndim) + array.shape
return array.reshape(new_shape)
def sphere_funcs(sphere_values, sphere, image=None, colormap='jet',
scale=2.2, norm=True, radial_scale=True):
"""Plot many morphed spherical functions simultaneously.
Parameters
----------
sphere_values : (M,) or (X, M) or (X, Y, M) or (X, Y, Z, M) ndarray
Values on the sphere.
sphere : Sphere
image : None,
Not yet supported.
colormap : None or 'jet'
If None then no color is used.
scale : float,
Distance between spheres.
norm : bool,
Normalize `sphere_values`.
radial_scale : bool,
Scale sphere points according to odf values.
Returns
-------
actor : vtkActor
Spheres.
Examples
--------
>>> from dipy.viz import fvtk
>>> r = fvtk.ren()
>>> odfs = np.ones((5, 5, 724))
>>> odfs[..., 0] = 2.
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric724')
>>> fvtk.add(r, fvtk.sphere_funcs(odfs, sphere))
>>> #fvtk.show(r)
"""
sphere_values = np.asarray(sphere_values)
if sphere_values.ndim > 4:
raise ValueError("Wrong shape")
sphere_values = _makeNd(sphere_values, 4)
grid_shape = np.array(sphere_values.shape[:3])
faces = np.asarray(sphere.faces, dtype=int)
vertices = sphere.vertices
if sphere_values.shape[-1] != sphere.vertices.shape[0]:
msg = 'Sphere.vertices.shape[0] should be the same as the '
msg += 'last dimensions of sphere_values i.e. sphere_values.shape[-1]'
raise ValueError(msg)
list_sq = []
list_cols = []
for ijk in np.ndindex(*grid_shape):
m = sphere_values[ijk].copy()
if norm:
m /= abs(m).max()
if radial_scale:
xyz = vertices.T * m
else:
xyz = vertices.T.copy()
xyz += scale * (ijk - grid_shape / 2.)[:, None]
xyz = xyz.T
list_sq.append(xyz)
if colormap is not None:
cols = create_colormap(m, colormap)
cols = np.interp(cols, [0, 1], [0, 255]).astype('ubyte')
list_cols.append(cols)
points = vtk.vtkPoints()
triangles = vtk.vtkCellArray()
if colormap is not None:
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
colors.SetName("Colors")
for k in xrange(len(list_sq)):
xyz = list_sq[k]
if colormap is not None:
cols = list_cols[k]
for i in xrange(xyz.shape[0]):
points.InsertNextPoint(*xyz[i])
if colormap is not None:
colors.InsertNextTuple3(*cols[i])
for j in xrange(faces.shape[0]):
triangle = vtk.vtkTriangle()
triangle.GetPointIds().SetId(0, faces[j, 0] + k * xyz.shape[0])
triangle.GetPointIds().SetId(1, faces[j, 1] + k * xyz.shape[0])
triangle.GetPointIds().SetId(2, faces[j, 2] + k * xyz.shape[0])
triangles.InsertNextCell(triangle)
del triangle
polydata = vtk.vtkPolyData()
polydata.SetPoints(points)
polydata.SetPolys(triangles)
if colormap is not None:
polydata.GetPointData().SetScalars(colors)
polydata.Modified()
mapper = vtk.vtkPolyDataMapper()
if major_version <= 5:
mapper.SetInput(polydata)
else:
mapper.SetInputData(polydata)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
return actor
def peaks(peaks_dirs, peaks_values=None, scale=2.2, colors=(1, 0, 0)):
""" Visualize peak directions as given from ``peaks_from_model``
Parameters
----------
peaks_dirs : ndarray
Peak directions. The shape of the array can be (M, 3) or (X, M, 3) or
(X, Y, M, 3) or (X, Y, Z, M, 3)
peaks_values : ndarray
Peak values. The shape of the array can be (M, ) or (X, M) or
(X, Y, M) or (X, Y, Z, M)
scale : float
Distance between spheres
colors : ndarray or tuple
Peak colors
Returns
-------
vtkActor
See Also
--------
dipy.viz.fvtk.sphere_funcs
"""
peaks_dirs = np.asarray(peaks_dirs)
if peaks_dirs.ndim > 5:
raise ValueError("Wrong shape")
peaks_dirs = _makeNd(peaks_dirs, 5)
if peaks_values is not None:
peaks_values = _makeNd(peaks_values, 4)
grid_shape = np.array(peaks_dirs.shape[:3])
list_dirs = []
for ijk in np.ndindex(*grid_shape):
xyz = scale * (ijk - grid_shape / 2.)[:, None]
xyz = xyz.T
for i in range(peaks_dirs.shape[-2]):
if peaks_values is not None:
pv = peaks_values[ijk][i]
else:
pv = 1.
symm = np.vstack((-peaks_dirs[ijk][i] * pv + xyz,
peaks_dirs[ijk][i] * pv + xyz))
list_dirs.append(symm)
return line(list_dirs, colors)
def tensor(evals, evecs, scalar_colors=None, sphere=None, scale=2.2, norm=True):
"""Plot many tensors as ellipsoids simultaneously.
Parameters
----------
evals : (3,) or (X, 3) or (X, Y, 3) or (X, Y, Z, 3) ndarray
eigenvalues
evecs : (3, 3) or (X, 3, 3) or (X, Y, 3, 3) or (X, Y, Z, 3, 3) ndarray
eigenvectors
scalar_colors : (3,) or (X, 3) or (X, Y, 3) or (X, Y, Z, 3) ndarray
RGB colors used to show the tensors
Default None, color the ellipsoids using ``color_fa``
sphere : Sphere,
this sphere will be transformed to the tensor ellipsoid
Default is None which uses a symmetric sphere with 724 points.
scale : float,
distance between ellipsoids.
norm : boolean,
Normalize `evals`.
Returns
-------
actor : vtkActor
Ellipsoids
Examples
--------
>>> from dipy.viz import fvtk
>>> r = fvtk.ren()
>>> evals = np.array([1.4, .35, .35]) * 10 ** (-3)
>>> evecs = np.eye(3)
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric724')
>>> fvtk.add(r, fvtk.tensor(evals, evecs, sphere=sphere))
>>> #fvtk.show(r)
"""
evals = np.asarray(evals)
if evals.ndim > 4:
raise ValueError("Wrong shape")
evals = _makeNd(evals, 4)
evecs = _makeNd(evecs, 5)
grid_shape = np.array(evals.shape[:3])
if sphere is None:
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')
faces = np.asarray(sphere.faces, dtype=int)
vertices = sphere.vertices
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
colors.SetName("Colors")
if scalar_colors is None:
from dipy.reconst.dti import color_fa, fractional_anisotropy
cfa = color_fa(fractional_anisotropy(evals), evecs)
else:
cfa = _makeNd(scalar_colors, 4)
list_sq = []
list_cols = []
for ijk in ndindex(grid_shape):
ea = evals[ijk]
if norm:
ea /= ea.max()
ea = np.diag(ea.copy())
ev = evecs[ijk].copy()
xyz = np.dot(ev, np.dot(ea, vertices.T))
xyz += scale * (ijk - grid_shape / 2.)[:, None]
xyz = xyz.T
list_sq.append(xyz)
acolor = np.zeros(xyz.shape)
acolor[:, :] = np.interp(cfa[ijk], [0, 1], [0, 255])
list_cols.append(acolor.astype('ubyte'))
points = vtk.vtkPoints()
triangles = vtk.vtkCellArray()
for k in xrange(len(list_sq)):
xyz = list_sq[k]
cols = list_cols[k]
for i in xrange(xyz.shape[0]):
points.InsertNextPoint(*xyz[i])
colors.InsertNextTuple3(*cols[i])
for j in xrange(faces.shape[0]):
triangle = vtk.vtkTriangle()
triangle.GetPointIds().SetId(0, faces[j, 0] + k * xyz.shape[0])
triangle.GetPointIds().SetId(1, faces[j, 1] + k * xyz.shape[0])
triangle.GetPointIds().SetId(2, faces[j, 2] + k * xyz.shape[0])
triangles.InsertNextCell(triangle)
del triangle
polydata = vtk.vtkPolyData()
polydata.SetPoints(points)
polydata.SetPolys(triangles)
polydata.GetPointData().SetScalars(colors)
polydata.Modified()
mapper = vtk.vtkPolyDataMapper()
if major_version <= 5:
mapper.SetInput(polydata)
else:
mapper.SetInputData(polydata)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
return actor
def slicer(vol, voxsz=(1.0, 1.0, 1.0), plane_i=[0], plane_j=None,
plane_k=None, outline=True):
""" Slice a 3D volume
Parameters
----------
vol : array, shape (N, M, K)
An array representing the volumetric dataset that we want to slice
voxsz : sequence of 3 floats
Voxel size.
plane_i : sequence of ints
show plane or planes along the first dimension
plane_j : sequence of ints
show plane or planes along the second dimension
plane_k : sequence of ints
show plane or planes along the third(last) dimension
outline : bool
if True (default) a small outline is drawn around the slices
Examples
--------
>>> import numpy as np
>>> from dipy.viz import fvtk
>>> x, y, z = np.ogrid[-10:10:80j, -10:10:80j, -10:10:80j]
>>> s = np.sin(x * y * z) / (x * y * z)
>>> r = fvtk.ren()
>>> fvtk.add(r, fvtk.slicer(s, plane_i=[0, 5]))
>>> #fvtk.show(r)
"""
if plane_i is None:
plane_i = []
if plane_j is None:
plane_j = []
if plane_k is None:
plane_k = []
if vol.ndim != 3:
raise ValueError("vol has to be a 3d array")
vol = np.interp(vol, xp=[vol.min(), vol.max()], fp=[0, 255])
vol = vol.astype('uint8')
im = vtk.vtkImageData()
if major_version <= 5:
im.SetScalarTypeToUnsignedChar()
I, J, K = vol.shape[:3]
im.SetDimensions(I, J, K)
# im.SetOrigin(0,0,0)
im.SetSpacing(voxsz[2], voxsz[0], voxsz[1])
if major_version <= 5:
im.AllocateScalars()
else:
im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 3)
# copy data
for i in range(vol.shape[0]):
for j in range(vol.shape[1]):
for k in range(vol.shape[2]):
im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])
# An outline provides context around the data.
outlineData = vtk.vtkOutlineFilter()
if major_version <= 5:
outlineData.SetInput(im)
else:
outlineData.SetInputData(im)
mapOutline = vtk.vtkPolyDataMapper()
mapOutline.SetInputConnection(outlineData.GetOutputPort())
outline_ = vtk.vtkActor()
outline_.SetMapper(mapOutline)
outline_.GetProperty().SetColor(1, 0, 0)
# Now we are creating three orthogonal planes passing through the
# volume. Each plane uses a different texture map and therefore has
# diferent coloration.
# Start by creatin a black/white lookup table.
lut = vtk.vtkLookupTable()
lut.SetTableRange(vol.min(), vol.max())
lut.SetSaturationRange(0, 0)
lut.SetHueRange(0, 0)
lut.SetValueRange(0, 1)
lut.SetRampToLinear()
lut.Build()
x1, x2, y1, y2, z1, z2 = im.GetExtent()
# print x1,x2,y1,y2,z1,z2
# Create the first of the three planes. The filter vtkImageMapToColors
# maps the data through the corresponding lookup table created above.
# The vtkImageActor is a type of vtkProp and conveniently displays an
# image on a single quadrilateral plane. It does this using texture
# mapping and as a result is quite fast. (Note: the input image has to
# be unsigned char values, which the vtkImageMapToColors produces.)
# Note also that by specifying the DisplayExtent, the pipeline
# requests data of this extent and the vtkImageMapToColors only
# processes a slice of data.
planeColors = vtk.vtkImageMapToColors()
# saggitalColors.SetInputConnection(im.GetOutputPort())
if major_version <= 5:
planeColors.SetInput(im)
else:
planeColors.SetInputData(im)
planeColors.SetLookupTable(lut)
planeColors.Update()
saggitals = []
for x in plane_i:
saggital = vtk.vtkImageActor()
if major_version <= 5:
saggital.SetInput(planeColors.GetOutput())
else:
saggital.SetInputData(planeColors.GetOutput())
saggital.SetDisplayExtent(x, x, y1, y2, z1, z2)
saggitals.append(saggital)
axials = []
for z in plane_k:
axial = vtk.vtkImageActor()
if major_version <= 5:
axial.SetInput(planeColors.GetOutput())
else:
axial.SetInputData(planeColors.GetOutput())
axial.SetDisplayExtent(x1, x2, y1, y2, z, z)
axials.append(axial)
coronals = []
for y in plane_j:
coronal = vtk.vtkImageActor()
if major_version <= 5:
coronal.SetInput(planeColors.GetOutput())
else:
coronal.SetInputData(planeColors.GetOutput())
coronal.SetDisplayExtent(x1, x2, y, y, z1, z2)
coronals.append(coronal)
assem = vtk.vtkAssembly()
for sag in saggitals:
assem.AddPart(sag)
for ax in axials:
assem.AddPart(ax)
for cor in coronals:
assem.AddPart(cor)
if outline:
assem.AddPart(outline_)
return assem
def camera(ren, pos=None, focal=None, viewup=None, verbose=True):
""" Change the active camera
Parameters
----------
ren : vtkRenderer
pos : tuple
(x, y, z) position of the camera
focal : tuple
(x, y, z) focal point
viewup : tuple
(x, y, z) viewup vector
verbose : bool
show information about the camera
Returns
-------
vtkCamera
"""
cam = ren.GetActiveCamera()
if verbose:
print('Camera Position (%.2f,%.2f,%.2f)' % cam.GetPosition())
print('Camera Focal Point (%.2f,%.2f,%.2f)' % cam.GetFocalPoint())
print('Camera View Up (%.2f,%.2f,%.2f)' % cam.GetViewUp())
if pos is not None:
cam = ren.GetActiveCamera().SetPosition(*pos)
if focal is not None:
ren.GetActiveCamera().SetFocalPoint(*focal)
if viewup is not None:
ren.GetActiveCamera().SetViewUp(*viewup)
cam = ren.GetActiveCamera()
if pos is not None or focal is not None or viewup is not None:
if verbose:
print('-------------------------------------')
print('Camera New Position (%.2f,%.2f,%.2f)' % cam.GetPosition())
print('Camera New Focal Point (%.2f,%.2f,%.2f)' %
cam.GetFocalPoint())
print('Camera New View Up (%.2f,%.2f,%.2f)' % cam.GetViewUp())
return cam
def show(ren, title='Dipy', size=(300, 300), png_magnify=1):
""" Show window
Notes
-----
To save a screenshot press's' and check your current directory
for ``fvtk.png``.
Parameters
------------
ren : vtkRenderer() object
As returned from function ``ren()``.
title : string
A string for the window title bar.
size : (int, int)
``(width, height)`` of the window
png_magnify : int
Number of times to magnify the screenshot.
Notes
-----
If you want to:
* navigate in the the 3d world use the left - middle - right mouse buttons
* reset the screen press 'r'
* save a screenshot press 's'
* quit press 'q'
See also
---------
dipy.viz.fvtk.record
Examples
----------
>>> import numpy as np
>>> from dipy.viz import fvtk
>>> r=fvtk.ren()
>>> lines=[np.random.rand(10,3),np.random.rand(20,3)]
>>> colors=np.array([[0.2,0.2,0.2],[0.8,0.8,0.8]])
>>> c=fvtk.line(lines,colors)
>>> fvtk.add(r,c)
>>> l=fvtk.label(r)
>>> fvtk.add(r,l)
>>> #fvtk.show(r)
See also
----------
dipy.viz.fvtk.record
"""
ren.ResetCamera()
window = vtk.vtkRenderWindow()
window.AddRenderer(ren)
# window.SetAAFrames(6)
window.SetWindowName(title)
window.SetSize(size[0], size[1])
style = vtk.vtkInteractorStyleTrackballCamera()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(window)
iren.SetPicker(picker)
def key_press(obj, event):
key = obj.GetKeySym()
if key == 's' or key == 'S':
print('Saving image...')
renderLarge = vtk.vtkRenderLargeImage()
if major_version <= 5:
renderLarge.SetInput(ren)
else:
renderLarge.SetInputData(ren)
renderLarge.SetMagnification(png_magnify)
renderLarge.Update()
writer = vtk.vtkPNGWriter()
writer.SetInputConnection(renderLarge.GetOutputPort())
writer.SetFileName('fvtk.png')
writer.Write()
print('Look for fvtk.png in your current working directory.')
iren.AddObserver('KeyPressEvent', key_press)
iren.SetInteractorStyle(style)
iren.Initialize()
picker.Pick(85, 126, 0, ren)
window.Render()
iren.Start()
# window.RemoveAllObservers()
# ren.SetRenderWindow(None)
window.RemoveRenderer(ren)
ren.SetRenderWindow(None)
def record(ren=None, cam_pos=None, cam_focal=None, cam_view=None,
out_path=None, path_numbering=False, n_frames=1, az_ang=10,
magnification=1, size=(300, 300), verbose=False):
''' This will record a video of your scene
Records a video as a series of ``.png`` files of your scene by rotating
the azimuth angle az_angle in every frame.
Parameters
-----------
ren : vtkRenderer() object
As returned from :func:`ren`.
cam_pos : None or sequence (3,), optional
Camera position.
cam_focal : None or sequence (3,), optional
Camera focal point.
cam_view : None or sequence (3,), optional
Camera view up.
out_path : str, optional
Output directory for the frames
path_numbering : bool, optional
when recording it changes out_path to out_path + str(frame number).
If n_frames is larger than 1, this will default to True
n_frames : int, optional
number of frames to save. Default: 1
az_ang : float, optional
Azimuthal angle of camera rotation (degrees). Default: 10.
magnification : int, optional
How much to magnify the saved frame. Default: 1 (no magnification).
Examples
---------
>>> from dipy.viz import fvtk
>>> r=fvtk.ren()
>>> a=fvtk.axes()
>>> fvtk.add(r,a)
>>> #uncomment below to record
>>> #fvtk.record(r)
>>> #check for new images in current directory
'''
if ren is None:
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(size[0], size[1])
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# ren.GetActiveCamera().Azimuth(180)
ren.ResetCamera()
renderLarge = vtk.vtkRenderLargeImage()
renderLarge.SetInput(ren)
renderLarge.SetMagnification(magnification)
renderLarge.Update()
writer = vtk.vtkPNGWriter()
ang = 0
if cam_pos is not None:
cx, cy, cz = cam_pos
ren.GetActiveCamera().SetPosition(cx, cy, cz)
if cam_focal is not None:
fx, fy, fz = cam_focal
ren.GetActiveCamera().SetFocalPoint(fx, fy, fz)
if cam_view is not None:
ux, uy, uz = cam_view
ren.GetActiveCamera().SetViewUp(ux, uy, uz)
cam = ren.GetActiveCamera()
if verbose:
print('Camera Position (%.2f,%.2f,%.2f)' % cam.GetPosition())
print('Camera Focal Point (%.2f,%.2f,%.2f)' % cam.GetFocalPoint())
print('Camera View Up (%.2f,%.2f,%.2f)' % cam.GetViewUp())
for i in range(n_frames):
ren.GetActiveCamera().Azimuth(ang)
renderLarge = vtk.vtkRenderLargeImage()
renderLarge.SetInput(ren)
renderLarge.SetMagnification(magnification)
renderLarge.Update()
writer.SetInputConnection(renderLarge.GetOutputPort())
# filename='/tmp/'+str(3000000+i)+'.png'
if n_frames > 1 or path_numbering:
if out_path is None:
filename = str(1000000 + i) + '.png'
else:
filename = out_path + str(1000000 + i) + '.png'
else:
filename = out_path
writer.SetFileName(filename)
writer.Write()
ang = +az_ang
if __name__ == "__main__":
pass<|fim▁end|>
|
compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
|
<|file_name|>CloudProviderRegistry.ts<|end_file_name|><|fim▁begin|>/* tslint:disable: no-console */
import { cloneDeep, get, isNil, set } from 'lodash';
import { SETTINGS } from '../config/settings';
export interface ICloudProviderLogo {
path: string;
}
export interface ICloudProviderConfig {
name: string;
logo?: ICloudProviderLogo;
[attribute: string]: any;
}
export class CloudProviderRegistry {
/*
Note: Providers don't get $log, so we stick with console statements here
*/
private static providers = new Map<string, ICloudProviderConfig>();
public static registerProvider(cloudProvider: string, config: ICloudProviderConfig): void {
if (SETTINGS.providers[cloudProvider]) {
this.providers.set(cloudProvider, config);
}
}
public static getProvider(cloudProvider: string): ICloudProviderConfig {
return this.providers.has(cloudProvider) ? cloneDeep(this.providers.get(cloudProvider)) : null;
}
public static listRegisteredProviders(): string[] {
return Array.from(this.providers.keys());
}
public static overrideValue(cloudProvider: string, key: string, overrideValue: any) {
if (!this.providers.has(cloudProvider)) {<|fim▁hole|> }
public static hasValue(cloudProvider: string, key: string) {
return this.providers.has(cloudProvider) && this.getValue(cloudProvider, key) !== null;
}
public static getValue(cloudProvider: string, key: string): any {
return get(this.getProvider(cloudProvider), key) ?? null;
}
public static isDisabled(cloudProvider: string) {
// If the adHocInfrastructureWritesEnabled flag when registering provider is not set
// Infrastructure writes will be enabled (Action buttons will not be disabled)
if (isNil(CloudProviderRegistry.getValue(cloudProvider, 'adHocInfrastructureWritesEnabled'))) {
return false;
}
return CloudProviderRegistry.getValue(cloudProvider, 'adHocInfrastructureWritesEnabled') === false;
}
}<|fim▁end|>
|
console.warn(`Cannot override "${key}" for provider "${cloudProvider}" (provider not registered)`);
return;
}
set(this.providers.get(cloudProvider), key, overrideValue);
|
<|file_name|>heartbeats.go<|end_file_name|><|fim▁begin|>//
// Copyright © 2011-2019 Guy M. Allard
//
// 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.
//
package stompngo
import (
"fmt"
"strconv"
"strings"
"time"
)
/*
Initialize heart beats if necessary and possible.
Return an error, possibly nil, to mainline if initialization can not
complete. Establish heartbeat send and receive goroutines as necessary.
*/
func (c *Connection) initializeHeartBeats(ch Headers) (e error) {
// Client wants Heartbeats ?
vc, ok := ch.Contains(HK_HEART_BEAT)
if !ok || vc == "0,0" {
return nil
}
// Server wants Heartbeats ?
vs, ok := c.ConnectResponse.Headers.Contains(HK_HEART_BEAT)
if !ok || vs == "0,0" {
return nil
}
// Work area, may or may not become connection heartbeat data
w := &heartBeatData{cx: 0, cy: 0, sx: 0, sy: 0,
hbs: true, hbr: true, // possible reset later
sti: 0, rti: 0,
ls: 0, lr: 0}
// Client specified values
cp := strings.Split(vc, ",")
if len(cp) != 2 { // S/B caught by the server first
return Error("invalid client heart-beat header: " + vc)
}
w.cx, e = strconv.ParseInt(cp[0], 10, 64)
if e != nil {
return Error("non-numeric cx heartbeat value: " + cp[0])
}
w.cy, e = strconv.ParseInt(cp[1], 10, 64)
if e != nil {
return Error("non-numeric cy heartbeat value: " + cp[1])
}
// Server specified values
sp := strings.Split(vs, ",")
if len(sp) != 2 {
return Error("invalid server heart-beat header: " + vs)
}
w.sx, e = strconv.ParseInt(sp[0], 10, 64)
if e != nil {
return Error("non-numeric sx heartbeat value: " + sp[0])
}
w.sy, e = strconv.ParseInt(sp[1], 10, 64)
if e != nil {
return Error("non-numeric sy heartbeat value: " + sp[1])
}
// Check for sending needed
if w.cx == 0 || w.sy == 0 {
w.hbs = false //
}
// Check for receiving needed
if w.sx == 0 || w.cy == 0 {
w.hbr = false //
}
// ========================================================================
if !w.hbs && !w.hbr {
return nil // none required
}
// ========================================================================
c.hbd = w // OK, we are doing some kind of heartbeating
ct := time.Now().UnixNano() // Prime current time
if w.hbs { // Finish sender parameters if required
sm := max(w.cx, w.sy) // ticker interval, ms
w.sti = 1000000 * sm // ticker interval, ns
w.ssd = make(chan struct{}) // add shutdown channel
w.ls = ct // Best guess at start
// fmt.Println("start send ticker")
go c.sendTicker()
}
if w.hbr { // Finish receiver parameters if required
rm := max(w.sx, w.cy) // ticker interval, ms
w.rti = 1000000 * rm // ticker interval, ns
w.rsd = make(chan struct{}) // add shutdown channel
w.lr = ct // Best guess at start
// fmt.Println("start receive ticker")
go c.receiveTicker()
}
return nil
}
/*
The heart beat send ticker.
*/
func (c *Connection) sendTicker() {
c.hbd.sc = 0
ticker := time.NewTicker(time.Duration(c.hbd.sti))
defer ticker.Stop()
hbSend:
for {
select {
case <-ticker.C:
c.log("HeartBeat Send data")
// Send a heartbeat
f := Frame{"\n", Headers{}, NULLBUFF} // Heartbeat frame
r := make(chan error)
if e := c.writeWireData(wiredata{f, r}); e != nil {
c.Hbsf = true
break hbSend
}
e := <-r
//
c.hbd.sdl.Lock()
if e != nil {
fmt.Printf("Heartbeat Send Failure: %v\n", e)
c.Hbsf = true
} else {
c.Hbsf = false
c.hbd.sc++
}
c.hbd.sdl.Unlock()
//
case _ = <-c.hbd.ssd:
break hbSend
case _ = <-c.ssdc:
break hbSend
} // End of select
} // End of for
c.log("Heartbeat Send Ends", time.Now())
return
}
/*
The heart beat receive ticker.
*/
func (c *Connection) receiveTicker() {
c.hbd.rc = 0
var first, last, nd int64
hbGet:
for {
nd = c.hbd.rti - (last - first)
// Check if receives are supposed to be "fast" *and* we spent a
// lot of time in the previous loop.
if nd <= 0 {
nd = c.hbd.rti
}
ticker := time.NewTicker(time.Duration(nd))
select {
case ct := <-ticker.C:
first = time.Now().UnixNano()
ticker.Stop()
c.hbd.rdl.Lock()
flr := c.hbd.lr
ld := ct.UnixNano() - flr
c.log("HeartBeat Receive TIC", "TickerVal", ct.UnixNano(),
"LastReceive", flr, "Diff", ld)
if ld > (c.hbd.rti + (c.hbd.rti / 5)) { // swag plus to be tolerant
c.log("HeartBeat Receive Read is dirty")
c.Hbrf = true // Flag possible dirty connection
} else {
c.Hbrf = false // Reset
c.hbd.rc++
}
c.hbd.rdl.Unlock()
last = time.Now().UnixNano()
case _ = <-c.hbd.rsd:
ticker.Stop()
break hbGet
case _ = <-c.ssdc:
ticker.Stop()
break hbGet
} // End of select<|fim▁hole|><|fim▁end|>
|
} // End of for
c.log("Heartbeat Receive Ends", time.Now())
return
}
|
<|file_name|>query.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Utilities for querying the layout, as needed by the layout thread.
use app_units::Au;
use construct::ConstructionResult;
use context::LayoutContext;
use euclid::{Point2D, Vector2D, Rect, Size2D};
use flow::{self, Flow};
use fragment::{Fragment, FragmentBorderBoxIterator, SpecificFragmentInfo};
use gfx::display_list::{DisplayItemMetadata, DisplayList, OpaqueNode, ScrollOffsetMap};
use inline::LAST_FRAGMENT_OF_ELEMENT;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use opaque_node::OpaqueNodeMethods;
use script_layout_interface::rpc::{ContentBoxResponse, ContentBoxesResponse};
use script_layout_interface::rpc::{HitTestResponse, LayoutRPC};
use script_layout_interface::rpc::{MarginStyleResponse, NodeGeometryResponse};
use script_layout_interface::rpc::{NodeOverflowResponse, OffsetParentResponse};
use script_layout_interface::rpc::{NodeScrollRootIdResponse, ResolvedStyleResponse, TextIndexResponse};
use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
use script_traits::LayoutMsg as ConstellationMsg;
use script_traits::UntrustedNodeAddress;
use sequential;
use std::cmp::{min, max};
use std::ops::Deref;
use std::sync::{Arc, Mutex};
use style::computed_values;
use style::context::{StyleContext, ThreadLocalStyleContext};
use style::dom::TElement;
use style::logical_geometry::{WritingMode, BlockFlowDirection, InlineBaseDirection};
use style::properties::{style_structs, PropertyId, PropertyDeclarationId, LonghandId};
use style::properties::longhands::{display, position};
use style::selector_parser::PseudoElement;
use style_traits::ToCss;
use style_traits::cursor::Cursor;
use webrender_api::ClipId;
use wrapper::LayoutNodeLayoutData;
/// Mutable data belonging to the LayoutThread.
///
/// This needs to be protected by a mutex so we can do fast RPCs.
pub struct LayoutThreadData {
/// The channel on which messages can be sent to the constellation.
pub constellation_chan: IpcSender<ConstellationMsg>,
/// The root stacking context.
pub display_list: Option<Arc<DisplayList>>,
/// A queued response for the union of the content boxes of a node.
pub content_box_response: Option<Rect<Au>>,
/// A queued response for the content boxes of a node.
pub content_boxes_response: Vec<Rect<Au>>,
/// A queued response for the client {top, left, width, height} of a node in pixels.
pub client_rect_response: Rect<i32>,
/// A queued response for the node at a given point
pub hit_test_response: (Option<DisplayItemMetadata>, bool),
/// A queued response for the scroll root id for a given node.
pub scroll_root_id_response: Option<ClipId>,
/// A pair of overflow property in x and y
pub overflow_response: NodeOverflowResponse,
/// A queued response for the scroll {top, left, width, height} of a node in pixels.
pub scroll_area_response: Rect<i32>,
/// A queued response for the resolved style property of an element.
pub resolved_style_response: String,
/// A queued response for the offset parent/rect of a node.
pub offset_parent_response: OffsetParentResponse,
/// A queued response for the offset parent/rect of a node.
pub margin_style_response: MarginStyleResponse,
/// Scroll offsets of scrolling regions.
pub scroll_offsets: ScrollOffsetMap,
/// Index in a text fragment. We need this do determine the insertion point.
pub text_index_response: TextIndexResponse,
/// A queued response for the list of nodes at a given point.
pub nodes_from_point_response: Vec<UntrustedNodeAddress>,
}
pub struct LayoutRPCImpl(pub Arc<Mutex<LayoutThreadData>>);
// https://drafts.csswg.org/cssom-view/#overflow-directions
fn overflow_direction(writing_mode: &WritingMode) -> OverflowDirection {
match (writing_mode.block_flow_direction(), writing_mode.inline_base_direction()) {
(BlockFlowDirection::TopToBottom, InlineBaseDirection::LeftToRight) |
(BlockFlowDirection::LeftToRight, InlineBaseDirection::LeftToRight) => OverflowDirection::RightAndDown,
(BlockFlowDirection::TopToBottom, InlineBaseDirection::RightToLeft) |
(BlockFlowDirection::RightToLeft, InlineBaseDirection::LeftToRight) => OverflowDirection::LeftAndDown,
(BlockFlowDirection::RightToLeft, InlineBaseDirection::RightToLeft) => OverflowDirection::LeftAndUp,
(BlockFlowDirection::LeftToRight, InlineBaseDirection::RightToLeft) => OverflowDirection::RightAndUp
}
}
impl LayoutRPC for LayoutRPCImpl {
// The neat thing here is that in order to answer the following two queries we only
// need to compare nodes for equality. Thus we can safely work only with `OpaqueNode`.
fn content_box(&self) -> ContentBoxResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
ContentBoxResponse(rw_data.content_box_response)
}
/// Requests the dimensions of all the content boxes, as in the `getClientRects()` call.
fn content_boxes(&self) -> ContentBoxesResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
ContentBoxesResponse(rw_data.content_boxes_response.clone())
}
/// Requests the node containing the point of interest.
fn hit_test(&self) -> HitTestResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
let &(ref result, update_cursor) = &rw_data.hit_test_response;
if update_cursor {
// Compute the new cursor.
let cursor = match *result {
None => Cursor::Default,
Some(dim) => dim.pointing.unwrap(),
};
rw_data.constellation_chan.send(ConstellationMsg::SetCursor(cursor)).unwrap();
}
HitTestResponse {
node_address: result.map(|dim| dim.node.to_untrusted_node_address()),
}
}
fn nodes_from_point_response(&self) -> Vec<UntrustedNodeAddress> {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
rw_data.nodes_from_point_response.clone()
}
fn node_geometry(&self) -> NodeGeometryResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
NodeGeometryResponse {
client_rect: rw_data.client_rect_response
}
}
fn node_overflow(&self) -> NodeOverflowResponse {
NodeOverflowResponse(self.0.lock().unwrap().overflow_response.0)
}
fn node_scroll_area(&self) -> NodeGeometryResponse {
NodeGeometryResponse {
client_rect: self.0.lock().unwrap().scroll_area_response
}
}
fn node_scroll_root_id(&self) -> NodeScrollRootIdResponse {
NodeScrollRootIdResponse(self.0.lock()
.unwrap().scroll_root_id_response
.expect("scroll_root_id is not correctly fetched"))
}
/// Retrieves the resolved value for a CSS style property.
fn resolved_style(&self) -> ResolvedStyleResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
ResolvedStyleResponse(rw_data.resolved_style_response.clone())
}
fn offset_parent(&self) -> OffsetParentResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
rw_data.offset_parent_response.clone()
}
fn margin_style(&self) -> MarginStyleResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
rw_data.margin_style_response.clone()
}
fn text_index(&self) -> TextIndexResponse {
let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap();
rw_data.text_index_response.clone()
}
}
struct UnioningFragmentBorderBoxIterator {
node_address: OpaqueNode,
rect: Option<Rect<Au>>,
}
impl UnioningFragmentBorderBoxIterator {
fn new(node_address: OpaqueNode) -> UnioningFragmentBorderBoxIterator {
UnioningFragmentBorderBoxIterator {
node_address: node_address,
rect: None
}
}
}
impl FragmentBorderBoxIterator for UnioningFragmentBorderBoxIterator {
fn process(&mut self, _: &Fragment, _: i32, border_box: &Rect<Au>) {
self.rect = match self.rect {
Some(rect) => {
Some(rect.union(border_box))
}
None => {
Some(*border_box)
}
};
}
fn should_process(&mut self, fragment: &Fragment) -> bool {
fragment.contains_node(self.node_address)
}
}
struct CollectingFragmentBorderBoxIterator {
node_address: OpaqueNode,
rects: Vec<Rect<Au>>,
}
impl CollectingFragmentBorderBoxIterator {
fn new(node_address: OpaqueNode) -> CollectingFragmentBorderBoxIterator {
CollectingFragmentBorderBoxIterator {
node_address: node_address,
rects: Vec::new(),
}
}
}
impl FragmentBorderBoxIterator for CollectingFragmentBorderBoxIterator {
fn process(&mut self, _: &Fragment, _: i32, border_box: &Rect<Au>) {
self.rects.push(*border_box);
}
fn should_process(&mut self, fragment: &Fragment) -> bool {
fragment.contains_node(self.node_address)
}
}
enum Side {
Left,
Right,
Bottom,
Top
}
enum MarginPadding {
Margin,
Padding
}
enum PositionProperty {
Left,
Right,
Top,
Bottom,
Width,
Height,
}
#[derive(Debug)]
enum OverflowDirection {
RightAndDown,
LeftAndDown,
LeftAndUp,
RightAndUp,
}
struct PositionRetrievingFragmentBorderBoxIterator {
node_address: OpaqueNode,
result: Option<Au>,
position: Point2D<Au>,
property: PositionProperty,
}
impl PositionRetrievingFragmentBorderBoxIterator {
fn new(node_address: OpaqueNode,
property: PositionProperty,
position: Point2D<Au>) -> PositionRetrievingFragmentBorderBoxIterator {
PositionRetrievingFragmentBorderBoxIterator {
node_address: node_address,
position: position,
property: property,
result: None,
}
}
}
impl FragmentBorderBoxIterator for PositionRetrievingFragmentBorderBoxIterator {
fn process(&mut self, fragment: &Fragment, _: i32, border_box: &Rect<Au>) {
let border_padding = fragment.border_padding.to_physical(fragment.style.writing_mode);
self.result =
Some(match self.property {
PositionProperty::Left => self.position.x,
PositionProperty::Top => self.position.y,
PositionProperty::Width => border_box.size.width - border_padding.horizontal(),
PositionProperty::Height => border_box.size.height - border_padding.vertical(),
// TODO: the following 2 calculations are completely wrong.
// They should return the difference between the parent's and this
// fragment's border boxes.
PositionProperty::Right => border_box.max_x() + self.position.x,
PositionProperty::Bottom => border_box.max_y() + self.position.y,
});
}
fn should_process(&mut self, fragment: &Fragment) -> bool {
fragment.contains_node(self.node_address)
}
}
struct MarginRetrievingFragmentBorderBoxIterator {
node_address: OpaqueNode,
result: Option<Au>,
writing_mode: WritingMode,
margin_padding: MarginPadding,
side: Side,
}
impl MarginRetrievingFragmentBorderBoxIterator {
fn new(node_address: OpaqueNode, side: Side, margin_padding:
MarginPadding, writing_mode: WritingMode) -> MarginRetrievingFragmentBorderBoxIterator {
MarginRetrievingFragmentBorderBoxIterator {
node_address: node_address,
side: side,
margin_padding: margin_padding,
result: None,
writing_mode: writing_mode,
}
}
}
impl FragmentBorderBoxIterator for MarginRetrievingFragmentBorderBoxIterator {
fn process(&mut self, fragment: &Fragment, _: i32, _: &Rect<Au>) {
let rect = match self.margin_padding {
MarginPadding::Margin => &fragment.margin,
MarginPadding::Padding => &fragment.border_padding
};
self.result = Some(match self.side {
Side::Left => rect.left(self.writing_mode),
Side::Right => rect.right(self.writing_mode),
Side::Bottom => rect.bottom(self.writing_mode),
Side::Top => rect.top(self.writing_mode)
});
}
fn should_process(&mut self, fragment: &Fragment) -> bool {
fragment.contains_node(self.node_address)
}
}
pub fn process_content_box_request<N: LayoutNode>(
requested_node: N, layout_root: &mut Flow) -> Option<Rect<Au>> {
// FIXME(pcwalton): This has not been updated to handle the stacking context relative
// stuff. So the position is wrong in most cases.
let mut iterator = UnioningFragmentBorderBoxIterator::new(requested_node.opaque());
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
iterator.rect
}
pub fn process_content_boxes_request<N: LayoutNode>(requested_node: N, layout_root: &mut Flow)
-> Vec<Rect<Au>> {
// FIXME(pcwalton): This has not been updated to handle the stacking context relative
// stuff. So the position is wrong in most cases.
let mut iterator = CollectingFragmentBorderBoxIterator::new(requested_node.opaque());
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
iterator.rects
}
struct FragmentLocatingFragmentIterator {
node_address: OpaqueNode,
client_rect: Rect<i32>,
}
impl FragmentLocatingFragmentIterator {
fn new(node_address: OpaqueNode) -> FragmentLocatingFragmentIterator {
FragmentLocatingFragmentIterator {
node_address: node_address,
client_rect: Rect::zero()
}
}
}
struct UnioningFragmentScrollAreaIterator {
node_address: OpaqueNode,
union_rect: Rect<i32>,
origin_rect: Rect<i32>,
level: Option<i32>,
is_child: bool,
overflow_direction: OverflowDirection
}
impl UnioningFragmentScrollAreaIterator {
fn new(node_address: OpaqueNode) -> UnioningFragmentScrollAreaIterator {
UnioningFragmentScrollAreaIterator {
node_address: node_address,
union_rect: Rect::zero(),
origin_rect: Rect::zero(),
level: None,
is_child: false,
overflow_direction: OverflowDirection::RightAndDown
}
}
}
struct NodeOffsetBoxInfo {
offset: Point2D<Au>,
rectangle: Rect<Au>,
}
struct ParentBorderBoxInfo {
node_address: OpaqueNode,
origin: Point2D<Au>,
}
struct ParentOffsetBorderBoxIterator {
node_address: OpaqueNode,
has_processed_node: bool,
node_offset_box: Option<NodeOffsetBoxInfo>,
parent_nodes: Vec<Option<ParentBorderBoxInfo>>,
}
impl ParentOffsetBorderBoxIterator {
fn new(node_address: OpaqueNode) -> ParentOffsetBorderBoxIterator {
ParentOffsetBorderBoxIterator {
node_address: node_address,
has_processed_node: false,
node_offset_box: None,
parent_nodes: Vec::new(),
}
}
}
impl FragmentBorderBoxIterator for FragmentLocatingFragmentIterator {
fn process(&mut self, fragment: &Fragment, _: i32, border_box: &Rect<Au>) {
let style_structs::Border {
border_top_width: top_width,
border_right_width: right_width,
border_bottom_width: bottom_width,<|fim▁hole|> self.client_rect.origin.x = left_width.0.to_px();
self.client_rect.size.width = (border_box.size.width - left_width.0 - right_width.0).to_px();
self.client_rect.size.height = (border_box.size.height - top_width.0 - bottom_width.0).to_px();
}
fn should_process(&mut self, fragment: &Fragment) -> bool {
fragment.node == self.node_address
}
}
// https://drafts.csswg.org/cssom-view/#scrolling-area
impl FragmentBorderBoxIterator for UnioningFragmentScrollAreaIterator {
fn process(&mut self, fragment: &Fragment, level: i32, border_box: &Rect<Au>) {
// In cases in which smaller child elements contain less padding than the parent
// the a union of the two elements padding rectangles could result in an unwanted
// increase in size. To work around this, we store the original elements padding
// rectangle as `origin_rect` and the union of all child elements padding and
// margin rectangles as `union_rect`.
let style_structs::Border {
border_top_width: top_border,
border_right_width: right_border,
border_bottom_width: bottom_border,
border_left_width: left_border,
..
} = *fragment.style.get_border();
let right_padding = (border_box.size.width - right_border.0 - left_border.0).to_px();
let bottom_padding = (border_box.size.height - bottom_border.0 - top_border.0).to_px();
let top_padding = top_border.0.to_px();
let left_padding = left_border.0.to_px();
match self.level {
Some(start_level) if level <= start_level => { self.is_child = false; }
Some(_) => {
let padding = Rect::new(Point2D::new(left_padding, top_padding),
Size2D::new(right_padding, bottom_padding));
let top_margin = fragment.margin.top(fragment.style.writing_mode).to_px();
let left_margin = fragment.margin.left(fragment.style.writing_mode).to_px();
let bottom_margin = fragment.margin.bottom(fragment.style.writing_mode).to_px();
let right_margin = fragment.margin.right(fragment.style.writing_mode).to_px();
let margin = Rect::new(Point2D::new(left_margin, top_margin),
Size2D::new(right_margin, bottom_margin));
self.union_rect = self.union_rect.union(&margin).union(&padding);
}
None => {
self.level = Some(level);
self.is_child = true;
self.overflow_direction = overflow_direction(&fragment.style.writing_mode);
self.origin_rect = Rect::new(Point2D::new(left_padding, top_padding),
Size2D::new(right_padding, bottom_padding));
},
};
}
fn should_process(&mut self, fragment: &Fragment) -> bool {
fragment.contains_node(self.node_address) || self.is_child
}
}
// https://drafts.csswg.org/cssom-view/#extensions-to-the-htmlelement-interface
impl FragmentBorderBoxIterator for ParentOffsetBorderBoxIterator {
fn process(&mut self, fragment: &Fragment, level: i32, border_box: &Rect<Au>) {
if self.node_offset_box.is_none() {
// We haven't found the node yet, so we're still looking
// for its parent. Remove all nodes at this level or
// higher, as they can't be parents of this node.
self.parent_nodes.truncate(level as usize);
assert_eq!(self.parent_nodes.len(), level as usize,
"Skipped at least one level in the flow tree!");
}
if !fragment.is_primary_fragment() {
// This fragment doesn't correspond to anything worth
// taking measurements from.
if self.node_offset_box.is_none() {
// If this is the only fragment in the flow, we need to
// do this to avoid failing the above assertion.
self.parent_nodes.push(None);
}
return;
}
if fragment.node == self.node_address {
// Found the fragment in the flow tree that matches the
// DOM node being looked for.
assert!(self.node_offset_box.is_none(),
"Node was being treated as inline, but it has an associated fragment!");
self.has_processed_node = true;
self.node_offset_box = Some(NodeOffsetBoxInfo {
offset: border_box.origin,
rectangle: *border_box,
});
// offsetParent returns null if the node is fixed.
if fragment.style.get_box().position == computed_values::position::T::fixed {
self.parent_nodes.clear();
}
} else if let Some(node) = fragment.inline_context.as_ref().and_then(|inline_context| {
inline_context.nodes.iter().find(|node| node.address == self.node_address)
}) {
// TODO: Handle cases where the `offsetParent` is an inline
// element. This will likely be impossible until
// https://github.com/servo/servo/issues/13982 is fixed.
// Found a fragment in the flow tree whose inline context
// contains the DOM node we're looking for, i.e. the node
// is inline and contains this fragment.
match self.node_offset_box {
Some(NodeOffsetBoxInfo { ref mut rectangle, .. }) => {
*rectangle = rectangle.union(border_box);
},
None => {
// https://github.com/servo/servo/issues/13982 will
// cause this assertion to fail sometimes, so it's
// commented out for now.
/*assert!(node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT),
"First fragment of inline node found wasn't its first fragment!");*/
self.node_offset_box = Some(NodeOffsetBoxInfo {
offset: border_box.origin,
rectangle: *border_box,
});
},
}
if node.flags.contains(LAST_FRAGMENT_OF_ELEMENT) {
self.has_processed_node = true;
}
} else if self.node_offset_box.is_none() {
// TODO(gw): Is there a less fragile way of checking whether this
// fragment is the body element, rather than just checking that
// it's at level 1 (below the root node)?
let is_body_element = level == 1;
let is_valid_parent = match (is_body_element,
fragment.style.get_box().position,
&fragment.specific) {
// Spec says it's valid if any of these are true:
// 1) Is the body element
// 2) Is static position *and* is a table or table cell
// 3) Is not static position
(true, _, _) |
(false, computed_values::position::T::static_, &SpecificFragmentInfo::Table) |
(false, computed_values::position::T::static_, &SpecificFragmentInfo::TableCell) |
(false, computed_values::position::T::absolute, _) |
(false, computed_values::position::T::relative, _) |
(false, computed_values::position::T::fixed, _) => true,
// Otherwise, it's not a valid parent
(false, computed_values::position::T::static_, _) => false,
};
let parent_info = if is_valid_parent {
let border_width = fragment.border_width().to_physical(fragment.style.writing_mode);
Some(ParentBorderBoxInfo {
node_address: fragment.node,
origin: border_box.origin + Vector2D::new(border_width.left, border_width.top),
})
} else {
None
};
self.parent_nodes.push(parent_info);
}
}
fn should_process(&mut self, _: &Fragment) -> bool {
!self.has_processed_node
}
}
pub fn process_node_geometry_request<N: LayoutNode>(requested_node: N, layout_root: &mut Flow)
-> Rect<i32> {
let mut iterator = FragmentLocatingFragmentIterator::new(requested_node.opaque());
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
iterator.client_rect
}
pub fn process_node_scroll_root_id_request<N: LayoutNode>(id: PipelineId,
requested_node: N)
-> ClipId {
let layout_node = requested_node.to_threadsafe();
layout_node.generate_scroll_root_id(id)
}
pub fn process_node_scroll_area_request< N: LayoutNode>(requested_node: N, layout_root: &mut Flow)
-> Rect<i32> {
let mut iterator = UnioningFragmentScrollAreaIterator::new(requested_node.opaque());
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
match iterator.overflow_direction {
OverflowDirection::RightAndDown => {
let right = max(iterator.union_rect.size.width, iterator.origin_rect.size.width);
let bottom = max(iterator.union_rect.size.height, iterator.origin_rect.size.height);
Rect::new(iterator.origin_rect.origin, Size2D::new(right, bottom))
},
OverflowDirection::LeftAndDown => {
let bottom = max(iterator.union_rect.size.height, iterator.origin_rect.size.height);
let left = max(iterator.union_rect.origin.x, iterator.origin_rect.origin.x);
Rect::new(Point2D::new(left, iterator.origin_rect.origin.y),
Size2D::new(iterator.origin_rect.size.width, bottom))
},
OverflowDirection::LeftAndUp => {
let top = min(iterator.union_rect.origin.y, iterator.origin_rect.origin.y);
let left = min(iterator.union_rect.origin.x, iterator.origin_rect.origin.x);
Rect::new(Point2D::new(left, top), iterator.origin_rect.size)
},
OverflowDirection::RightAndUp => {
let top = min(iterator.union_rect.origin.y, iterator.origin_rect.origin.y);
let right = max(iterator.union_rect.size.width, iterator.origin_rect.size.width);
Rect::new(Point2D::new(iterator.origin_rect.origin.x, top),
Size2D::new(right, iterator.origin_rect.size.height))
}
}
}
/// Return the resolved value of property for a given (pseudo)element.
/// https://drafts.csswg.org/cssom/#resolved-value
pub fn process_resolved_style_request<'a, N>(context: &LayoutContext,
node: N,
pseudo: &Option<PseudoElement>,
property: &PropertyId,
layout_root: &mut Flow) -> String
where N: LayoutNode,
{
use style::stylist::RuleInclusion;
use style::traversal::resolve_style;
let element = node.as_element().unwrap();
// We call process_resolved_style_request after performing a whole-document
// traversal, so in the common case, the element is styled.
if element.get_data().is_some() {
return process_resolved_style_request_internal(node, pseudo, property, layout_root);
}
// In a display: none subtree. No pseudo-element exists.
if pseudo.is_some() {
return String::new();
}
let mut tlc = ThreadLocalStyleContext::new(&context.style_context);
let mut context = StyleContext {
shared: &context.style_context,
thread_local: &mut tlc,
};
let styles = resolve_style(&mut context, element, RuleInclusion::All, false);
let style = styles.primary();
let longhand_id = match *property {
PropertyId::Longhand(id) => id,
// Firefox returns blank strings for the computed value of shorthands,
// so this should be web-compatible.
PropertyId::Shorthand(_) => return String::new(),
PropertyId::Custom(ref name) => {
return style.computed_value_to_string(PropertyDeclarationId::Custom(name))
}
};
// No need to care about used values here, since we're on a display: none
// subtree, use the resolved value.
style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id))
}
/// The primary resolution logic, which assumes that the element is styled.
fn process_resolved_style_request_internal<'a, N>(
requested_node: N,
pseudo: &Option<PseudoElement>,
property: &PropertyId,
layout_root: &mut Flow,
) -> String
where
N: LayoutNode,
{
let layout_el = requested_node.to_threadsafe().as_element().unwrap();
let layout_el = match *pseudo {
Some(PseudoElement::Before) => layout_el.get_before_pseudo(),
Some(PseudoElement::After) => layout_el.get_after_pseudo(),
Some(PseudoElement::DetailsSummary) |
Some(PseudoElement::DetailsContent) |
Some(PseudoElement::Selection) => None,
// FIXME(emilio): What about the other pseudos? Probably they shouldn't
// just return the element's style!
_ => Some(layout_el)
};
let layout_el = match layout_el {
None => {
// The pseudo doesn't exist, return nothing. Chrome seems to query
// the element itself in this case, Firefox uses the resolved value.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=29006
return String::new();
}
Some(layout_el) => layout_el
};
let style = &*layout_el.resolved_style();
let longhand_id = match *property {
PropertyId::Longhand(id) => id,
// Firefox returns blank strings for the computed value of shorthands,
// so this should be web-compatible.
PropertyId::Shorthand(_) => return String::new(),
PropertyId::Custom(ref name) => {
return style.computed_value_to_string(PropertyDeclarationId::Custom(name))
}
};
let positioned = match style.get_box().position {
position::computed_value::T::relative |
/*position::computed_value::T::sticky |*/
position::computed_value::T::fixed |
position::computed_value::T::absolute => true,
_ => false
};
//TODO: determine whether requested property applies to the element.
// eg. width does not apply to non-replaced inline elements.
// Existing browsers disagree about when left/top/right/bottom apply
// (Chrome seems to think they never apply and always returns resolved values).
// There are probably other quirks.
let applies = true;
fn used_value_for_position_property<N: LayoutNode>(
layout_el: <N::ConcreteThreadSafeLayoutNode as ThreadSafeLayoutNode>::ConcreteThreadSafeLayoutElement,
layout_root: &mut Flow,
requested_node: N,
longhand_id: LonghandId) -> String {
let maybe_data = layout_el.borrow_layout_data();
let position = maybe_data.map_or(Point2D::zero(), |data| {
match (*data).flow_construction_result {
ConstructionResult::Flow(ref flow_ref, _) =>
flow::base(flow_ref.deref()).stacking_relative_position.to_point(),
// TODO(dzbarsky) search parents until we find node with a flow ref.
// https://github.com/servo/servo/issues/8307
_ => Point2D::zero()
}
});
let property = match longhand_id {
LonghandId::Bottom => PositionProperty::Bottom,
LonghandId::Top => PositionProperty::Top,
LonghandId::Left => PositionProperty::Left,
LonghandId::Right => PositionProperty::Right,
LonghandId::Width => PositionProperty::Width,
LonghandId::Height => PositionProperty::Height,
_ => unreachable!()
};
let mut iterator =
PositionRetrievingFragmentBorderBoxIterator::new(requested_node.opaque(),
property,
position);
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root,
&mut iterator);
iterator.result.map(|r| r.to_css_string()).unwrap_or(String::new())
}
// TODO: we will return neither the computed nor used value for margin and padding.
match longhand_id {
LonghandId::MarginBottom | LonghandId::MarginTop |
LonghandId::MarginLeft | LonghandId::MarginRight |
LonghandId::PaddingBottom | LonghandId::PaddingTop |
LonghandId::PaddingLeft | LonghandId::PaddingRight
if applies && style.get_box().display != display::computed_value::T::none => {
let (margin_padding, side) = match longhand_id {
LonghandId::MarginBottom => (MarginPadding::Margin, Side::Bottom),
LonghandId::MarginTop => (MarginPadding::Margin, Side::Top),
LonghandId::MarginLeft => (MarginPadding::Margin, Side::Left),
LonghandId::MarginRight => (MarginPadding::Margin, Side::Right),
LonghandId::PaddingBottom => (MarginPadding::Padding, Side::Bottom),
LonghandId::PaddingTop => (MarginPadding::Padding, Side::Top),
LonghandId::PaddingLeft => (MarginPadding::Padding, Side::Left),
LonghandId::PaddingRight => (MarginPadding::Padding, Side::Right),
_ => unreachable!()
};
let mut iterator =
MarginRetrievingFragmentBorderBoxIterator::new(requested_node.opaque(),
side,
margin_padding,
style.writing_mode);
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root,
&mut iterator);
iterator.result.map(|r| r.to_css_string()).unwrap_or(String::new())
},
LonghandId::Bottom | LonghandId::Top | LonghandId::Right | LonghandId::Left
if applies && positioned && style.get_box().display !=
display::computed_value::T::none => {
used_value_for_position_property(layout_el, layout_root, requested_node, longhand_id)
}
LonghandId::Width | LonghandId::Height
if applies && style.get_box().display !=
display::computed_value::T::none => {
used_value_for_position_property(layout_el, layout_root, requested_node, longhand_id)
}
// FIXME: implement used value computation for line-height
_ => {
style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id))
}
}
}
pub fn process_offset_parent_query<N: LayoutNode>(requested_node: N, layout_root: &mut Flow)
-> OffsetParentResponse {
let mut iterator = ParentOffsetBorderBoxIterator::new(requested_node.opaque());
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
let node_offset_box = iterator.node_offset_box;
let parent_info = iterator.parent_nodes.into_iter().rev().filter_map(|info| info).next();
match (node_offset_box, parent_info) {
(Some(node_offset_box), Some(parent_info)) => {
let origin = node_offset_box.offset - parent_info.origin.to_vector();
let size = node_offset_box.rectangle.size;
OffsetParentResponse {
node_address: Some(parent_info.node_address.to_untrusted_node_address()),
rect: Rect::new(origin, size),
}
}
_ => {
OffsetParentResponse::empty()
}
}
}
pub fn process_node_overflow_request<N: LayoutNode>(requested_node: N) -> NodeOverflowResponse {
let layout_node = requested_node.to_threadsafe();
let style = &*layout_node.as_element().unwrap().resolved_style();
let style_box = style.get_box();
NodeOverflowResponse(Some((Point2D::new(style_box.overflow_x, style_box.overflow_y))))
}
pub fn process_margin_style_query<N: LayoutNode>(requested_node: N)
-> MarginStyleResponse {
let layout_node = requested_node.to_threadsafe();
let style = &*layout_node.as_element().unwrap().resolved_style();
let margin = style.get_margin();
MarginStyleResponse {
top: margin.margin_top,
right: margin.margin_right,
bottom: margin.margin_bottom,
left: margin.margin_left,
}
}<|fim▁end|>
|
border_left_width: left_width,
..
} = *fragment.style.get_border();
self.client_rect.origin.y = top_width.0.to_px();
|
<|file_name|>oaipmh.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# =================================================================
#
# Authors: Tom Kralidis <[email protected]>
#
# Copyright (c) 2015 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================
import logging
from pycsw.core import util
from pycsw.core.etree import etree
LOGGER = logging.getLogger(__name__)
class OAIPMH(object):
"""OAI-PMH wrapper class"""
def __init__(self, context, config):
LOGGER.debug('Initializing OAI-PMH constants')
self.oaipmh_version = '2.0'
self.namespaces = {
'oai': 'http://www.openarchives.org/OAI/2.0/',
'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
}
self.request_model = {
'Identify': [],
'ListSets': ['resumptiontoken'],
'ListMetadataFormats': ['identifier'],
'GetRecord': ['identifier', 'metadataprefix'],
'ListRecords': ['from', 'until', 'set', 'resumptiontoken', 'metadataprefix'],
'ListIdentifiers': ['from', 'until', 'set', 'resumptiontoken', 'metadataprefix'],
}
self.metadata_formats = {
'iso19139': {
'namespace': 'http://www.isotc211.org/2005/gmd',
'schema': 'http://www.isotc211.org/2005/gmd/gmd.xsd',
'identifier': './/gmd:fileIdentifier/gco:CharacterString',
'dateStamp': './/gmd:dateStamp/gco:DateTime|.//gmd:dateStamp/gco:Date',
'setSpec': './/gmd:hierarchyLevel/gmd:MD_ScopeCode'
},
'csw-record': {
'namespace': 'http://www.opengis.net/cat/csw/2.0.2',
'schema': 'http://schemas.opengis.net/csw/2.0.2/record.xsd',<|fim▁hole|> 'setSpec': './/dc:type'
},
'fgdc-std': {
'namespace': 'http://www.opengis.net/cat/csw/csdgm',
'schema': 'http://www.fgdc.gov/metadata/fgdc-std-001-1998.xsd',
'identifier': './/idinfo/datasetid',
'dateStamp': './/metainfo/metd',
'setSpec': './/dataset'
},
'oai_dc': {
'namespace': '%soai_dc/' % self.namespaces['oai'],
'schema': 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',
'identifier': './/dc:identifier',
'dateStamp': './/dct:modified',
'setSpec': './/dc:type'
},
'dif': {
'namespace': 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/',
'schema': 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/dif.xsd',
'identifier': './/dif:Entry_ID',
'dateStamp': './/dif:Last_DIF_Revision_Date',
'setSpec': '//dataset'
},
'gm03': {
'namespace': 'http://www.interlis.ch/INTERLIS2.3',
'schema': 'http://www.geocat.ch/internet/geocat/en/home/documentation/gm03.parsys.50316.downloadList.86742.DownloadFile.tmp/gm0321.zip',
'identifier': './/gm03:DATASECTION//gm03:fileIdentifer',
'dateStamp': './/gm03:DATASECTION//gm03:dateStamp',
'setSpec': './/dataset'
}
}
self.metadata_sets = {
'datasets': ('Datasets', 'dataset'),
'interactiveResources': ('Interactive Resources', 'service')
}
self.error_codes = {
'badArgument': 'InvalidParameterValue',
'badVerb': 'OperationNotSupported',
'idDoesNotExist': None,
'noRecordsMatch': None,
}
self.context = context
self.context.namespaces.update(self.namespaces)
self.context.namespaces.update({'gco': 'http://www.isotc211.org/2005/gco'})
self.config = config
def request(self, kvp):
"""process OAI-PMH request"""
kvpout = {'service': 'CSW', 'version': '2.0.2', 'mode': 'oaipmh'}
LOGGER.debug('Incoming kvp: %s', kvp)
if 'verb' in kvp:
if 'metadataprefix' in kvp:
self.metadata_prefix = kvp['metadataprefix']
try:
kvpout['outputschema'] = self._get_metadata_prefix(kvp['metadataprefix'])
except KeyError:
kvpout['outputschema'] = kvp['metadataprefix']
else:
self.metadata_prefix = 'csw-record'
LOGGER.debug('metadataPrefix: %s', self.metadata_prefix)
if kvp['verb'] in ['ListRecords', 'ListIdentifiers', 'GetRecord']:
kvpout['request'] = 'GetRecords'
kvpout['resulttype'] = 'results'
kvpout['typenames'] = 'csw:Record'
kvpout['elementsetname'] = 'full'
if kvp['verb'] in ['Identify', 'ListMetadataFormats', 'ListSets']:
kvpout['request'] = 'GetCapabilities'
elif kvp['verb'] == 'GetRecord':
kvpout['request'] = 'GetRecordById'
if 'identifier' in kvp:
kvpout['id'] = kvp['identifier']
if ('outputschema' in kvpout and
kvp['metadataprefix'] == 'oai_dc'): # just use default DC
del kvpout['outputschema']
elif kvp['verb'] in ['ListRecords', 'ListIdentifiers']:
if 'resumptiontoken' in kvp:
kvpout['startposition'] = kvp['resumptiontoken']
if ('outputschema' in kvpout and
kvp['verb'] == 'ListIdentifiers'): # simple output only
pass #del kvpout['outputschema']
if ('outputschema' in kvpout and
kvp['metadataprefix'] in ['dc', 'oai_dc']): # just use default DC
del kvpout['outputschema']
start = end = None
LOGGER.debug('Scanning temporal parameters')
if 'from' in kvp:
start = 'dc:date >= %s' % kvp['from']
if 'until' in kvp:
end = 'dc:date <= %s' % kvp['until']
if any([start is not None, end is not None]):
if all([start is not None, end is not None]):
time_query = '%s and %s' % (start, end)
elif end is None:
time_query = start
elif start is None:
time_query = end
kvpout['constraintlanguage'] = 'CQL_TEXT'
kvpout['constraint'] = time_query
LOGGER.debug('Resulting parameters: %s', kvpout)
return kvpout
def response(self, response, kvp, repository, server_url):
"""process OAI-PMH request"""
mode = kvp.pop('mode', None)
if 'config' in kvp:
config_val = kvp.pop('config')
url = '%smode=oaipmh' % util.bind_url(server_url)
node = etree.Element(util.nspath_eval('oai:OAI-PMH', self.namespaces), nsmap=self.namespaces)
node.set(util.nspath_eval('xsi:schemaLocation', self.namespaces), '%s http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd' % self.namespaces['oai'])
LOGGER.debug(etree.tostring(node))
etree.SubElement(node, util.nspath_eval('oai:responseDate', self.namespaces)).text = util.get_today_and_now()
etree.SubElement(node, util.nspath_eval('oai:request', self.namespaces), attrib=kvp).text = url
if 'verb' not in kvp:
etree.SubElement(node, util.nspath_eval('oai:error', self.namespaces), code='badArgument').text = 'Missing \'verb\' parameter'
return node
if kvp['verb'] not in self.request_model.keys():
etree.SubElement(node, util.nspath_eval('oai:error', self.namespaces), code='badArgument').text = 'Unknown verb \'%s\'' % kvp['verb']
return node
if etree.QName(response).localname == 'ExceptionReport':
etree.SubElement(node, util.nspath_eval('oai:error', self.namespaces), code='badArgument').text = response.xpath('//ows:ExceptionText|//ows20:ExceptionText', namespaces=self.context.namespaces)[0].text
return node
verb = kvp.pop('verb')
if verb in ['GetRecord', 'ListIdentifiers', 'ListRecords']:
if 'metadataprefix' not in kvp:
etree.SubElement(node, util.nspath_eval('oai:error', self.namespaces), code='badArgument').text = 'Missing metadataPrefix parameter'
return node
elif kvp['metadataprefix'] not in self.metadata_formats.keys():
etree.SubElement(node, util.nspath_eval('oai:error', self.namespaces), code='badArgument').text = 'Invalid metadataPrefix parameter'
return node
for key, value in kvp.items():
if key != 'mode' and key not in self.request_model[verb]:
etree.SubElement(node, util.nspath_eval('oai:error', self.namespaces), code='badArgument').text = 'Illegal parameter \'%s\'' % key
return node
verbnode = etree.SubElement(node, util.nspath_eval('oai:%s' % verb, self.namespaces))
if verb == 'Identify':
etree.SubElement(verbnode, util.nspath_eval('oai:repositoryName', self.namespaces)).text = self.config.get('metadata:main', 'identification_title')
etree.SubElement(verbnode, util.nspath_eval('oai:baseURL', self.namespaces)).text = url
etree.SubElement(verbnode, util.nspath_eval('oai:protocolVersion', self.namespaces)).text = '2.0'
etree.SubElement(verbnode, util.nspath_eval('oai:adminEmail', self.namespaces)).text = self.config.get('metadata:main', 'contact_email')
etree.SubElement(verbnode, util.nspath_eval('oai:earliestDatestamp', self.namespaces)).text = repository.query_insert('min')
etree.SubElement(verbnode, util.nspath_eval('oai:deletedRecord', self.namespaces)).text = 'no'
etree.SubElement(verbnode, util.nspath_eval('oai:granularity', self.namespaces)).text = 'YYYY-MM-DDThh:mm:ssZ'
elif verb == 'ListSets':
for key, value in sorted(self.metadata_sets.items()):
setnode = etree.SubElement(verbnode, util.nspath_eval('oai:set', self.namespaces))
etree.SubElement(setnode, util.nspath_eval('oai:setSpec', self.namespaces)).text = key
etree.SubElement(setnode, util.nspath_eval('oai:setName', self.namespaces)).text = value[0]
elif verb == 'ListMetadataFormats':
for key, value in sorted(self.metadata_formats.items()):
mdfnode = etree.SubElement(verbnode, util.nspath_eval('oai:metadataFormat', self.namespaces))
etree.SubElement(mdfnode, util.nspath_eval('oai:metadataPrefix', self.namespaces)).text = key
etree.SubElement(mdfnode, util.nspath_eval('oai:schema', self.namespaces)).text = value['schema']
etree.SubElement(mdfnode, util.nspath_eval('oai:metadataNamespace', self.namespaces)).text = value['namespace']
elif verb in ['GetRecord', 'ListIdentifiers', 'ListRecords']:
if verb == 'GetRecord': # GetRecordById
records = response.getchildren()
else: # GetRecords
records = response.getchildren()[1].getchildren()
for child in records:
recnode = etree.SubElement(verbnode, util.nspath_eval('oai:record', self.namespaces))
header = etree.SubElement(recnode, util.nspath_eval('oai:header', self.namespaces))
self._transform_element(header, child, 'oai:identifier')
self._transform_element(header, child, 'oai:dateStamp')
self._transform_element(header, child, 'oai:setSpec')
if verb in ['GetRecord', 'ListRecords']:
metadata = etree.SubElement(recnode, util.nspath_eval('oai:metadata', self.namespaces))
if 'metadataprefix' in kvp and kvp['metadataprefix'] == 'oai_dc':
child.tag = util.nspath_eval('oai_dc:dc', self.namespaces)
metadata.append(child)
if verb != 'GetRecord':
complete_list_size = response.xpath('//@numberOfRecordsMatched')[0]
next_record = response.xpath('//@nextRecord')[0]
cursor = str(int(complete_list_size) - int(next_record) - 1)
resumption_token = etree.SubElement(verbnode, util.nspath_eval('oai:resumptionToken', self.namespaces),
completeListSize=complete_list_size, cursor=cursor).text = next_record
return node
def _get_metadata_prefix(self, prefix):
"""Convenience function to return metadataPrefix as CSW outputschema"""
try:
outputschema = self.metadata_formats[prefix]['namespace']
except KeyError:
outputschema = prefix
return outputschema
def _transform_element(self, parent, element, elname):
"""tests for existence of a given xpath, writes out text if exists"""
xpath = self.metadata_formats[self.metadata_prefix][elname.split(':')[1]]
if xpath.startswith(('.//', '//')):
value = element.xpath(xpath, namespaces=self.context.namespaces)
if value:
value = value[0].text
else: # bare string literal
value = xpath
el = etree.SubElement(parent, util.nspath_eval(elname, self.context.namespaces))
if value:
if elname == 'oai:setSpec':
value = None
for k, v in self.metadata_sets.items():
if v[1] == elname:
value = k
break
el.text = value<|fim▁end|>
|
'identifier': './/dc:identifier',
'dateStamp': './/dct:modified',
|
<|file_name|>forms.py<|end_file_name|><|fim▁begin|><|fim▁hole|># This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from wtforms_sqlalchemy.fields import QuerySelectField
from indico.core.db.sqlalchemy.descriptions import RenderMode
from indico.modules.events.sessions.models.sessions import Session
from indico.modules.events.tracks.models.groups import TrackGroup
from indico.util.i18n import _
from indico.web.forms.base import IndicoForm, generated_data
from indico.web.forms.fields import IndicoMarkdownField
class TrackForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()])
code = StringField(_('Code'))
track_group = QuerySelectField(_('Track group'), default='', allow_blank=True, get_label='title',
description=_('Select a track group to which this track should belong'))
default_session = QuerySelectField(_('Default session'), default='', allow_blank=True, get_label='title',
description=_('Indico will preselect this session whenever an abstract is '
'accepted for the track'))
description = IndicoMarkdownField(_('Description'), editor=True)
def __init__(self, *args, **kwargs):
event = kwargs.pop('event')
super().__init__(*args, **kwargs)
self.default_session.query = Session.query.with_parent(event)
self.track_group.query = TrackGroup.query.with_parent(event)
class ProgramForm(IndicoForm):
program = IndicoMarkdownField(_('Program'), editor=True, mathjax=True)
@generated_data
def program_render_mode(self):
return RenderMode.markdown
class TrackGroupForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()])
description = IndicoMarkdownField(_('Description'), editor=True)<|fim▁end|>
| |
<|file_name|>rpn.rs<|end_file_name|><|fim▁begin|>//! Uses RPN expression
extern crate rand;
fn main() {
use rand::Rng;
use std::io::{self, Write};
let mut rng = rand::thread_rng();
let stdin = io::stdin();
let mut stdout = io::stdout();
// generating 4 numbers
let choices: Vec<u32> = (0..4).map(|_| rng.gen_range(1, 10)).collect();
println!("Make 24 with the following numbers");
// start the game loop
let mut buffer = String::new();
loop {
println!(
"Your numbers: {}, {}, {}, {}",
choices[0], choices[1], choices[2], choices[3]
);<|fim▁hole|> buffer.clear();
stdin.read_line(&mut buffer).expect("Failed to read line!");
match check_input(&buffer[..], &choices[..]) {
Ok(()) => {
println!("Good job!");
break;
}
Err(e) => println!("{}", e),
}
print!("Try again? (y/n): ");
stdout.flush().unwrap();
buffer.clear();
stdin.read_line(&mut buffer).expect("Failed to read line!");
if buffer.trim() != "y" {
break;
}
}
}
fn check_input(expr: &str, choices: &[u32]) -> Result<(), String> {
let mut stack: Vec<u32> = Vec::new();
for token in expr.split_whitespace() {
if is_operator(token) {
let (a, b) = (stack.pop(), stack.pop());
match (a, b) {
(Some(x), Some(y)) => stack.push(evaluate(y, x, token)),
(_, _) => return Err("Not a valid RPN expression!".to_string()),
}
} else {
match token.parse::<u32>() {
Ok(n) => {
// check if the number is valid
if !choices.contains(&n) {
return Err(format!("Cannot use {}", n));
}
stack.push(n)
}
Err(_) => return Err(format!("Invalid input: {}", token)),
}
}
}
let ans = stack.pop();
if !stack.is_empty() {
return Err("Not a valid RPN expression!".to_string());
}
match ans {
Some(x) if x == 24 => Ok(()),
Some(x) => Err(format!("Wrong answer. Result: {}", x)),
None => Err("Error encountered!".to_string()),
}
}
fn evaluate(a: u32, b: u32, op: &str) -> u32 {
match op {
"+" => a + b,
"-" => a - b,
"*" => a * b,
"/" => a / b,
_ => unreachable!(),
}
}
fn is_operator(op: &str) -> bool {
["*", "-", "+", "/"].contains(&op)
}
#[cfg(tests)]
mod tests {
const v1: [u32; 4] = [4u32, 3, 6, 2];
#[test]
fn correct_result() {
assert_eq!(check_input("4 3 * 6 2 * +", &v1), Ok(()));
}
#[test]
fn incorrect_result() {
assert_eq!(
check_input("4 3 * 2 6 + -", &v1),
Err("Wrong answer. Result: 4".to_string())
);
}
#[test]
fn wrong_numbers_in_input() {
assert_eq!(
check_input("4 5 + 6 2 * -", &v1),
Err("Cannot use 5".to_string())
);
}
#[test]
fn invalid_chars_in_input() {
assert_eq!(
check_input("4 ) + _ 2 * -", &v1),
Err("Invalid input: )".to_string())
);
}
fn invalid_rpn_expression() {
assert_eq!(
check_input("4 3 + 6 2 *", &v1),
Err("Not a valid RPN expression!".to_string())
);
}
}<|fim▁end|>
| |
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from odoo import models, fields, api
class fixing_issues_view(models.Model):<|fim▁hole|> _inherit = 'project.issue'<|fim▁end|>
| |
<|file_name|>Sprite.java<|end_file_name|><|fim▁begin|>/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA<|fim▁hole|>import java.awt.*;
/**
* This interface describes objects that can paint themselves, possibly varying
* as a function of time.
*
* @author Eric Lafortune
*/
public interface Sprite
{
/**
* Paints the object.
*
* @param graphics the Graphics to paint on.
* @param time the time since the start of the animation, expressed in
* milliseconds.
*/
public void paint(Graphics graphics, long time);
}<|fim▁end|>
|
*/
package proguard.gui.splash;
|
<|file_name|>node_array.go<|end_file_name|><|fim▁begin|>// Copyright 2015 Liu Dong <[email protected]>.
// Licensed under the MIT license.
package flydb
import (
"fmt"
)
func NewArrayNode(v []interface{}) (*ArrayNode, error) {
node := &ArrayNode {
}
if err := node.SetRaw(v); err != nil {
return nil, err
}
return node, nil
}
// Array node contains list of nodes
type ArrayNode struct {
data []*Node
}
func (this *ArrayNode) SetRaw(raw interface{}) (error) {
rawArray, ok := raw.([]interface{})
if !ok {
return fmt.Errorf("raw data is not an array")
}
data := make([]*Node, len(rawArray))
for k, v := range rawArray {
node, err := CreateNode(v)
if err != nil {
return err
}
data[k] = node
}
this.data = data
return nil<|fim▁hole|>func (this *ArrayNode) GetRaw() interface{} {
result := make([]interface{}, len(this.data))
for i, v := range this.data {
result[i] = v.GetRaw()
}
return result
}
func (this *ArrayNode) Append(data interface{}) error {
node, err := CreateNode(data)
if err != nil {
return err
}
this.data = append(this.data, node)
return nil
}
func (this *ArrayNode) Get(i int) (*Node, error) {
if i < 0 || i >= len(this.data) {
return nil, fmt.Errorf("key out of range: %d", i)
}
return this.data[i], nil
}
func (this *ArrayNode) Set(i int, data interface{}) error {
if i < 0 || i >= len(this.data) {
return fmt.Errorf("key out of range: %d", i)
}
node, err := CreateNode(data)
if err != nil {
return err
}
this.data[i] = node
return nil
}
func (this *ArrayNode) Delete(key int) {
if key < 0 || key >= len(this.data) {
return
}
this.data = append(this.data[0:key], this.data[key+1:]...)
}
func (this *ArrayNode) Length() int {
return len(this.data)
}<|fim▁end|>
|
}
|
<|file_name|>reset.cpp<|end_file_name|><|fim▁begin|>#include <iostream>
#include <plog/Log.h>
#include "libaps2.h"
#include "../C++/helpers.h"
#include "../C++/optionparser.h"
#include <concol.h>
using std::cout;
using std::endl;
enum optionIndex { UNKNOWN, HELP, IP_ADDR, RESET_MODE, LOG_LEVEL };
const option::Descriptor usage[] = {
{UNKNOWN, 0, "", "", option::Arg::None, "USAGE: reset [options]\n\n"
"Options:"},
{HELP, 0, "", "help", option::Arg::None,
" --help \tPrint usage and exit."},
{IP_ADDR, 0, "", "ipAddr", option::Arg::NonEmpty,
" --ipAddr \tIP address of unit to program (optional)."},
{RESET_MODE, 0, "", "resetMode", option::Arg::NonEmpty,
" --resetMode \tWhat type of reset to do (USER_IMAGE,BASE_IMAGE,TCP) "
"(optional)."},
{LOG_LEVEL, 0, "", "logLevel", option::Arg::Numeric,
" --logLevel \t(optional) Logging level level to print (optional; "
"default=3/DEBUG)."},
{UNKNOWN, 0, "", "", option::Arg::None, "\nExamples:\n"
" flash --IP\n"
" flash --SPI\n"},
{0, 0, 0, 0, 0, 0}};
APS2_RESET_MODE get_reset_mode() {
cout << concol::RED << "Reset options:" << concol::RESET << endl;
cout << "1) Reset to user image" << endl;
cout << "2) Reset to backup image" << endl;
cout << "3) Reset tcp connection" << endl << endl;
cout << "Choose option [1]: ";
char input;
cin.get(input);
switch (input) {
case '1':
default:
return RECONFIG_EPROM_USER;
break;
case '2':
return RECONFIG_EPROM_BASE;
break;
case '3':
return RESET_TCP;
break;
}
}
int main(int argc, char *argv[]) {
print_title("BBN APS2 Reset Utility");
argc -= (argc > 0);
argv += (argc > 0); // skip program name argv[0] if present
option::Stats stats(usage, argc, argv);
option::Option *options = new option::Option[stats.options_max];
option::Option *buffer = new option::Option[stats.buffer_max];
option::Parser parse(usage, argc, argv, options, buffer);
if (parse.error())
return -1;
if (options[HELP]) {
option::printUsage(std::cout, usage);
return 0;
}
// Logging level
plog::Severity logLevel = plog::debug;
if (options[LOG_LEVEL]) {
//TODO: Input validation??
logLevel = static_cast<plog::Severity>(atoi(options[LOG_LEVEL].arg));
}
set_file_logging_level(logLevel);
set_console_logging_level(plog::info);
string deviceSerial;
if (options[IP_ADDR]) {
deviceSerial = string(options[IP_ADDR].arg);
cout << "Programming device " << deviceSerial << endl;
} else {
deviceSerial = get_device_id();
}
if ( deviceSerial.empty() ) {
cout << concol::RED << "No APS2 devices connected! Exiting..."
<< concol::RESET << endl;
return 0;
}
APS2_RESET_MODE mode;
if (options[RESET_MODE]) {
std::map<string, APS2_RESET_MODE> mode_map{
{"USER_IMAGE", RECONFIG_EPROM_USER},
{"BASE_IMAGE", RECONFIG_EPROM_BASE},
{"TCP", RESET_TCP}};
string mode_str(options[RESET_MODE].arg);
if (mode_map.count(mode_str)) {
mode = mode_map[mode_str];
} else {<|fim▁hole|> std::cerr << concol::RED << "Unexpected reset mode" << concol::RESET
<< endl;
return -1;
}
} else {
mode = get_reset_mode();
}
if (mode != RESET_TCP) {
connect_APS(deviceSerial.c_str());
}
reset(deviceSerial.c_str(), mode);
if (mode != RESET_TCP) {
disconnect_APS(deviceSerial.c_str());
}
cout << concol::RED << "Finished!" << concol::RESET << endl;
return 0;
}<|fim▁end|>
| |
<|file_name|>test_sagemaker_base.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import unittest
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.sensors.sagemaker_base import SageMakerBaseSensor
class TestSagemakerBaseSensor(unittest.TestCase):
def test_execute(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
<|fim▁hole|> return {
'SomeKey': {'State': 'COMPLETED'},
'ResponseMetadata': {'HTTPStatusCode': 200}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
sensor.execute(None)
def test_poke_with_unfinished_job(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
return {
'SomeKey': {'State': 'PENDING'},
'ResponseMetadata': {'HTTPStatusCode': 200}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertEqual(sensor.poke(None), False)
def test_poke_with_not_implemented_method(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertRaises(NotImplementedError, sensor.poke, None)
def test_poke_with_bad_response(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
return {
'SomeKey': {'State': 'COMPLETED'},
'ResponseMetadata': {'HTTPStatusCode': 400}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertEqual(sensor.poke(None), False)
def test_poke_with_job_failure(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
return {
'SomeKey': {'State': 'FAILED'},
'ResponseMetadata': {'HTTPStatusCode': 200}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertRaises(AirflowException, sensor.poke, None)
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible<|fim▁hole|>@python_2_unicode_compatible
class DockerServer(models.Model):
name = models.CharField(max_length=255, unique=True)
version = models.CharField(max_length=255, default='auto')
docker_host = models.CharField(max_length=255)
docker_tls_verify = models.BooleanField(default=True)
docker_cert_path = models.CharField(max_length=255, null=True, blank=True)
def get_env(self):
env = {
'DOCKER_HOST': self.docker_host
}
if self.docker_tls_verify:
env['DOCKER_TLS_VERIFY'] = self.docker_tls_verify
if self.docker_cert_path:
env['DOCKER_CERT_PATH'] = self.docker_cert_path
return env
def get_client(self):
client = docker.from_env(
version=self.version,
environment=self.get_env()
)
return client
def __str__(self):
return 'Docker Server: %s' % self.name<|fim▁end|>
|
import docker
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
from third_party.bi_att_flow.my.tensorflow import *
|
<|file_name|>file.ts<|end_file_name|><|fim▁begin|>export function mockGlobalFile() {
// @ts-ignore
global.File = class MockFile {
name: string;
size: number;
type: string;
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[];
properties?: FilePropertyBag;
lastModified: number;
constructor(
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[],
name: string,
properties?: FilePropertyBag
) {
this.parts = parts;
this.name = name;
this.size = parts.join('').length;
this.type = 'txt';<|fim▁hole|> };
}
export function testFile(filename: string, size: number = 42) {
return new File(['x'.repeat(size)], filename, undefined);
}<|fim▁end|>
|
this.properties = properties;
this.lastModified = 1234567890000; // Sat Feb 13 2009 23:31:30 GMT+0000.
}
|
<|file_name|>global.js<|end_file_name|><|fim▁begin|>/**
* Created by LPAC006013 on 23/11/14.
*/
/*
* wiring Super fish to menu
*/
var sfvar = jQuery('div.menu');
var phoneSize = 600;
jQuery(document).ready(function($) {
//if screen size is bigger than phone's screen (Tablet,Desktop)
if($(document).width() >= phoneSize) {<|fim▁hole|> delay: 500,
speed: 'slow'
});
jQuery("#menu-main-menu").addClass('clear');
var containerheight = jQuery("#menu-main-menu").height();
jQuery("#menu-main-menu").children().css("height",containerheight);
}
$(window).resize(function() {
if($(document).width() >= phoneSize && !sfvar.hasClass('sf-js-enabled')) {
sfvar.superfish({
delay: 500,
speed: 'slow'
});
}
// phoneSize, disable superfish
else if($(document).width() < phoneSize) {
sfvar.superfish('destroy');
}
});
});<|fim▁end|>
|
// enable superfish
sfvar.superfish({
|
<|file_name|>uncoded.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
'''
Uncoded Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import urlparse,sys,urllib
params = dict(urlparse.parse_qsl(sys.argv[2].replace('?','')))
action = params.get('action')
name = params.get('name')
title = params.get('title')
year = params.get('year')
imdb = params.get('imdb')
tvdb = params.get('tvdb')
tmdb = params.get('tmdb')
season = params.get('season')
episode = params.get('episode')
tvshowtitle = params.get('tvshowtitle')
premiered = params.get('premiered')
url = params.get('url')
image = params.get('image')
meta = params.get('meta')
select = params.get('select')
query = params.get('query')
source = params.get('source')
content = params.get('content')
windowedtrailer = params.get('windowedtrailer')
windowedtrailer = int(windowedtrailer) if windowedtrailer in ("0","1") else 0
if action == None:
from resources.lib.indexers import navigator
from resources.lib.modules import cache
cache.cache_version_check()
navigator.navigator().root()
elif action == 'movieNavigator':
from resources.lib.indexers import navigator
navigator.navigator().movies()
elif action == 'movieliteNavigator':
from resources.lib.indexers import navigator
navigator.navigator().movies(lite=True)
elif action == 'mymovieNavigator':
from resources.lib.indexers import navigator
navigator.navigator().mymovies()
elif action == 'mymovieliteNavigator':
from resources.lib.indexers import navigator
navigator.navigator().mymovies(lite=True)
elif action == 'tvNavigator':
from resources.lib.indexers import navigator
navigator.navigator().tvshows()
elif action == 'tvliteNavigator':
from resources.lib.indexers import navigator
navigator.navigator().tvshows(lite=True)
elif action == 'mytvNavigator':
from resources.lib.indexers import navigator
navigator.navigator().mytvshows()
elif action == 'mytvliteNavigator':
from resources.lib.indexers import navigator
navigator.navigator().mytvshows(lite=True)
elif action == 'downloadNavigator':
from resources.lib.indexers import navigator
navigator.navigator().downloads()
elif action == 'libraryNavigator':
from resources.lib.indexers import navigator
navigator.navigator().library()
elif action == 'toolNavigator':
from resources.lib.indexers import navigator
navigator.navigator().tools()
elif action == 'searchNavigator':
from resources.lib.indexers import navigator
navigator.navigator().search()
elif action == 'viewsNavigator':
from resources.lib.indexers import navigator
navigator.navigator().views()
elif action == 'clearCache':
from resources.lib.indexers import navigator
navigator.navigator().clearCache()
elif action == 'clearCacheSearch':
from resources.lib.indexers import navigator
navigator.navigator().clearCacheSearch()
elif action == 'infoCheck':
from resources.lib.indexers import navigator
navigator.navigator().infoCheck('')
elif action == 'movies':
from resources.lib.indexers import movies
movies.movies().get(url)
elif action == 'moviePage':
from resources.lib.indexers import movies
movies.movies().get(url)
elif action == 'movieWidget':
from resources.lib.indexers import movies
movies.movies().widget()
elif action == 'movieSearch':
from resources.lib.indexers import movies
movies.movies().search()
elif action == 'movieSearchnew':
from resources.lib.indexers import movies
movies.movies().search_new()
elif action == 'movieSearchterm':
from resources.lib.indexers import movies
movies.movies().search_term(name)
elif action == 'moviePerson':
from resources.lib.indexers import movies
movies.movies().person()
elif action == 'movieGenres':
from resources.lib.indexers import movies
movies.movies().genres()
elif action == 'movieLanguages':
from resources.lib.indexers import movies
movies.movies().languages()
elif action == 'movieCertificates':
from resources.lib.indexers import movies
movies.movies().certifications()
elif action == 'movieYears':
from resources.lib.indexers import movies
movies.movies().years()
elif action == 'moviePersons':
from resources.lib.indexers import movies
movies.movies().persons(url)
elif action == 'movieUserlists':
from resources.lib.indexers import movies
movies.movies().userlists()
elif action == 'channels':
from resources.lib.indexers import channels
channels.channels().get()
elif action == 'tvshows':
from resources.lib.indexers import tvshows
tvshows.tvshows().get(url)
elif action == 'tvshowPage':
from resources.lib.indexers import tvshows
tvshows.tvshows().get(url)<|fim▁hole|> from resources.lib.indexers import tvshows
tvshows.tvshows().search()
elif action == 'tvSearchnew':
from resources.lib.indexers import tvshows
tvshows.tvshows().search_new()
elif action == 'tvSearchterm':
from resources.lib.indexers import tvshows
tvshows.tvshows().search_term(name)
elif action == 'tvPerson':
from resources.lib.indexers import tvshows
tvshows.tvshows().person()
elif action == 'tvGenres':
from resources.lib.indexers import tvshows
tvshows.tvshows().genres()
elif action == 'tvNetworks':
from resources.lib.indexers import tvshows
tvshows.tvshows().networks()
elif action == 'tvLanguages':
from resources.lib.indexers import tvshows
tvshows.tvshows().languages()
elif action == 'tvCertificates':
from resources.lib.indexers import tvshows
tvshows.tvshows().certifications()
elif action == 'tvPersons':
from resources.lib.indexers import tvshows
tvshows.tvshows().persons(url)
elif action == 'tvUserlists':
from resources.lib.indexers import tvshows
tvshows.tvshows().userlists()
elif action == 'seasons':
from resources.lib.indexers import episodes
episodes.seasons().get(tvshowtitle, year, imdb, tvdb)
elif action == 'episodes':
from resources.lib.indexers import episodes
episodes.episodes().get(tvshowtitle, year, imdb, tvdb, season, episode)
elif action == 'calendar':
from resources.lib.indexers import episodes
episodes.episodes().calendar(url)
elif action == 'tvWidget':
from resources.lib.indexers import episodes
episodes.episodes().widget()
elif action == 'calendars':
from resources.lib.indexers import episodes
episodes.episodes().calendars()
elif action == 'episodeUserlists':
from resources.lib.indexers import episodes
episodes.episodes().userlists()
elif action == 'refresh':
from resources.lib.modules import control
control.refresh()
elif action == 'queueItem':
from resources.lib.modules import control
control.queueItem()
elif action == 'openSettings':
from resources.lib.modules import control
control.openSettings(query)
elif action == 'artwork':
from resources.lib.modules import control
control.artwork()
elif action == 'addView':
from resources.lib.modules import views
views.addView(content)
elif action == 'moviePlaycount':
from resources.lib.modules import playcount
playcount.movies(imdb, query)
elif action == 'episodePlaycount':
from resources.lib.modules import playcount
playcount.episodes(imdb, tvdb, season, episode, query)
elif action == 'tvPlaycount':
from resources.lib.modules import playcount
playcount.tvshows(name, imdb, tvdb, season, query)
elif action == 'trailer':
from resources.lib.modules import trailer
trailer.trailer().play(name, url, windowedtrailer)
elif action == 'traktManager':
from resources.lib.modules import trakt
trakt.manager(name, imdb, tvdb, content)
elif action == 'authTrakt':
from resources.lib.modules import trakt
trakt.authTrakt()
elif action == 'smuSettings':
try: import urlresolver
except: pass
urlresolver.display_settings()
elif action == 'download':
import json
from resources.lib.modules import sources
from resources.lib.modules import downloader
try: downloader.download(name, image, sources.sources().sourcesResolve(json.loads(source)[0], True))
except: pass
elif action == 'play':
from resources.lib.modules import sources
sources.sources().play(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, meta, select)
elif action == 'addItem':
from resources.lib.modules import sources
sources.sources().addItem(title)
elif action == 'playItem':
from resources.lib.modules import sources
sources.sources().playItem(title, source)
elif action == 'alterSources':
from resources.lib.modules import sources
sources.sources().alterSources(url, meta)
elif action == 'clearSources':
from resources.lib.modules import sources
sources.sources().clearSources()
elif action == 'random':
rtype = params.get('rtype')
if rtype == 'movie':
from resources.lib.indexers import movies
rlist = movies.movies().get(url, create_directory=False)
r = sys.argv[0]+"?action=play"
elif rtype == 'episode':
from resources.lib.indexers import episodes
rlist = episodes.episodes().get(tvshowtitle, year, imdb, tvdb, season, create_directory=False)
r = sys.argv[0]+"?action=play"
elif rtype == 'season':
from resources.lib.indexers import episodes
rlist = episodes.seasons().get(tvshowtitle, year, imdb, tvdb, create_directory=False)
r = sys.argv[0]+"?action=random&rtype=episode"
elif rtype == 'show':
from resources.lib.indexers import tvshows
rlist = tvshows.tvshows().get(url, create_directory=False)
r = sys.argv[0]+"?action=random&rtype=season"
from resources.lib.modules import control
from random import randint
import json
try:
rand = randint(1,len(rlist))-1
for p in ['title','year','imdb','tvdb','season','episode','tvshowtitle','premiered','select']:
if rtype == "show" and p == "tvshowtitle":
try: r += '&'+p+'='+urllib.quote_plus(rlist[rand]['title'])
except: pass
else:
try: r += '&'+p+'='+urllib.quote_plus(rlist[rand][p])
except: pass
try: r += '&meta='+urllib.quote_plus(json.dumps(rlist[rand]))
except: r += '&meta='+urllib.quote_plus("{}")
if rtype == "movie":
try: control.infoDialog(rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000)
except: pass
elif rtype == "episode":
try: control.infoDialog(rlist[rand]['tvshowtitle']+" - Season "+rlist[rand]['season']+" - "+rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000)
except: pass
control.execute('RunPlugin(%s)' % r)
except:
control.infoDialog(control.lang(32537).encode('utf-8'), time=8000)
elif action == 'movieToLibrary':
from resources.lib.modules import libtools
libtools.libmovies().add(name, title, year, imdb, tmdb)
elif action == 'moviesToLibrary':
from resources.lib.modules import libtools
libtools.libmovies().range(url)
elif action == 'tvshowToLibrary':
from resources.lib.modules import libtools
libtools.libtvshows().add(tvshowtitle, year, imdb, tvdb)
elif action == 'tvshowsToLibrary':
from resources.lib.modules import libtools
libtools.libtvshows().range(url)
elif action == 'updateLibrary':
from resources.lib.modules import libtools
libtools.libepisodes().update(query)
elif action == 'service':
from resources.lib.modules import libtools
libtools.libepisodes().service()<|fim▁end|>
|
elif action == 'tvSearch':
|
<|file_name|>appointment_tags.py<|end_file_name|><|fim▁begin|>#
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2014 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# Arezqui Belaid <[email protected]>
#
from django.template.defaultfilters import register
from appointment.constants import EVENT_STATUS, ALARM_STATUS, ALARM_METHOD
@register.filter(name='event_status')
def event_status(value):
"""Event Status Templatetag"""
if not value:
return ''
STATUS = dict(EVENT_STATUS)
try:
return STATUS[value].encode('utf-8')
except:
return ''<|fim▁hole|>
@register.filter(name='alarm_status')
def alarm_status(value):
"""Alarm Status Templatetag"""
if not value:
return ''
STATUS = dict(ALARM_STATUS)
try:
return STATUS[value].encode('utf-8')
except:
return ''
@register.filter(name='alarm_method')
def alarm_method(value):
"""Alarm Method Templatetag"""
if not value:
return ''
METHOD = dict(ALARM_METHOD)
try:
return METHOD[value].encode('utf-8')
except:
return ''<|fim▁end|>
| |
<|file_name|>Tx3gDecoderTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.
*/
package com.google.android.exoplayer2.text.tx3g;
import static com.google.common.truth.Truth.assertThat;
import android.graphics.Color;
import android.graphics.Typeface;
import android.test.InstrumentationTestCase;
import android.text.SpannedString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;<|fim▁hole|>import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.Subtitle;
import com.google.android.exoplayer2.text.SubtitleDecoderException;
import java.io.IOException;
import java.util.Collections;
/**
* Unit test for {@link Tx3gDecoder}.
*/
public final class Tx3gDecoderTest extends InstrumentationTestCase {
private static final String NO_SUBTITLE = "tx3g/no_subtitle";
private static final String SAMPLE_JUST_TEXT = "tx3g/sample_just_text";
private static final String SAMPLE_WITH_STYL = "tx3g/sample_with_styl";
private static final String SAMPLE_WITH_STYL_ALL_DEFAULTS = "tx3g/sample_with_styl_all_defaults";
private static final String SAMPLE_UTF16_BE_NO_STYL = "tx3g/sample_utf16_be_no_styl";
private static final String SAMPLE_UTF16_LE_NO_STYL = "tx3g/sample_utf16_le_no_styl";
private static final String SAMPLE_WITH_MULTIPLE_STYL = "tx3g/sample_with_multiple_styl";
private static final String SAMPLE_WITH_OTHER_EXTENSION = "tx3g/sample_with_other_extension";
private static final String SAMPLE_WITH_TBOX = "tx3g/sample_with_tbox";
private static final String INITIALIZATION = "tx3g/initialization";
private static final String INITIALIZATION_ALL_DEFAULTS = "tx3g/initialization_all_defaults";
public void testDecodeNoSubtitle() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_SUBTITLE);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertThat(subtitle.getCues(0)).isEmpty();
}
public void testDecodeJustText() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_JUST_TEXT);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStylAllDefaults() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL_ALL_DEFAULTS);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16BeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_BE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16LeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_LE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithMultipleStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_MULTIPLE_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("Line 2\nLine 3");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, 5, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.ITALIC);
findSpan(text, 7, 12, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 5, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
colorSpan = findSpan(text, 7, 12, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithOtherExtension() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_OTHER_EXTENSION);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(2);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testInitializationDecodeWithStyl() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(5);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1f);
}
public void testInitializationDecodeWithTbox() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_TBOX);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1875f);
}
public void testInitializationAllDefaultsDecodeWithStyl() throws IOException,
SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION_ALL_DEFAULTS);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
private static <T> T findSpan(SpannedString testObject, int expectedStart, int expectedEnd,
Class<T> expectedType) {
T[] spans = testObject.getSpans(0, testObject.length(), expectedType);
for (T span : spans) {
if (testObject.getSpanStart(span) == expectedStart
&& testObject.getSpanEnd(span) == expectedEnd) {
return span;
}
}
fail("Span not found.");
return null;
}
private static void assertFractionalLinePosition(Cue cue, float expectedFraction) {
assertThat(cue.lineType).isEqualTo(Cue.LINE_TYPE_FRACTION);
assertThat(cue.lineAnchor).isEqualTo(Cue.ANCHOR_TYPE_START);
assertThat(Math.abs(expectedFraction - cue.line) < 1e-6).isTrue();
}
}<|fim▁end|>
|
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.TestUtil;
|
<|file_name|>Xfplot2DPanel.java<|end_file_name|><|fim▁begin|>//--------------------------------------------------------------------------------//
// COPYRIGHT NOTICE //
//--------------------------------------------------------------------------------//
// Copyright (c) 2012, Instituto de Microelectronica de Sevilla (IMSE-CNM) //
// //
// All rights reserved. //
// //
// Redistribution and use in source and binary forms, with or without //
// modification, are permitted provided that the following conditions are met: //
// //
// * Redistributions of source code must retain the above copyright notice, //
// this list of conditions and the following disclaimer. //
// //
// * Redistributions in binary form must reproduce the above copyright //
// notice, this list of conditions and the following disclaimer in the //
// documentation and/or other materials provided with the distribution. //
// //
// * Neither the name of the IMSE-CNM nor the names of its contributors may //
// be used to endorse or promote products derived from this software //
// without specific prior written permission. //
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE //
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE //
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL //
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR //
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //
//--------------------------------------------------------------------------------//
package xfuzzy.xfplot;
import javax.swing.*;
import java.awt.*;
/**
* Clase que desarrolla el panel para la representación gráfica en 2
* dimensiones
*
* @author Francisco José Moreno Velo
*
*/
public class Xfplot2DPanel extends JPanel {
//----------------------------------------------------------------------------//
// CONSTANTES PRIVADAS //
//----------------------------------------------------------------------------//<|fim▁hole|> private static final long serialVersionUID = 95505666603053L;
/**
* Altura del panel
*/
private static final int HEIGHT = 500;
/**
* Anchura del panel
*/
private static final int WIDTH = 700;
//----------------------------------------------------------------------------//
// MIEMBROS PRIVADOS //
//----------------------------------------------------------------------------//
/**
* Referencia al apágina principal de la aplicación
*/
private Xfplot xfplot;
//----------------------------------------------------------------------------//
// CONSTRUCTOR //
//----------------------------------------------------------------------------//
/**
* Constructor
*/
public Xfplot2DPanel(Xfplot xfplot) {
super();
this.xfplot = xfplot;
setSize(new Dimension(WIDTH,HEIGHT));
setPreferredSize(new Dimension(WIDTH,HEIGHT));
setBackground(Color.white);
setBorder(BorderFactory.createLoweredBevelBorder());
}
//----------------------------------------------------------------------------//
// MÉTODOS PÚBLICOS //
//----------------------------------------------------------------------------//
/**
* Pinta la representación gráfica.
* Este método sobreescribe el método paint() de JPanel().
*/
public void paint(Graphics g) {
super.paint(g);
paintAxis(g);
paintVariables(g);
paintFunction(g);
}
//----------------------------------------------------------------------------//
// MÉTODOS PRIVADOS //
//----------------------------------------------------------------------------//
/**
* Dibuja los ejes de la representación gráfica
*/
private void paintAxis(Graphics g) {
int width = getSize().width;
int height = getSize().height;
int xmin = width/8;
int xmax = width*7/8;
int ymin = height*7/8;
int ymax = height/8;
g.drawLine(xmin, ymin, xmin, ymax);
g.drawLine(xmin, ymin, xmax, ymin);
for(int i=0; i<6; i++) {
int y = ymin + (ymax - ymin)*i/5;
g.drawLine(xmin-3, y, xmin, y);
}
for(int i=0; i<6; i++) {
int x = xmin + (xmax - xmin)*i/5;
g.drawLine(x, ymin+3, x, ymin);
}
}
/**
* Dibuja los nombres de las variables a representar
*/
private void paintVariables(Graphics g) {
int width = getSize().width;
int height = getSize().height;
int xx = width * 9 / 10;
int xy = height * 9 / 10;
int yx = width / 10;
int yy = height / 10;
g.drawString(xfplot.getXVariable().toString(), xx, xy);
g.drawString(xfplot.getZVariable().toString(), yx, yy);
}
/**
* Dibuja la función en tramos lineales
*/
private void paintFunction(Graphics g) {
double function[] = xfplot.get2DFunction();
if(function == null) return;
int x0, y0, x1, y1;
int width = getSize().width;
int height = getSize().height;
int xrange = width * 3 / 4;
int yrange = height * 3 / 4;
int xmin = width/8;
int ymin = height*7/8;
Color old = g.getColor();
g.setColor(Color.red);
x0 = xmin;
y0 = ymin - (int) Math.round(function[0]*yrange);
for(int i=1; i<function.length; i++) {
x1 = xmin + i*xrange/(function.length-1);
y1 = ymin - (int) Math.round(function[i]*yrange);
g.drawLine(x0,y0,x1,y1);
x0 = x1;
y0 = y1;
}
g.setColor(old);
}
}<|fim▁end|>
|
/**
* Código asociado a la clase serializable
*/
|
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/requestid"
"github.com/kataras/golog"
)
func main() {<|fim▁hole|> // app.Logger().RegisterFormatter(golog.Formatter...)
// Also, see app.Logger().SetLevelOutput(level string, w io.Writer)
// to set a custom writer for a specific level.
app.Use(requestid.New())
/* Example Output:
{
"timestamp": 1591422944,
"level": "debug",
"message": "This is a message with data",
"fields": {
"username": "kataras"
},
"stacktrace": [
{
"function": "main.main",
"source": "C:/mygopath/src/github.com/kataras/iris/_examples/logging/json-logger/main.go:16"
}
]
}
*/
app.Logger().Debugf("This is a %s with data (debug prints the stacktrace too)", "message", golog.Fields{
"username": "kataras",
})
/* Example Output:
{
"timestamp": 1591422944,
"level": "info",
"message": "An info message",
"fields": {
"home": "https://iris-go.com"
}
}
*/
app.Logger().Infof("An info message", golog.Fields{"home": "https://iris-go.com"})
app.Get("/ping", ping)
// Navigate to http://localhost:8080/ping.
app.Listen(":8080" /*, iris.WithoutBanner*/)
}
func ping(ctx iris.Context) {
/* Example Output:
{
"timestamp": 1591423046,
"level": "debug",
"message": "Request path: /ping",
"fields": {
"request_id": "fc12d88a-a338-4bb9-aa5e-126f2104365c"
},
"stacktrace": [
{
"function": "main.ping",
"source": "C:/mygopath/src/github.com/kataras/iris/_examples/logging/json-logger/main.go:82"
},
...
]
}
*/
ctx.Application().Logger().Debugf("Request path: %s", ctx.Path(), golog.Fields{
"request_id": ctx.GetID(),
})
ctx.WriteString("pong")
}<|fim▁end|>
|
app := iris.New()
app.Logger().SetLevel("debug")
app.Logger().SetFormat("json", " ")
// to register a custom Formatter:
|
<|file_name|>ext-lang-zh_CN.js<|end_file_name|><|fim▁begin|>/*
* Simplified Chinese translation
* By DavidHu
* 09 April 2007<|fim▁hole|> */
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">加载中...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.Grid){
Ext.grid.Grid.prototype.ddText = "{0} 选择行";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "关闭";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "输入值非法";
}
Date.monthNames = [
"一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"
];
Date.dayNames = [
"日",
"一",
"二",
"三",
"四",
"五",
"六"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "确定",
cancel : "取消",
yes : "是",
no : "否"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "y年m月d日");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "今天",
minText : "日期在最小日期之前",
maxText : "日期在最大日期之后",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : '下月 (Control+Right)',
prevText : '上月 (Control+Left)',
monthYearText : '选择一个月 (Control+Up/Down 来改变年)',
todayTip : "{0} (空格键选择)",
format : "y年m月d日"
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "第",
afterPageText : "页,共 {0} 页",
firstText : "第一页",
prevText : "前一页",
nextText : "下一页",
lastText : "最后页",
refreshText : "刷新",
displayMsg : "显示 {0} - {1},共 {2} 条",
emptyMsg : '没有数据需要显示'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "该输入项的最小长度是 {0}",
maxLengthText : "该输入项的最大长度是 {0}",
blankText : "该输入项为必输项",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "该输入项的最小值是 {0}",
maxText : "该输入项的最大值是 {0}",
nanText : "{0} 不是有效数值"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "禁用",
disabledDatesText : "禁用",
minText : "该输入项的日期必须在 {0} 之后",
maxText : "该输入项的日期必须在 {0} 之前",
invalidText : "{0} 是无效的日期 - 必须符合格式: {1}",
format : "y年m月d日"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "加载...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : '该输入项必须是电子邮件地址,格式如: "[email protected]"',
urlText : '该输入项必须是URL地址,格式如: "http:/'+'/www.domain.com"',
alphaText : '该输入项只能包含字符和_',
alphanumText : '该输入项只能包含字符,数字和_'
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "正序",
sortDescText : "逆序",
lockText : "锁列",
unlockText : "解锁列",
columnsText : "列"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "名称",
valueText : "值",
dateFormat : "y年m月d日"
});
}
if(Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "拖动来改变尺寸.",
collapsibleSplitTip : "拖动来改变尺寸. 双击隐藏."
});
}<|fim▁end|>
| |
<|file_name|>textNoteEditView.js<|end_file_name|><|fim▁begin|>/**
*
* Note Edit View
*
* noteEditView.js
* @author Kerri Shotts
* @version 3.0.0
*
* Copyright (c) 2013 Packt Publishing
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*jshint
asi:true,
bitwise:true,
browser:true,
curly:true,
eqeqeq:false,
forin:true,
noarg:true,
noempty:true,
plusplus:false,
smarttabs:true,
sub:true,
trailing:false,
undef:true,
white:false,
onevar:false
*/
/*global define*/
define( [ "yasmf", "app/models/noteStorageSingleton",
"text!html/textNoteEditView.html!strip", "hammer"
], function( _y, noteStorageSingleton, textNoteEditViewHTML, Hammer ) {
// store our classname for easy overriding later
var _className = "TextNoteEditView";
var TextNoteEditView = function() {
// This time we descend from a simple ViewContainer
var self = new _y.UI.ViewContainer();
// always subclass
self.subclass( _className );
// our internal pointers to specific elements
self._navigationBar = null;
self._nameEditor = null;
self._scrollContainer = null;
self._contentsEditor = null;
self._backButton = null;
self._deleteButton = null;
self._shareButton = null; // new for v6
// the note we're editing
self._note = null;
/**
* Save the specific note by copying the name and contents
* from the DOM
*/
self.saveNote = function() {
self._note.name = self._nameEditor.innerText;
self._note.textContents = self._contentsEditor.value;
noteStorageSingleton.saveNote( self._note );
};
/**
* Delete the specific note.
*/
self.deleteNote = function() {
var areYouSure = new _y.UI.Alert();
areYouSure.initWithOptions( {
title: _y.T( "app.nev.action.DELETE_NOTE" ),
text: _y.T( "app.nev.action.ARE_YOU_SURE_THIS_ACTION_CANT_BE_UNDONE" ),
promise: true,
buttons: [ _y.UI.Alert.button( _y.T( "DELETE" ), {
type: "destructive"
} ),
_y.UI.Alert.button( _y.T( "CANCEL" ), {
type: "bold",
tag: -1
} )
]
} );
areYouSure.show().then( function( idx ) {
if ( idx > -1 ) {
noteStorageSingleton.removeNote( self._note.uid );
// return to the previous view.
self.navigationController.popView();
}
} ).catch( function( anError ) {
return; // happens when a cancel button is pressed
} ).done();
};
/**
* Go back to the previous view after saving the note.
*/
self.goBack = function() {
self.saveNote();
self.navigationController.popView();
};
/**
* Share the note using the sharing plugin. New for v6.
*/
self.shareNote = function() {
self.saveNote();
var message = {
subject: self._note.name,
text: self._note.textContents
};
window.socialmessage.send( message );
};
/**
* Render the template, passing the note contents and
* translated text.
*/
self.overrideSuper( self.class, "render", self.render );
self.render = function() {
// no need to call super; it's abstract
return _y.template( textNoteEditViewHTML, {
"NOTE_NAME": self._note.name,
"NOTE_CONTENTS": self._note.textContents,
"BACK": _y.T( "BACK" ),
"DELETE_NOTE": _y.T( "app.nev.DELETE_NOTE" )
} );
};
/**
* RenderToElement renders the template, finds our elements in the DOM
* and hooks up the necessary event handling
*/
self.overrideSuper( self.class, "renderToElement", self.renderToElement );
self.renderToElement = function() {
self.super( _className, "renderToElement" );<|fim▁hole|> self._navigationBar = self.element.querySelector( ".ui-navigation-bar" );
self._nameEditor = self.element.querySelector( ".ui-navigation-bar .ui-title" );
self._backButton = self.element.querySelector(
".ui-navigation-bar .ui-bar-button-group.ui-align-left .ui-back-button" );
self._deleteButton = self.element.querySelector(
".ui-navigation-bar .ui-bar-button-group.ui-align-right .ui-bar-button" );
self._scrollContainer = self.element.querySelector( ".ui-scroll-container" );
self._contentsEditor = self.element.querySelector( ".ui-text-box" );
Hammer( self._backButton ).on( "tap", self.goBack );
Hammer( self._deleteButton ).on( "tap", self.deleteNote );
self._shareButton = self.element.querySelector( ".share-button" );
if ( self._shareButton !== null ) {
Hammer( self._shareButton ).on( "tap", self.shareNote );
}
_y.UI.backButton.addListenerForNotification( "backButtonPressed", self.goBack );
};
/**
* Initializes our view -- theParentElement is the DOM element to attach to, and
* theUID is the specific note to edit.
*/
self.overrideSuper( self.class, "init", self.init );
self.init = function( theParentElement, theNote ) {
// get the note
self._note = theNote;
// call super
self.super( _className, "init", [ undefined, "div", self.class +
" noteEditView ui-container", theParentElement
] );
// listen for our disappearance
self.addListenerForNotification( "viewWasPopped", self.releaseBackButton );
self.addListenerForNotification( "viewWasPopped", self.destroy );
};
self.overrideSuper( self.class, "initWithOptions", self.init );
self.initWithOptions = function( options ) {
var theParentElement;
var theNote;
if ( typeof options !== "undefined" ) {
if ( typeof options.parent !== "undefined" ) {
theParentElement = options.parent;
}
if ( typeof options.note !== "undefined" ) {
theNote = options.note;
}
}
self.init( theParentElement, theNote );
};
self.releaseBackButton = function() {
// and make sure we forget about the physical back button
_y.UI.backButton.removeListenerForNotification( "backButtonPressed", self.goBack );
};
/**
* When destroy is called, release all our elements and
* remove our backButton listener.
*/
self.overrideSuper( self.class, "destroy", self.destroy );
self.destroy = function() {
self.releaseBackButton();
// Stop listening for our disappearance
self.removeListenerForNotification( "viewWasPopped", self.releaseBackButton );
self.removeListenerForNotification( "viewWasPopped", self.destroy );
// release our objects
self._navigationBar = null
self._backButton = null;
self._deleteButton = null;
self._scrollContainer = null;
self._nameEditor = null;
self._contentsEditor = null;
self._shareButton = null; // new for v6
self.super( _className, "destroy" );
};
return self;
};
/**
* add translations we need
*/
_y.addTranslations( {
"app.nev.DELETE_NOTE": {
"EN": "Delete",
"ES": "Eliminar"
},
"app.nev.action.DELETE_NOTE": {
"EN": "Delete Note",
"ES": "Eliminar Nota"
},
"app.nev.action.ARE_YOU_SURE_THIS_ACTION_CANT_BE_UNDONE": {
"EN": "Are you sure? This action can't be undone.",
"ES": "¿Está seguro? Esta acción no se puede deshacer."
}
} );
return TextNoteEditView;
} );<|fim▁end|>
| |
<|file_name|>1280_tidy_up_latent.py<|end_file_name|><|fim▁begin|>"""tidy_up_latent
Tidy up a latent migration not previously picked up by alembic or ignored.
Revision ID: 1280
Revises: 1270
Create Date: 2019-06-10 15:51:48.661665
"""<|fim▁hole|>from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1280'
down_revision = '1270'
def upgrade():
# this field not has a "unique index" instead of a "unique constraint"
op.drop_constraint('uq_direct_award_projects_external_id', 'direct_award_projects', type_='unique')
def downgrade():
op.create_unique_constraint('uq_direct_award_projects_external_id', 'direct_award_projects', ['external_id'])<|fim▁end|>
| |
<|file_name|>composites.py<|end_file_name|><|fim▁begin|>#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# 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.
#
from __future__ import annotations
from edb.common import ordered<|fim▁hole|>from . import base
class Record(type):
def __new__(mcls, name, fields, default=None):
dct = {'_fields___': fields, '_default___': default}
bases = (RecordBase, )
return super(Record, mcls).__new__(mcls, name, bases, dct)
def __init__(cls, name, fields, default):
pass
def has_field(cls, name):
return name in cls._fields___
class RecordBase:
def __init__(self, **kwargs):
for k, v in kwargs.items():
if k not in self.__class__._fields___:
msg = '__init__() got an unexpected keyword argument %s' % k
raise TypeError(msg)
setattr(self, k, v)
for k in set(self.__class__._fields___) - set(kwargs.keys()):
setattr(self, k, self.__class__._default___)
def __setattr__(self, name, value):
if name not in self.__class__._fields___:
msg = '%s has no attribute %s' % (self.__class__.__name__, name)
raise AttributeError(msg)
super().__setattr__(name, value)
def __eq__(self, tup):
if not isinstance(tup, tuple):
return NotImplemented
return tuple(self) == tup
def __getitem__(self, index):
return getattr(self, self.__class__._fields___[index])
def __iter__(self):
for name in self.__class__._fields___:
yield getattr(self, name)
def __len__(self):
return len(self.__class__._fields___)
def items(self):
for name in self.__class__._fields___:
yield name, getattr(self, name)
def keys(self):
return iter(self.__class__._fields___)
def __str__(self):
f = ', '.join(str(v) for v in self)
if len(self) == 1:
f += ','
return '(%s)' % f
__repr__ = __str__
class CompositeDBObject(base.DBObject):
def __init__(self, name, columns=None):
super().__init__()
self.name = name
self._columns = ordered.OrderedSet()
self.add_columns(columns or [])
def add_columns(self, iterable):
self._columns.update(iterable)
@property
def record(self):
return Record(
self.__class__.__name__ + '_record',
[c.name for c in self._columns], default=base.Default)
class CompositeAttributeCommand:
def __init__(self, attribute):
self.attribute = attribute
def __repr__(self):
return '<%s.%s %r>' % (
self.__class__.__module__, self.__class__.__name__, self.attribute)
class AlterCompositeAddAttribute(CompositeAttributeCommand):
def code(self, block: base.PLBlock) -> str:
return (f'ADD {self.get_attribute_term()} ' # type: ignore
f'{self.attribute.code(block)}')
def generate_extra(self, block: base.PLBlock,
alter: base.CompositeCommandGroup):
self.attribute.generate_extra(block, alter)
class AlterCompositeDropAttribute(CompositeAttributeCommand):
def code(self, block: base.PLBlock) -> str:
attrname = common.qname(self.attribute.name)
return f'DROP {self.get_attribute_term()} {attrname}' # type: ignore
class AlterCompositeAlterAttributeType:
def __init__(self, attribute_name, new_type, *, using_expr=None):
self.attribute_name = attribute_name
self.new_type = new_type
self.using_expr = using_expr
def code(self, block: base.PLBlock) -> str:
attrterm = self.get_attribute_term() # type: ignore
attrname = common.quote_ident(str(self.attribute_name))
code = f'ALTER {attrterm} {attrname} SET DATA TYPE {self.new_type}'
if self.using_expr is not None:
code += f' USING ({self.using_expr})'
return code
def __repr__(self):
cls = self.__class__
return f'<{cls.__name__} {self.attribute_name!r} to {self.new_type}>'<|fim▁end|>
|
from .. import common
|
<|file_name|>footnote.go<|end_file_name|><|fim▁begin|>package ast
import (
"fmt"
gast "github.com/yuin/goldmark/ast"
)
// A FootnoteLink struct represents a link to a footnote of Markdown
// (PHP Markdown Extra) text.
type FootnoteLink struct {
gast.BaseInline
Index int
RefCount int<|fim▁hole|>}
// Dump implements Node.Dump.
func (n *FootnoteLink) Dump(source []byte, level int) {
m := map[string]string{}
m["Index"] = fmt.Sprintf("%v", n.Index)
m["RefCount"] = fmt.Sprintf("%v", n.RefCount)
gast.DumpHelper(n, source, level, m, nil)
}
// KindFootnoteLink is a NodeKind of the FootnoteLink node.
var KindFootnoteLink = gast.NewNodeKind("FootnoteLink")
// Kind implements Node.Kind.
func (n *FootnoteLink) Kind() gast.NodeKind {
return KindFootnoteLink
}
// NewFootnoteLink returns a new FootnoteLink node.
func NewFootnoteLink(index int) *FootnoteLink {
return &FootnoteLink{
Index: index,
RefCount: 0,
}
}
// A FootnoteBacklink struct represents a link to a footnote of Markdown
// (PHP Markdown Extra) text.
type FootnoteBacklink struct {
gast.BaseInline
Index int
RefCount int
}
// Dump implements Node.Dump.
func (n *FootnoteBacklink) Dump(source []byte, level int) {
m := map[string]string{}
m["Index"] = fmt.Sprintf("%v", n.Index)
m["RefCount"] = fmt.Sprintf("%v", n.RefCount)
gast.DumpHelper(n, source, level, m, nil)
}
// KindFootnoteBacklink is a NodeKind of the FootnoteBacklink node.
var KindFootnoteBacklink = gast.NewNodeKind("FootnoteBacklink")
// Kind implements Node.Kind.
func (n *FootnoteBacklink) Kind() gast.NodeKind {
return KindFootnoteBacklink
}
// NewFootnoteBacklink returns a new FootnoteBacklink node.
func NewFootnoteBacklink(index int) *FootnoteBacklink {
return &FootnoteBacklink{
Index: index,
RefCount: 0,
}
}
// A Footnote struct represents a footnote of Markdown
// (PHP Markdown Extra) text.
type Footnote struct {
gast.BaseBlock
Ref []byte
Index int
}
// Dump implements Node.Dump.
func (n *Footnote) Dump(source []byte, level int) {
m := map[string]string{}
m["Index"] = fmt.Sprintf("%v", n.Index)
m["Ref"] = fmt.Sprintf("%s", n.Ref)
gast.DumpHelper(n, source, level, m, nil)
}
// KindFootnote is a NodeKind of the Footnote node.
var KindFootnote = gast.NewNodeKind("Footnote")
// Kind implements Node.Kind.
func (n *Footnote) Kind() gast.NodeKind {
return KindFootnote
}
// NewFootnote returns a new Footnote node.
func NewFootnote(ref []byte) *Footnote {
return &Footnote{
Ref: ref,
Index: -1,
}
}
// A FootnoteList struct represents footnotes of Markdown
// (PHP Markdown Extra) text.
type FootnoteList struct {
gast.BaseBlock
Count int
}
// Dump implements Node.Dump.
func (n *FootnoteList) Dump(source []byte, level int) {
m := map[string]string{}
m["Count"] = fmt.Sprintf("%v", n.Count)
gast.DumpHelper(n, source, level, m, nil)
}
// KindFootnoteList is a NodeKind of the FootnoteList node.
var KindFootnoteList = gast.NewNodeKind("FootnoteList")
// Kind implements Node.Kind.
func (n *FootnoteList) Kind() gast.NodeKind {
return KindFootnoteList
}
// NewFootnoteList returns a new FootnoteList node.
func NewFootnoteList() *FootnoteList {
return &FootnoteList{
Count: 0,
}
}<|fim▁end|>
| |
<|file_name|>serverhub.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************
**
** This file is part of .
** https://github.com/HamedMasafi/
**
** is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with . If not, see <http://www.gnu.org/licenses/>.
**
**************************************************************************/
#include <QEventLoop>
#include <QtCore/QDebug><|fim▁hole|>#include "abstracthub_p.h"
#include "serverhub.h"
#include "serverhub_p.h"
NEURON_BEGIN_NAMESPACE
ServerHubPrivate::ServerHubPrivate() : serverThread(nullptr), connectionEventLoop(nullptr)
{
}
ServerHub::ServerHub(QObject *parent) : AbstractHub(parent),
d(new ServerHubPrivate)
{
}
ServerHub::ServerHub(AbstractSerializer *serializer, QObject *parent) : AbstractHub(serializer, parent),
d(new ServerHubPrivate)
{
}
ServerHub::ServerHub(QTcpSocket *socket, QObject *parent) : AbstractHub(parent),
d(new ServerHubPrivate)
{
this->socket = socket;
}
ServerHub::~ServerHub()
{
// QList<SharedObject *> soList = sharedObjects();
// foreach (SharedObject *so, soList) {
// if(so)
// removeSharedObject(so);
// }
// while(sharedObjects().count()){
// removeSharedObject(sharedObjects().at(0));
// }
auto so = sharedObjectHash();
QHashIterator<const QString, SharedObject*> i(so);
while (i.hasNext()) {
i.next();
// cout << i.key() << ": " << i.value() << endl;
detachSharedObject(i.value());
}
}
ServerThread *ServerHub::serverThread() const
{
return d->serverThread;
}
qlonglong ServerHub::hi(qlonglong hubId)
{
initalizeMutex.lock();
setHubId(hubId);
// emit connected();
K_TRACE_DEBUG;
// invokeOnPeer(THIS_HUB, "hi", hubId);
if (d->connectionEventLoop) {
d->connectionEventLoop->quit();
d->connectionEventLoop->deleteLater();
}
initalizeMutex.unlock();
setStatus(Connected);
return this->hubId();
}
bool ServerHub::setSocketDescriptor(qintptr socketDescriptor, bool waitForConnect)
{
bool ok = socket->setSocketDescriptor(socketDescriptor);
if(waitForConnect)
socket->waitForReadyRead();
return ok;
}
void ServerHub::setServerThread(ServerThread *serverThread)
{
if(d->serverThread != serverThread)
d->serverThread = serverThread;
}
void ServerHub::beginConnection()
{
K_TRACE_DEBUG;
d->connectionEventLoop = new QEventLoop;
K_REG_OBJECT(d->connectionEventLoop);
d->connectionEventLoop->exec();
}
NEURON_END_NAMESPACE<|fim▁end|>
|
#include <QtNetwork/QTcpSocket>
|
<|file_name|>setup_win32.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import glob
import os
import site
from cx_Freeze import setup, Executable
import meld.build_helpers
import meld.conf
site_dir = site.getsitepackages()[1]
include_dll_path = os.path.join(site_dir, "gnome")
missing_dll = [
'libgtk-3-0.dll',
'libgdk-3-0.dll',
'libatk-1.0-0.dll',
'libintl-8.dll',
'libzzz.dll',
'libwinpthread-1.dll',
'libcairo-gobject-2.dll',
'libgdk_pixbuf-2.0-0.dll',
'libpango-1.0-0.dll',
'libpangocairo-1.0-0.dll',
'libpangoft2-1.0-0.dll',
'libpangowin32-1.0-0.dll',
'libffi-6.dll',
'libfontconfig-1.dll',
'libfreetype-6.dll',
'libgio-2.0-0.dll',
'libglib-2.0-0.dll',
'libgmodule-2.0-0.dll',
'libgobject-2.0-0.dll',
'libgirepository-1.0-1.dll',
'libgtksourceview-3.0-1.dll',
'libjasper-1.dll',
'libjpeg-8.dll',
'libpng16-16.dll',
'libgnutls-26.dll',
'libxmlxpat.dll',
'librsvg-2-2.dll',
'libharfbuzz-gobject-0.dll',
'libwebp-5.dll',
]
gtk_libs = [
'etc/fonts',
'etc/gtk-3.0/settings.ini',
'etc/pango',
'lib/gdk-pixbuf-2.0',
'lib/girepository-1.0',
'share/fontconfig',
'share/fonts',
'share/glib-2.0',
'share/gtksourceview-3.0',
'share/icons',
]
include_files = [(os.path.join(include_dll_path, path), path) for path in
missing_dll + gtk_libs]
build_exe_options = {
"compressed": False,
"icon": "data/icons/meld.ico",
"includes": ["gi"],
"packages": ["gi", "weakref"],
"include_files": include_files,
}
# Create our registry key, and fill with install directory and exe
registry_table = [
('MeldKLM', 2, 'SOFTWARE\Meld', '*', None, 'TARGETDIR'),
('MeldInstallDir', 2, 'SOFTWARE\Meld', 'InstallDir', '[TARGETDIR]', 'TARGETDIR'),
('MeldExecutable', 2, 'SOFTWARE\Meld', 'Executable', '[TARGETDIR]Meld.exe', 'TARGETDIR'),
]
# Provide the locator and app search to give MSI the existing install directory
# for future upgrades
reg_locator_table = [
('MeldInstallDirLocate', 2, 'SOFTWARE\Meld', 'InstallDir', 0)
]
app_search_table = [('TARGETDIR', 'MeldInstallDirLocate')]
msi_data = {
'Registry': registry_table,
'RegLocator': reg_locator_table,
'AppSearch': app_search_table
}
bdist_msi_options = {
"upgrade_code": "{1d303789-b4e2-4d6e-9515-c301e155cd50}",
"data": msi_data,
}
setup(
name="Meld",
version=meld.conf.__version__,<|fim▁hole|> maintainer='Kai Willadsen',
url='http://meldmerge.org',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: X11 Applications :: GTK',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',
'Programming Language :: Python',
'Topic :: Desktop Environment :: Gnome',
'Topic :: Software Development',
'Topic :: Software Development :: Version Control',
],
options = {
"build_exe": build_exe_options,
"bdist_msi": bdist_msi_options,
},
executables = [
Executable(
"bin/meld",
base="Win32GUI",
targetName="Meld.exe",
shortcutName="Meld",
shortcutDir="ProgramMenuFolder",
),
],
packages=[
'meld',
'meld.ui',
'meld.util',
'meld.vc',
],
package_data={
'meld': ['README', 'COPYING', 'NEWS']
},
scripts=['bin/meld'],
data_files=[
('share/man/man1',
['meld.1']
),
('share/doc/meld-' + meld.conf.__version__,
['COPYING', 'NEWS']
),
('share/meld',
['data/meld.css', 'data/meld-dark.css']
),
('share/meld/icons',
glob.glob("data/icons/*.png") +
glob.glob("data/icons/COPYING*")
),
('share/meld/ui',
glob.glob("data/ui/*.ui") + glob.glob("data/ui/*.xml")
),
],
cmdclass={
"build_i18n": meld.build_helpers.build_i18n,
"build_help": meld.build_helpers.build_help,
"build_icons": meld.build_helpers.build_icons,
"build_data": meld.build_helpers.build_data,
}
)<|fim▁end|>
|
description='Visual diff and merge tool',
author='The Meld project',
author_email='[email protected]',
|
<|file_name|>conversion-test.py<|end_file_name|><|fim▁begin|>import unittest
converter = __import__("obj-to-sm-conversion")
model = """
# Blender v2.71 (sub 0) OBJ File:
# www.blender.org
mtllib object.mtl
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000<|fim▁hole|>v -1.000000 1.000000 -1.000000
v 0.493105 -0.493106 2.246419
v -0.493106 -0.493106 2.246419
v 0.493105 0.493105 2.246419
v -0.493106 0.493105 2.246419
v 0.493105 -0.493106 3.738037
v -0.493106 -0.493106 3.738037
v 0.493104 0.493105 3.738037
v -0.493107 0.493105 3.738037
v 0.493105 -0.493106 4.284467
v -0.493107 -0.493106 4.284467
v 0.493104 0.493105 4.284468
v -0.493107 0.493105 4.284467
v 0.493104 1.012896 3.738037
v -0.493107 1.012896 3.738037
v 0.493104 1.343554 4.284468
v -0.493107 1.343554 4.284467
v 0.493105 1.845343 3.234304
v -0.493106 1.845343 3.234304
v 0.493105 2.176001 3.780735
v -0.493106 2.176001 3.780734
v 0.570207 -1.571936 -0.570207
v 0.570207 -1.571936 0.570207
v -0.570207 -1.571936 0.570207
v -0.570207 -1.571936 -0.570208
v 0.570207 -3.115134 -0.570207
v 0.570207 -3.115134 0.570207
v -0.570207 -3.115134 0.570207
v -0.570207 -3.115134 -0.570208
vn -0.799400 -0.600800 -0.000000
vn 0.000000 1.000000 0.000000
vn 1.000000 -0.000000 0.000000
vn -0.000000 0.926300 0.376700
vn -1.000000 -0.000000 -0.000000
vn 0.000000 0.000000 -1.000000
vn -0.926300 -0.000000 0.376700
vn 0.926300 0.000000 0.376700
vn 0.000000 -0.926300 0.376700
vn 0.000000 -1.000000 0.000000
vn -0.000000 -0.000000 1.000000
vn 0.000000 0.855600 -0.517700
vn -0.000000 0.517700 0.855600
vn 0.000000 -0.517700 -0.855600
vn -0.000000 -0.600800 0.799400
vn 0.000000 -0.600800 -0.799400
vn 0.799400 -0.600800 0.000000
usemtl Material
s off
f 4//1 32//1 31//1
f 8//2 7//2 6//2
f 1//3 5//3 6//3
f 7//4 12//4 11//4
f 7//5 8//5 4//5
f 1//6 4//6 8//6
f 12//2 16//2 15//2
f 7//7 3//7 10//7
f 2//8 6//8 11//8
f 2//9 9//9 10//9
f 16//5 20//5 24//5
f 12//5 10//5 14//5
f 9//3 11//3 15//3
f 9//10 13//10 14//10
f 17//11 19//11 20//11
f 16//5 14//5 18//5
f 15//3 19//3 17//3
f 13//10 17//10 18//10
f 22//5 24//5 28//5
f 15//3 21//3 23//3
f 19//11 23//11 24//11
f 16//6 22//6 21//6
f 26//12 28//12 27//12
f 23//3 21//3 25//3
f 23//13 27//13 28//13
f 22//14 26//14 25//14
f 32//5 36//5 35//5
f 3//15 31//15 30//15
f 1//16 29//16 32//16
f 2//17 30//17 29//17
f 34//10 35//10 36//10
f 31//11 35//11 34//11
f 29//6 33//6 36//6
f 29//3 30//3 34//3
f 3//1 4//1 31//1
f 5//2 8//2 6//2
f 2//3 1//3 6//3
f 6//4 7//4 11//4
f 3//5 7//5 4//5
f 5//6 1//6 8//6
f 11//2 12//2 15//2
f 12//7 7//7 10//7
f 9//8 2//8 11//8
f 3//9 2//9 10//9
f 22//5 16//5 24//5
f 16//5 12//5 14//5
f 13//3 9//3 15//3
f 10//10 9//10 14//10
f 18//11 17//11 20//11
f 20//5 16//5 18//5
f 13//3 15//3 17//3
f 14//10 13//10 18//10
f 26//5 22//5 28//5
f 19//3 15//3 23//3
f 20//11 19//11 24//11
f 15//6 16//6 21//6
f 25//12 26//12 27//12
f 27//3 23//3 25//3
f 24//13 23//13 28//13
f 21//14 22//14 25//14
f 31//5 32//5 35//5
f 2//15 3//15 30//15
f 4//16 1//16 32//16
f 1//17 2//17 29//17
f 33//10 34//10 36//10
f 30//11 31//11 34//11
f 32//6 29//6 36//6
f 33//3 29//3 34//3
"""
class TestConvertFunctions(unittest.TestCase):
def test_conversion(self):
global model
(format, faces, vertexes, normals, texture) = converter.convert_to_objects(model)
self.assertEqual(len(faces), 68)
self.assertEqual(len(vertexes), 36)
self.assertEqual(len(normals), 17)
self.assertEqual(len(texture), 0)
self.assertEqual(format, 'vn')
return 0<|fim▁end|>
|
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
|
<|file_name|>CustomEvent.js<|end_file_name|><|fim▁begin|>(function () {
describe('CustomEvent tests - future rule?', function () {
context('ignores safe patterns', function () {
context(null, function () {
var good = 'var a = "CustomEvent";';
it(good, function () {
chai.expect(ScanJS.scan(acorn.parse(good, {locations: true}), "/tests/")).to.be.empty;
});
});
context(null, function () {
var good = 'good.CustomEvent = "CustomEvent";';
it(good, function () {
chai.expect(ScanJS.scan(acorn.parse(good, {locations: true}), "/tests/")).to.be.empty;
});
});
});
context('detects dangerous patterns', function () {
context(null, function () {
var bad = 'obj.addEventListener("cat", function(e) { process(e.detail) }); var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}}); obj.dispatchEvent(event);';
it.skip(bad, function () {
chai.expect(ScanJS.scan(acorn.parse(bad, {locations: true}), "/tests/")).not.to.be.empty;<|fim▁hole|> });
})();<|fim▁end|>
|
});
});
});
|
<|file_name|>farewells.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> "Sayonara!".to_string()
}<|fim▁end|>
|
pub fn goodbye() -> String {
|
<|file_name|>JsonIgnore.java<|end_file_name|><|fim▁begin|>package com.jsoniter.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;<|fim▁hole|>import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonIgnore {
boolean ignoreDecoding() default true;
boolean ignoreEncoding() default true;
}<|fim▁end|>
| |
<|file_name|>pyrarcr-0.2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
##### ##### ##### ##### #### ####
# # # # # # # # # # #### #### # # #
##### #### ##### ##### ##### # # # # ####
# # # # # # # # # # # # #
# # # # # # # # #### # #### # ####
#finds the password of a desired rar or zip file using a brute-force algorithm
##will fail to find the password if the password has a character that isnt in
##the english alphabet or isnt a number (you can change the char. list though)
#now using itertools!
#importing needed modules
import time,os,sys,shutil,itertools
#checking if the user has unrar/p7zip installed
for which in ["unrar","p7zip"]:
if not shutil.which(which):
print("ERROR:",which,"isn't installed.\nExiting...")
sys.exit(-1)
#defining the function
def rc(rf):
alphabet="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1234567890"
start=time.time()
tryn=0
for a in range(1,len(alphabet)+1):
for b in itertools.product(alphabet,repeat=a):
k="".join(b)
if rf[-4:]==".rar":
print("Trying:",k)
kf=os.popen("unrar t -y -p%s %s 2>&1|grep 'All OK'"%(k,rf))
tryn+=1
for rkf in kf.readlines():
if rkf=="All OK\n":
print("Found password:",repr(k))
print("Tried combination count:",tryn)
print("It took",round(time.time()-start,3),"seconds")
print("Exiting...")
time.sleep(2)
sys.exit(1)
elif rf[-4:]==".zip" or rf[-3:]==".7z":
print("Trying:",k)
kf=os.popen("7za t -p%s %s 2>&1|grep 'Everything is Ok'"%(k,rf))
tryn+=1
for rkf in kf.readlines():
if rkf=="Everything is Ok\n":
print("Found password:",repr(k))
print("Tried combination count:",tryn)
print("It took",round(time.time()-start,3),"seconds")
print("Exiting...")
time.sleep(2)
sys.exit(1)
else:
print("ERROR: File isnt a RAR, ZIP or 7z file.\nExiting...")
<|fim▁hole|>if len(sys.argv)==2:
if os.path.exists(sys.argv[1]):
rc(sys.argv[1])
else:
print("ERROR: File doesn't exist.\nExiting...")
else:
print("Usage:",os.path.basename(__file__),"[rar file]")
print("Example:",os.path.basename(__file__),"foobar.rar")<|fim▁end|>
|
#checking if the file exists/running the function
|
<|file_name|>assignment04_159201_final_version.cpp<|end_file_name|><|fim▁begin|>//!
//! @author Wang Weixu 13114633, Xiufeng Zhang 06197620, Boxi Zhang, 12238967
//! @date 12.12.2014
//!
//! @brief This code implemented Big Number using linked list as underlying
//! data structure.
//!
//! Assignment 4, 159.201,s3,2014
//!
#include <iostream>
#include <fstream>
#include <string>
namespace ads {
/**
* @brief Section A : The List class
*/
template<typename T>
class List
{
struct Node{ T value_; Node* prev_; Node* next_; };
public:
using SizeType = std::size_t;
void push_front(T const& new_value)
{
if(empty())
{
head_ = tail_ = new Node{new_value, nullptr, nullptr};
}
else
{
head_ = new Node{new_value, nullptr, head_};
head_->next_->prev_ = head_;
}
++size_;
}
bool empty()const
{
return !head_ and !tail_;
}
SizeType size() const
{
return size_;
}
~List()
{
if(not empty())
for(Node* ptr = head_, *tmp; (tmp=ptr); ptr=ptr->next_) delete tmp;
head_ = tail_ = nullptr;
}
protected:
Node* head_{};
Node* tail_{};
private:
SizeType size_{0};
};
template<typename T>
struct BigNumber;
template<typename T>
BigNumber<T> operator+(BigNumber<T> const& lhs, BigNumber<T> const& rhs);
/**
* @brief Section B : The BigNumber struct
*/
template<typename T>
struct BigNumber : private List<T>
{
friend BigNumber operator+ <T>(BigNumber const&, BigNumber const&);
using List<T>::push_front;
BigNumber() = default;
explicit BigNumber(std::string const& num)
{
for(auto c = num.crbegin(); c != num.crend(); ++c)
if(std::isdigit(*c)) push_front(*c - 48);
}
std::ostream& print() const
{
for(auto ptr = this->head_; ptr; ptr = ptr->next_) std::cout << ptr->value_;
return std::cout << std::endl;
}
};
<|fim▁hole|>/**
* @brief Section C : operator +
* @param lhs
* @param rhs
* @return the sum
*/
template<typename T>
BigNumber<T> operator+(BigNumber<T> const& lhs, BigNumber<T> const& rhs)
{
BigNumber<T> sum;
int carry = 0;
auto l = lhs.tail_, r = rhs.tail_;
for(; l and r; l = l->prev_, r = r->prev_) //add two numbers.
{
auto digit_sum = carry + l->value_ + r->value_ ;
sum.push_front(digit_sum%10);
carry = digit_sum/10;
}
for(auto rest = l?l:r; rest; rest = rest->prev_) //when either one exhausted.
{
auto digit_sum = carry + rest->value_;
sum.push_front(digit_sum%10);
carry = digit_sum/10;
}
if(carry) //for the last carry,if any.
sum.push_front(carry);
return sum;
}
}//namespace
int main(int argc, char ** argv)
{
if(argc!=2)
{
std::cout<< "cannot read the file " << argv[1] << std::endl;
exit(0);
}
std::string l,r;
{
std::ifstream ifs{argv[1]};
std::getline(ifs,l);
std::getline(ifs,r);
}
ads::BigNumber<int> lhs{l}, rhs{r};
lhs.print() << "+\n";
rhs.print() << "=\n";
(lhs+rhs).print();
return 0;
}<|fim▁end|>
| |
<|file_name|>date-parser.js<|end_file_name|><|fim▁begin|>define(['../../moduleDef', 'angular'], function(module, angular) {
'use strict';
module.provider('$dateParser', function() {
var proto = Date.prototype;
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var defaults = this.defaults = {
format: 'shortDate',
strict: false
};
this.$get = function($locale) {
var DateParserFactory = function(config) {
var options = angular.extend({}, defaults, config);
var $dateParser = {};
var regExpMap = {
'sss' : '[0-9]{3}',
'ss' : '[0-5][0-9]',
's' : options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]',
'mm' : '[0-5][0-9]',
'm' : options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]',
'HH' : '[01][0-9]|2[0-3]',
'H' : options.strict ? '[0][1-9]|[1][012]' : '[01][0-9]|2[0-3]',
'hh' : '[0][1-9]|[1][012]',
'h' : options.strict ? '[1-9]|[1][012]' : '[0]?[1-9]|[1][012]',
'a' : 'AM|PM',
'EEEE' : $locale.DATETIME_FORMATS.DAY.join('|'),
'EEE' : $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
'dd' : '[0-2][0-9]{1}|[3][01]{1}',
'd' : options.strict ? '[1-2]?[0-9]{1}|[3][01]{1}' : '[0-2][0-9]{1}|[3][01]{1}',
'MMMM' : $locale.DATETIME_FORMATS.MONTH.join('|'),
'MMM' : $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
'MM' : '[0][1-9]|[1][012]',
'M' : options.strict ? '[1-9]|[1][012]' : '[0][1-9]|[1][012]',
'yyyy' : '(?:(?:[1]{1}[0-9]{1}[0-9]{1}[0-9]{1})|(?:[2]{1}[0-9]{3}))(?![[0-9]])',
'yy' : '(?:(?:[0-9]{1}[0-9]{1}))(?![[0-9]])'
};
var setFnMap = {
'sss' : proto.setMilliseconds,
'ss' : proto.setSeconds,
's' : proto.setSeconds,
'mm' : proto.setMinutes,
'm' : proto.setMinutes,
'HH' : proto.setHours,
'H' : proto.setHours,
'hh' : proto.setHours,
'h' : proto.setHours,
'dd' : proto.setDate,<|fim▁hole|> 'a' : function(value) { var hours = this.getHours(); return this.setHours(value.match(/pm/i) ? hours + 12 : hours); },
'MMMM' : function(value) { return this.setMonth($locale.DATETIME_FORMATS.MONTH.indexOf(value)); },
'MMM' : function(value) { return this.setMonth($locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value)); },
'MM' : function(value) { return this.setMonth(1 * value - 1); },
'M' : function(value) { return this.setMonth(1 * value - 1); },
'yyyy' : proto.setFullYear,
'yy' : function(value) { return this.setFullYear(2000 + 1 * value); },
'y' : proto.setFullYear
};
var regex, setMap;
$dateParser.init = function() {
$dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format;
regex = regExpForFormat($dateParser.$format);
setMap = setMapForFormat($dateParser.$format);
};
$dateParser.isValid = function(date) {
if(angular.isDate(date)) return !isNaN(date.getTime());
return regex.test(date);
};
$dateParser.parse = function(value, baseDate) {
if(angular.isDate(value)) return value;
var matches = regex.exec(value);
if(!matches) return false;
var date = baseDate || new Date(0);
for(var i = 0; i < matches.length - 1; i++) {
setMap[i] && setMap[i].call(date, matches[i+1]);
}
return date;
};
// Private functions
function setMapForFormat(format) {
var keys = Object.keys(setFnMap), i;
var map = [], sortedMap = [];
// Map to setFn
var clonedFormat = format;
for(i = 0; i < keys.length; i++) {
if(format.split(keys[i]).length > 1) {
var index = clonedFormat.search(keys[i]);
format = format.split(keys[i]).join('');
if(setFnMap[keys[i]]) map[index] = setFnMap[keys[i]];
}
}
// Sort result map
angular.forEach(map, function(v) {
sortedMap.push(v);
});
return sortedMap;
}
function escapeReservedSymbols(text) {
return text.replace(/\//g, '[\\/]').replace('/-/g', '[-]').replace(/\./g, '[.]').replace(/\\s/g, '[\\s]');
}
function regExpForFormat(format) {
var keys = Object.keys(regExpMap), i;
var re = format;
// Abstract replaces to avoid collisions
for(i = 0; i < keys.length; i++) {
re = re.split(keys[i]).join('${' + i + '}');
}
// Replace abstracted values
for(i = 0; i < keys.length; i++) {
re = re.split('${' + i + '}').join('(' + regExpMap[keys[i]] + ')');
}
format = escapeReservedSymbols(format);
return new RegExp('^' + re + '$', ['i']);
}
$dateParser.init();
return $dateParser;
};
return DateParserFactory;
};
});
});<|fim▁end|>
|
'd' : proto.setDate,
|
<|file_name|>base_model.py<|end_file_name|><|fim▁begin|>import logging
from django.db import models
class BaseModel(models.Model):
class Meta:
# Makes django recognize model in split modules
app_label = 'sdn'
# Turns this into an abstract model (does not create table for it)
abstract = True
# Default exception for models in manager
class ModelException(Exception):
# Get an instance of a logger
logger = logging.getLogger(__name__)
def __init__(self, msg):<|fim▁hole|> return repr(self.msg)<|fim▁end|>
|
self.msg = msg
self.logger.warning(msg)
def __str__(self):
|
<|file_name|>test_rpc_util.py<|end_file_name|><|fim▁begin|>"""
Test rpc_util functions
"""
__author__ = 'Dan Gunter <[email protected]>'
__date__ = '8/28/15'
# Imports
# stdlib
import re
# third-party
from nose.tools import raises
# local
from doekbase.data_api import rpc_util
from thrift.Thrift import TType
class Metadata:
"""SAMPLE object for testing validation, etc.
Default metadata for an object.
Attributes:
- object_id
- object_name
- object_reference
- object_reference_versioned
- type_string
- save_date
- version
- saved_by
- workspace_id
- workspace_name
- object_checksum
- object_size
- object_metadata
"""<|fim▁hole|> None, # 0
(1, TType.STRING, 'object_id', None, None,), # 1
(2, TType.STRING, 'object_name', None, None,), # 2
(3, TType.STRING, 'object_reference', None, None,), # 3
(4, TType.STRING, 'object_reference_versioned', None, None,), # 4
(5, TType.STRING, 'type_string', None, None,), # 5
(6, TType.DOUBLE, 'save_timestamp', None, None,), # 6
(7, TType.STRING, 'version', None, None,), # 7
(8, TType.STRING, 'saved_by', None, None,), # 8
(9, TType.I64, 'workspace_id', None, None,), # 9
(10, TType.STRING, 'workspace_name', None, None,), # 10
(11, TType.STRING, 'object_checksum', None, None,), # 11
(12, TType.I64, 'object_size', None, None,), # 12
(13, TType.STRING, 'object_metadata', None, None,), # 13
)
def __init__(self, object_id=None, object_name=None, object_reference=None,
object_reference_versioned=None, type_string=None,
save_timestamp=None, version=None, saved_by=None,
workspace_id=None, workspace_name=None, object_checksum=None,
object_size=None, object_metadata=None, ):
self.object_id = object_id
self.object_name = object_name
self.object_reference = object_reference
self.object_reference_versioned = object_reference_versioned
self.type_string = type_string
self.save_timestamp = save_timestamp
self.version = version
self.saved_by = saved_by
self.workspace_id = workspace_id
self.workspace_name = workspace_name
self.object_checksum = object_checksum
self.object_size = object_size
self.object_metadata = object_metadata
@raises(rpc_util.InvalidField)
def test_thrift_validate_str_fail():
rpc_util.thrift_validate(Metadata(object_id=12))
@raises(rpc_util.InvalidField)
def test_thrift_validate_int_fail():
rpc_util.thrift_validate(Metadata(workspace_id='hello'))
@raises(rpc_util.InvalidField)
def test_thrift_validate_int_double_fail():
rpc_util.thrift_validate(Metadata(workspace_id=3.5))
@raises(rpc_util.InvalidField)
def test_thrift_validate_double_fail():
rpc_util.thrift_validate(Metadata(save_timestamp=['June']))
def test_thrift_validate_str():
rpc_util.thrift_validate(Metadata(object_id='12'))
rpc_util.thrift_validate(Metadata(object_id=u'12'))
def test_thrift_validate_int():
rpc_util.thrift_validate(Metadata(workspace_id=12))
def test_thrift_validate_int_double():
rpc_util.thrift_validate(Metadata(workspace_id=12.0)) # ok if int.
rpc_util.thrift_validate(Metadata(workspace_id=12))
def test_thrift_validate_double():
rpc_util.thrift_validate(Metadata(save_timestamp=123456))
rpc_util.thrift_validate(Metadata(save_timestamp=123456.7))
def test_thrift_errmsg():
val = 'really big'
try:
rpc_util.thrift_validate(Metadata(object_size=val))
except rpc_util.InvalidField as err:
msg = str(err)
#print("@@ {}".format(msg))
# make sure both type and value appear in error message
assert val in msg # note: assumes string value
assert 'I64' in msg<|fim▁end|>
|
thrift_spec = (
|
<|file_name|>no_tmp_typemap_GeometricFields.hpp<|end_file_name|><|fim▁begin|>// pythonFlu - Python wrapping for OpenFOAM C++ API
// Copyright (C) 2010- Alexey Petrov
// Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// See http://sourceforge.net/projects/pythonflu
//
// Author : Alexey PETROV
//---------------------------------------------------------------------------
#ifndef no_tmp_typemap_GeometricFields_hpp
#define no_tmp_typemap_GeometricFields_hpp
//---------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/fields/tmp/tmp.i"
%import "Foam/ext/common/ext_tmp.hxx"
//---------------------------------------------------------------------------
%define NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Type, TPatchField, TMesh )
%typecheck( SWIG_TYPECHECK_POINTER ) Foam::GeometricField< Type, TPatchField, TMesh >&
{
void *ptr;
int res_T = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), 0 );
int res_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 );
int res_ext_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 );
$1 = SWIG_CheckState( res_T ) || SWIG_CheckState( res_tmpT ) || SWIG_CheckState( res_ext_tmpT );
}
%typemap( in ) Foam::GeometricField< Type, TPatchField, TMesh >&
{
void *argp = 0;
int res = 0;
res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), %convertptr_flags );
if ( SWIG_IsOK( res )&& argp ){
Foam::GeometricField< Type, TPatchField, TMesh > * res = %reinterpret_cast( argp, Foam::GeometricField< Type, TPatchField, TMesh >* );
$1 = res;
} else {
res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags );
if ( SWIG_IsOK( res ) && argp ) {
Foam::tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * );
$1 = tmp_res->operator->();
} else {
res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags );
if ( SWIG_IsOK( res ) && argp ) {
Foam::ext_tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * );
$1 = tmp_res->operator->();
} else {
%argument_fail( res, "$type", $symname, $argnum );
}
}
}
}
%enddef
//---------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/scalar.i"
%include "Foam/src/finiteVolume/volMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::scalar, Foam::fvPatchField, Foam::volMesh );
//----------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/vector.i"
%include "Foam/src/finiteVolume/volMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Vector< Foam::scalar >, Foam::fvPatchField, Foam::volMesh );
//----------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/tensor.i"
%include "Foam/src/finiteVolume/volMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Tensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh );
//-----------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/symmTensor.i"
%include "Foam/src/finiteVolume/volMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::SymmTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh );
//------------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/sphericalTensor.i"
%include "Foam/src/finiteVolume/volMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::SphericalTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh );
//------------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/scalar.i"
%include "Foam/src/finiteVolume/surfaceMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::scalar, Foam::fvsPatchField, Foam::surfaceMesh );
//-------------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/vector.i"
%include "Foam/src/finiteVolume/surfaceMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Vector< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh );
//-------------------------------------------------------------------------------
%import "Foam/src/OpenFOAM/primitives/tensor.i"
%include "Foam/src/finiteVolume/surfaceMesh.hpp"
%include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp"
NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Tensor< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh );
<|fim▁hole|><|fim▁end|>
|
//-------------------------------------------------------------------------------
#endif
|
<|file_name|>TaoParser.java<|end_file_name|><|fim▁begin|>/*
* generated by Xtext
*/
package org.eclectic.frontend.parser.antlr;
import com.google.inject.Inject;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.eclectic.frontend.services.TaoGrammarAccess;
public class TaoParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private TaoGrammarAccess grammarAccess;
@Override
protected void setInitialHiddenTokens(XtextTokenStream tokenStream) {
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
}<|fim▁hole|> }
@Override
protected String getDefaultRuleName() {
return "TaoTransformation";
}
public TaoGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(TaoGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}<|fim▁end|>
|
@Override
protected org.eclectic.frontend.parser.antlr.internal.InternalTaoParser createParser(XtextTokenStream stream) {
return new org.eclectic.frontend.parser.antlr.internal.InternalTaoParser(stream, getGrammarAccess());
|
<|file_name|>commons.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ocitysmap, city map and street index generator from OpenStreetMap data
# Copyright (C) 2010 David Decotigny
# Copyright (C) 2010 Frédéric Lehobey<|fim▁hole|># Copyright (C) 2010 Thomas Petazzoni
# Copyright (C) 2010 Gaël Utard
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# PT/metrics conversion routines
PT_PER_INCH = 72.0
def convert_pt_to_dots(pt, dpi = PT_PER_INCH):
return float(pt * dpi) / PT_PER_INCH
def convert_mm_to_pt(mm):
return ((mm/10.0) / 2.54) * 72
def convert_pt_to_mm(pt):
return (float(pt) * 10.0 * 2.54) / 72<|fim▁end|>
|
# Copyright (C) 2010 Pierre Mauduit
# Copyright (C) 2010 David Mentré
# Copyright (C) 2010 Maxime Petazzoni
|
<|file_name|>client.py<|end_file_name|><|fim▁begin|>from .company import Company<|fim▁hole|>from .contact import Contact
from .deal import Deal
from .note import Note
from .requester import Requester
class AgileCRM:
def __init__(self, domain, email, api_key):
requester = Requester(domain, email, api_key)
self.contact = Contact(requester=requester)
self.company = Company(requester=requester)
self.deal = Deal(requester=requester)
self.note = Note(requester=requester)<|fim▁end|>
| |
<|file_name|>http-response.test.js<|end_file_name|><|fim▁begin|>'use strict';
const assert = require('assert');
const HttpResponse = require('./http-response');
describe('HttpResponse', () => {
const mockResponse = {
version: '1.0',
status: '200 OK'
};
it('should create an instance', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse instanceof HttpResponse);
});
describe('isProtocolVersion()', () => {
it('should determine if protocol version matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isProtocolVersion('1.0'));
});
it('should return false if versions do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isProtocolVersion('2.0'), false);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.isProtocolVersion(false), /The protocol `version` must be a string/);
});
});
describe('getProtocolVersion()', () => {
it('should get the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
});
});
describe('setProtocolVersion()', () => {
it('should set the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
httpResponse.setProtocolVersion('2.0');
assert.equal(httpResponse.getProtocolVersion(), '2.0');
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.setProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setProtocolVersion(Boolean), /The protocol `version` must be a string/);
});
});
describe('isStatus()', () => {
it('should determine if status matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isStatus('200 OK'));
});
it('should return false if status do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isStatus('400 Bad Request'), false);
});
it('should throw an error if no status specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isStatus, /Specify a `status`/);
});
it('should throw an error if specified status is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.isStatus({}), /The `status` must be a string/);
});
});
describe('getStatus()', () => {
it('should return the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
});
});
describe('getStatusCode()', () => {
it('should return status code', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusCode(), '200');
});
});
describe('getStatusText()', () => {
it('should return status text', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusText(), 'OK');
});
});
describe('setStatus()', () => {
it('should set the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
httpResponse.setStatus(400, 'Bad Request');
assert.equal(httpResponse.getStatus(), '400 Bad Request');
});
it('should throw an error if no code specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(void 0, 'Bad Request'), /Specify a status `code`/);
});
it('should throw an error if the code is not an integer', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() =>
httpResponse.setStatus('200', 'Bad Request'), /The status `code` must be an integer/);
});
it('should throw an error if no text specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, void 0), /Specify a status `text`/);
});
it('should throw an error if specified text is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, true), /The status `text` must be a string/);
});
});
describe('hasHeader()', () => {
it('should determine if header has been set', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': 'test'}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasHeader('Content-Type'));
});
it('should return false if header has not been set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasHeader('Content-Type'), false);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.hasHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.hasHeader({}), /The header `name` must be a string/);
});
});
describe('getHeader()', () => {
it('should return the header with the specified `name`', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': ['test']}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should return the default value if specified header does not exist', () => {
const _mockResponse = Object.assign({headers: {}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
const defaultValue = 'text/plain';
assert.equal(httpResponse.getHeader('Content-Type', defaultValue), defaultValue);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.getHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.getHeader({}), /The header `name` must be a string/);
});
});<|fim▁hole|> const headers = {'Content-Type': ['test']};
const _mockResponse = Object.assign({headers}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {'Content-Type': 'test'});
});
it('should return an empty set of headers when none are set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {});
});
});
describe('setHeader()', () => {
it('should set a header in the httpResponse', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('Content-Type', 'test');
assert.ok(httpResponse.hasHeader('Content-Type'));
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should throw an error if a header `name` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader(void 0, 'test'), /Specify a header `name`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader(false, 'test'), /The header `name` must be a string/);
});
it('should throw an error if a header `value` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader('Content-Type', void 0), /Specify a header `value`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader('Content-Type', []),
/The header `value` must be a string/);
});
it('should register a new header as an array with 1 value', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('X-Test', 'test');
assert.ok(httpResponse.hasHeader('X-Test'));
assert.deepEqual(httpResponse.getHeaderArray('X-Test'), ['test']);
});
});
describe('hasBody()', () => {
it('should determine if the httpResponse has a `body`', () => {
const _mockResponse = Object.assign({body: ' '}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasBody());
});
it('should return false if the esponse do not have a `body`', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasBody(), false);
});
});
describe('getBody()', () => {
it('should return the content of the httpResponse `body`', () => {
const body = ' ';
const _mockResponse = Object.assign({body}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getBody(), body);
});
});
describe('setBody()', () => {
it('should set the content of the httpResponse `body`', () => {
const body = ' ';
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setBody(body);
assert.equal(httpResponse.getBody(), body);
});
});
});<|fim▁end|>
|
describe('getHeaders()', () => {
it('should return all headers', () => {
|
<|file_name|>dunces-and-dungeons.py<|end_file_name|><|fim▁begin|>from dungeon.dungeon import Dungeon, Hub
from entity.player.players import Player, Party
import entity.item.items as items
import sys, os
import base
import web.server
try:
import dill
except:
dill = None
PARTY = Party()
class Manager:
def __init__(self):
self.checked = False
def get_current_release(self):
latest = None
try:
import requests
latest = requests.get('https://api.github.com/repos/microwaveabletoaster/dunces-and-dungeons/releases/latest').json()['tag_name']<|fim▁hole|> def update_check(self):
base.put('checking for update...')
latest = self.get_current_release()
if latest:
if latest == self.RELEASE_ID:
base.put('you\'re up to date!')
else:
base.put("---------------=====UPDATE!!=====-----------\nan update to dunces and dungeons has been released! \ngo download it now from here: https://github.com/microwaveabletoaster/dunces-and-dungeons/releases \nit probably contains super important bugfixes and or more neat features, so don't dawdle!! \n\n<3 the team\n")
self.checked = True
def main(self,webbed=False):
self.webbed = webbed
if webbed: # ha amphibian joke
base.IS_WEB_VERSION = True
base.SERVER = web.server
web.server.party = PARTY
print 'MOVED ON'
base.BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ver = []
with open('%s/version.dunce' % base.BASE_DIR, 'r+') as f:
contents = f.read()
if contents is '':
base.put('writing')
f.write(self.get_current_release().replace('.',' ').replace('v',''))
ver = contents.split(' ')
self.RELEASE_ID = ('v%s.%s.%s' % (ver[0],ver[1],ver[2])).strip()
if not self.checked:
self.update_check()
go = True
intro = """
______ _ _______ _______ _______
( __ \ |\ /|( ( /|( ____ \( ____ \( ____ \\
| ( \ )| ) ( || \ ( || ( \/| ( \/| ( \/
| | ) || | | || \ | || | | (__ | (_____
| | | || | | || (\ \) || | | __) (_____ )
| | ) || | | || | \ || | | ( ) |
| (__/ )| (___) || ) \ || (____/\| (____/\/\____) |
(______/ (_______)|/ )_)(_______/(_______/\_______)
_______ _ ______
( ___ )( ( /|( __ \\
| ( ) || \ ( || ( \ )
| (___) || \ | || | ) |
| ___ || (\ \) || | | |
| ( ) || | \ || | ) |
| ) ( || ) \ || (__/ )
|/ \||/ )_)(______/
______ _ _______ _______ _______ _ _______
( __ \ |\ /|( ( /|( ____ \( ____ \( ___ )( ( /|( ____ \\
| ( \ )| ) ( || \ ( || ( \/| ( \/| ( ) || \ ( || ( \/
| | ) || | | || \ | || | | (__ | | | || \ | || (_____
| | | || | | || (\ \) || | ____ | __) | | | || (\ \) |(_____ )
| | ) || | | || | \ || | \_ )| ( | | | || | \ | ) |
| (__/ )| (___) || ) \ || (___) || (____/\| (___) || ) \ |/\____) |
(______/ (_______)|/ )_)(_______)(_______/(_______)|/ )_)\_______)
copyleft (c) 2016 John Dikeman and Cameron Egger
"""
base.put(intro)
cho = 0
# most of this code is super redundant cause cho is hardcoded but do i care? nope lol.
if cho is not None:
if cho is 0:
self.new_game()
if cho is 1:
li = []
if os.path.exists('%s/saves/' % base.BASE_DIR):
for dirpath, dirname, filename in os.walk('%s/saves/' % base.BASE_DIR):
for fi in filename:
if '.dunce' in fi:
li.append(fi)
else:
base.put('no saves to choose from!')
op = base.make_choice(li,"savefile")
if dill:
if op is not None:
go = False
base.put('loading session')
dill.load_session('%s/saves/%s' % (base.BASE_DIR,li[op]))
else:
base.put('save/load support is disabled because you haven\'t installed dill!')
def new_game(self):
# PARTY.current_dungeon.start()
if self.webbed:
party_size = base.get_input('enter the size of your party: ')
if int(party_size) is 0:
base.put("you can't play with zero people, dingus")
sys.exit()
# creating all the players in the party
for a in range(int(party_size)):
name = base.get_input('enter the name of player %d: ' % a)
PARTY.add_player(Player(name))
base.put('Game Start')
base.put(PARTY.to_str())
dungeon = Hub(PARTY)
PARTY.hub = dungeon
PARTY.current_dungeon = dungeon
PARTY.current_dungeon.start()
while(PARTY.end):
PARTY.handle_player_turn()
if(PARTY.end):
PARTY.current_dungeon.handle_monster_turn()
base.put("\n\n------------=========GAME OVER=========------------")
else:
party_size = base.get_input('enter the size of your party: ')
if int(party_size) is 0:
base.put("you can't play with zero people, dingus")
sys.exit()
# creating all the players in the party
for a in range(int(party_size)):
name = base.get_input('enter the name of player %d: ' % a)
PARTY.add_player(Player(name))
base.put('Game Start')
base.put(PARTY.to_str())
dungeon = Hub(PARTY)
PARTY.hub = dungeon
PARTY.current_dungeon = dungeon
PARTY.current_dungeon.start()
while(PARTY.end):
PARTY.handle_player_turn()
if(PARTY.end):
PARTY.current_dungeon.handle_monster_turn()
base.put("\n\n------------=========GAME OVER=========------------")
if __name__ == '__main__':
game = Manager()
try:
if sys.argv[1] == 'web':
print 'initializing web server. point your browser to http://localhost:5000.'
game.main(True)
else:
game.main()
except IndexError:
game.main()<|fim▁end|>
|
except:
base.put("could not reach the update service :'(")
return latest
|
<|file_name|>fft.rs<|end_file_name|><|fim▁begin|>#[cfg(test)]
mod tests {<|fim▁hole|> fn it_works() {
assert!(true);
}
}<|fim▁end|>
|
#[test]
|
<|file_name|>mock.js<|end_file_name|><|fim▁begin|>module.exports = {
// mock开发配置
'GET /login?$user&$password': {
ok: {
code: 100,
msg: 'ok',
data: {
a: 1,
b: 2
}
},
fail: {
code: 200,
msg: 'fail'
}
},
'POST /signup?$user&$password': {
ok: {
code: 100,
msg: 'ok',
data: {<|fim▁hole|> }
},
fail: {
code: 200,
msg: 'fail'
}
}
}<|fim▁end|>
|
a: 1,
b: 2
|
<|file_name|>aboutDialog.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import sys
from constants import *
#For using unicode utf-8
reload(sys).setdefaultencoding("utf-8")
from PyQt4 import QtCore
from PyQt4 import QtGui
from uiQt_aboutdialog import Ui_aboutDialog
class aboutDialog(QtGui.QDialog, Ui_aboutDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.fillAll()
def fillAll(self):
name = """\
<b>%s %s</b><p>
%s<p>
%s"""% (NAME, VERSION, SUMMARY, DESCRIPTION)
self.nameAndVersion.setText(name.decode("utf-8"))
developers = """\
<b>Core Developer:</b><p>
%s<p>
%s"""% (CORE_DEVELOPER, CORE_EMAIL)
self.developersText.setText(developers.decode("utf-8"))
self.translatorsText.setText(TRANSLATORS.decode("utf-8"))
licenseFile = QtCore.QFile("COPYING")
if not licenseFile.open(QtCore.QIODevice.ReadOnly):
license = LICENSE_NAME
else:
textstream = QtCore.QTextStream(licenseFile)
textstream.setCodec("UTF-8")
license = textstream.readAll()<|fim▁hole|> self.licenseText.setText(license)
iconsLicense = "CC by-nc-sa\nhttp://creativecommons.org/licenses/by-nc-sa/3.0/"
self.iconsLicenseText.setText(iconsLicense)<|fim▁end|>
| |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* 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.
*/
/*
* D E F A U L T A P P L I C A T I O N
*
* Simple http response server to display default.html
*
*/
console.log("STARTING DEFAULT APPLICATION");
var fs = require('fs');
var path = require('path');
var server = io.nodekit.electro.protocol.createServer('node:', function (request, response) {
console.log("EXECUTING DEFAULT APPLICATION");
var file = path.resolve(__dirname, 'default.html');
fs.readFile(file, function read(err, content) {
if (err) {
console.log(err);
response.writeHead(500, { 'Content-Type': 'text/html' });
response.end('<html><body>An internal server error occurred</body>', 'utf-8');
} else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
}
});
});<|fim▁hole|> console.log("Server running");<|fim▁end|>
|
server.listen();
|
<|file_name|>App.js<|end_file_name|><|fim▁begin|>import React, { Component } from 'react';
import Header from './Header';
import MainSection from './MainSection';
export default class App extends Component {
render() {<|fim▁hole|> <MainSection/>
</div>
);
}
}<|fim▁end|>
|
return (
<div>
<Header/>
|
<|file_name|>FunctionalAction.java<|end_file_name|><|fim▁begin|>package org.aslab.om.metacontrol.action;
import java.util.HashSet;
import java.util.Set;
import org.aslab.om.ecl.action.Action;
import org.aslab.om.ecl.action.ActionFeedback;
import org.aslab.om.ecl.action.ActionResult;
import org.aslab.om.metacontrol.value.CompGoalAtomTracker;
/**
* <!-- begin-UML-doc -->
* <!-- end-UML-doc -->
* @author chcorbato
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
public class FunctionalAction extends Action {
/** <|fim▁hole|> * number of ever issued action_list (this way a new number is assigned to everyone upon creation)
* <!-- end-UML-doc -->
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
private static short num_of_actions = 0;
@Override
protected short addAction(){
return num_of_actions++;
}
/**
* <!-- begin-UML-doc -->
* <!-- end-UML-doc -->
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
public Set<CompGoalAtomTracker> atoms = new HashSet<CompGoalAtomTracker>();
/**
* <!-- begin-UML-doc -->
* <!-- end-UML-doc -->
* @param a
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
public FunctionalAction(Set<CompGoalAtomTracker> a) {
// begin-user-code
atoms = a;
// end-user-code
}
@Override
public ActionResult processResult(ActionFeedback feedback) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean timeOut() {
// TODO Auto-generated method stub
return false;
}
}<|fim▁end|>
|
* <!-- begin-UML-doc -->
|
<|file_name|>connection.rs<|end_file_name|><|fim▁begin|>//! The connection module contains the Connection struct, that provides an interface for a Server
//! Query connection.
use channel::ChannelList;
use client::ClientList;
use command::Command;
use error;
use error::{Error, SQError};
use map::*;
use std::fmt;
use std::io::prelude::*;
use std::io::BufReader;
use std::net;
use std::string::String;
/// Connection provides an interface for a Server Query connection.
#[derive(Debug)]
pub struct Connection {
addr: net::SocketAddrV4,
conn: BufReader<net::TcpStream>,
}
impl Connection {
/// creates a new Connection from an adress given as a string reference.
pub fn new(addr: &str) -> error::Result<Connection> {
let addr = addr.to_string();
let a = addr.parse()?;
let c = net::TcpStream::connect(a)?;
let mut connection = Connection {
addr: a,
conn: BufReader::new(c),
};
let mut tmp = String::new();
connection.conn.read_line(&mut tmp)?;
if tmp.trim() != "TS3" {
return Err(From::from("the given server is not a TS3 server"));
}
connection.read_line(&mut tmp)?;
Ok(connection)
}
fn read_line<'a>(&mut self, buf: &'a mut String) -> error::Result<&'a str> {
let _ = self.conn.read_line(buf)?;
Ok(buf.trim_left_matches(char::is_control))
}
fn get_stream_mut(&mut self) -> &mut net::TcpStream {
self.conn.get_mut()
}
/// sends a given command to the Server Query server and returns the answer as a String, or
/// the error.
pub fn send_command<C>(&mut self, command: &C) -> error::Result<String>
where
C: Command,
{
let command = command.string();
if command.is_empty() {
return Err(Error::from("no command"));
}
writeln!(self.get_stream_mut(), "{}", command)?;
self.get_stream_mut().flush()?;
let mut result = String::new();
loop {
let mut line = String::new();
let line = self.read_line(&mut line)?;
let ok = SQError::parse_is_ok(line)?;
if ok {
break;
}
result += line; // + "\n";
}
Ok(result)
}
pub fn send_command_to_map<C>(&mut self, command: &C) -> error::Result<StringMap>
where
C: Command,
{
let result = self.send_command(command)?;
Ok(to_map(&result))
}
pub fn send_command_vec<C>(&mut self, commands: C) -> error::Result<Vec<String>>
where
C: IntoIterator,
C::Item: Command,
{
let mut results = Vec::new();
for cmd in commands {
let res = self.send_command(&cmd)?;
results.push(res);
}
Ok(results)
}
/// sends the quit command to the server and shuts the Connection down.
pub fn quit(&mut self) -> error::Result<()> {
self.send_command(&"quit")?;
self.conn.get_ref().shutdown(net::Shutdown::Both)?;
Ok(())
}
/// sends the use command with the given id to the server.
pub fn use_server_id(&mut self, id: u64) -> error::Result<()> {<|fim▁hole|> }
/// sends the login command with the name and password to the server.
pub fn login(&mut self, name: &str, pw: &str) -> error::Result<()> {
self.send_command(&format!("login {} {}", name, pw))
.map(|_| ())
}
/// tries to change the nickname of the Server Query client.
pub fn change_nickname(&mut self, nickname: &str) -> error::Result<()> {
let map = self.send_command_to_map(&"whoami")?;
let id = map
.get("client_id")
.ok_or("error at collecting client_id")?;
let cmd = format!("clientupdate clid={} client_nickname={}", id, nickname);
let _ = self.send_command(&cmd)?;
Ok(())
}
/// sends the clientlist command to the server and parses the result.
pub fn clientlist(&mut self) -> error::Result<ClientList> {
let s = self.send_command(&"clientlist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn clientlist_with_info(&mut self) -> error::Result<ClientList> {
let mut clients = self.clientlist()?;
for client in clients.as_mut().iter_mut() {
let command = format!("clientinfo clid={}", client.clid);
let str = self.send_command(&command)?;
let map = to_map(&str);
client.mut_from_map(&map);
}
Ok(clients)
}
/// sends the channellist command to the server and parses the result.
pub fn channellist(&mut self) -> error::Result<ChannelList> {
let s = self.send_command(&"channellist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn channellist_with_clients(&mut self) -> error::Result<ChannelList> {
let clients = self.clientlist_with_info()?;
let mut channels = self.channellist()?;
channels.merge_clients(&clients);
Ok(channels)
}
}
impl fmt::Display for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.addr)
}
}<|fim▁end|>
|
self.send_command(&format!("use {}", id)).map(|_| ())
|
<|file_name|>highlightable.ts<|end_file_name|><|fim▁begin|>import {
ChangeDetectorRef,
SimpleChanges,
NgZone,
} from '@angular/core';
import {highlightTime} from '../../utils/configuration';
const initialTimespan = highlightTime;
export abstract class Highlightable {
isUpdated = false;
private timespan = initialTimespan; // scales down
private resetUpdateState;
constructor(
private elementChangeDetector: ChangeDetectorRef,
private elementIsUpdated?: (changes?: SimpleChanges) => boolean
) {}
protected ngOnChanges(changes: SimpleChanges) {
if (typeof this.elementIsUpdated === 'function') {
if (this.elementIsUpdated(changes)) {
this.changed();
}
}
else {
this.changed();
}
}
protected ngOnDestroy() {
this.elementChangeDetector = null;
this.clear();
}
protected clear() {
clearTimeout(this.resetUpdateState);<|fim▁hole|>
if (this.elementChangeDetector) {
this.elementChangeDetector.detectChanges();
}
}
protected changed() {
this.isUpdated = true;
if (this.resetUpdateState != null) {
clearTimeout(this.resetUpdateState);
this.timespan = initialTimespan * 0.1;
}
else {
this.timespan = initialTimespan;
}
this.resetUpdateState = setTimeout(() => this.clear(), highlightTime);
if (this.elementChangeDetector) {
this.elementChangeDetector.detectChanges();
}
}
}<|fim▁end|>
|
this.resetUpdateState = null;
this.isUpdated = false;
|
<|file_name|>SwipeListView.java<|end_file_name|><|fim▁begin|>package com.longluo.demo.widget.swipelistview;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.longluo.demo.R;
import java.util.List;
/**
* ListView subclass that provides the swipe functionality
*/
public class SwipeListView extends ListView {
/**
* log tag
*/
public final static String TAG = "SwipeListView";
/**
* whether debug
*/
public final static boolean DEBUG = false;
/**
* Used when user want change swipe list mode on some rows
*/
public final static int SWIPE_MODE_DEFAULT = -1;
/**
* Disables all swipes
*/
public final static int SWIPE_MODE_NONE = 0;
/**
* Enables both left and right swipe
*/
public final static int SWIPE_MODE_BOTH = 1;
/**
* Enables right swipe
*/
public final static int SWIPE_MODE_RIGHT = 2;
/**
* Enables left swipe
*/
public final static int SWIPE_MODE_LEFT = 3;
/**
* Binds the swipe gesture to reveal a view behind the row (Drawer style)
*/
public final static int SWIPE_ACTION_REVEAL = 0;
/**
* Dismisses the cell when swiped over
*/
public final static int SWIPE_ACTION_DISMISS = 1;
/**
* Marks the cell as checked when swiped and release
*/
public final static int SWIPE_ACTION_CHOICE = 2;
/**
* No action when swiped
*/
public final static int SWIPE_ACTION_NONE = 3;
/**
* Default ids for front view
*/
public final static String SWIPE_DEFAULT_FRONT_VIEW = "swipelist_frontview";
/**
* Default id for back view
*/
public final static String SWIPE_DEFAULT_BACK_VIEW = "swipelist_backview";
/**
* Indicates no movement
*/
private final static int TOUCH_STATE_REST = 0;
/**
* State scrolling x position
*/
private final static int TOUCH_STATE_SCROLLING_X = 1;
/**
* State scrolling y position
*/
private final static int TOUCH_STATE_SCROLLING_Y = 2;
private int touchState = TOUCH_STATE_REST;
private float lastMotionX;
private float lastMotionY;
private int touchSlop;
int swipeFrontView = 0;
int swipeBackView = 0;
/**
* Internal listener for common swipe events
*/
private SwipeListViewListener swipeListViewListener;
/**
* Internal touch listener
*/
private SwipeListViewTouchListener touchListener;
/**
* If you create a View programmatically you need send back and front identifier
*
* @param context Context
* @param swipeBackView Back Identifier
* @param swipeFrontView Front Identifier<|fim▁hole|> this.swipeBackView = swipeBackView;
init(null);
}
/**
* @see android.widget.ListView#ListView(android.content.Context, android.util.AttributeSet)
*/
public SwipeListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
/**
* @see android.widget.ListView#ListView(android.content.Context, android.util.AttributeSet, int)
*/
public SwipeListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
/**
* Init ListView
*
* @param attrs AttributeSet
*/
private void init(AttributeSet attrs) {
int swipeMode = SWIPE_MODE_BOTH;
boolean swipeOpenOnLongPress = true;
boolean swipeCloseAllItemsWhenMoveList = true;
long swipeAnimationTime = 0;
float swipeOffsetLeft = 0;
float swipeOffsetRight = 0;
int swipeDrawableChecked = 0;
int swipeDrawableUnchecked = 0;
int swipeActionLeft = SWIPE_ACTION_REVEAL;
int swipeActionRight = SWIPE_ACTION_REVEAL;
if (attrs != null) {
TypedArray styled = getContext().obtainStyledAttributes(attrs, R.styleable.SwipeListView);
swipeMode = styled.getInt(R.styleable.SwipeListView_swipeMode, SWIPE_MODE_BOTH);
swipeActionLeft = styled.getInt(R.styleable.SwipeListView_swipeActionLeft, SWIPE_ACTION_REVEAL);
swipeActionRight = styled.getInt(R.styleable.SwipeListView_swipeActionRight, SWIPE_ACTION_REVEAL);
swipeOffsetLeft = styled.getDimension(R.styleable.SwipeListView_swipeOffsetLeft, 0);
swipeOffsetRight = styled.getDimension(R.styleable.SwipeListView_swipeOffsetRight, 0);
swipeOpenOnLongPress = styled.getBoolean(R.styleable.SwipeListView_swipeOpenOnLongPress, true);
swipeAnimationTime = styled.getInteger(R.styleable.SwipeListView_swipeAnimationTime, 0);
swipeCloseAllItemsWhenMoveList = styled.getBoolean(R.styleable.SwipeListView_swipeCloseAllItemsWhenMoveList, true);
swipeDrawableChecked = styled.getResourceId(R.styleable.SwipeListView_swipeDrawableChecked, 0);
swipeDrawableUnchecked = styled.getResourceId(R.styleable.SwipeListView_swipeDrawableUnchecked, 0);
swipeFrontView = styled.getResourceId(R.styleable.SwipeListView_swipeFrontView, 0);
swipeBackView = styled.getResourceId(R.styleable.SwipeListView_swipeBackView, 0);
styled.recycle();
}
if (swipeFrontView == 0 || swipeBackView == 0) {
swipeFrontView = getContext().getResources().getIdentifier(SWIPE_DEFAULT_FRONT_VIEW, "id", getContext().getPackageName());
swipeBackView = getContext().getResources().getIdentifier(SWIPE_DEFAULT_BACK_VIEW, "id", getContext().getPackageName());
if (swipeFrontView == 0 || swipeBackView == 0) {
throw new RuntimeException(String.format("You forgot the attributes swipeFrontView or swipeBackView. You can add this attributes or use '%s' and '%s' identifiers", SWIPE_DEFAULT_FRONT_VIEW, SWIPE_DEFAULT_BACK_VIEW));
}
}
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
touchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
touchListener = new SwipeListViewTouchListener(this, swipeFrontView, swipeBackView);
if (swipeAnimationTime > 0) {
touchListener.setAnimationTime(swipeAnimationTime);
}
touchListener.setRightOffset(swipeOffsetRight);
touchListener.setLeftOffset(swipeOffsetLeft);
touchListener.setSwipeActionLeft(swipeActionLeft);
touchListener.setSwipeActionRight(swipeActionRight);
touchListener.setSwipeMode(swipeMode);
touchListener.setSwipeClosesAllItemsWhenListMoves(swipeCloseAllItemsWhenMoveList);
touchListener.setSwipeOpenOnLongPress(swipeOpenOnLongPress);
touchListener.setSwipeDrawableChecked(swipeDrawableChecked);
touchListener.setSwipeDrawableUnchecked(swipeDrawableUnchecked);
setOnTouchListener(touchListener);
setOnScrollListener(touchListener.makeScrollListener());
}
/**
* Recycle cell. This method should be called from getView in Adapter when use SWIPE_ACTION_CHOICE
*
* @param convertView parent view
* @param position position in list
*/
public void recycle(View convertView, int position) {
touchListener.reloadChoiceStateInView(convertView.findViewById(swipeFrontView), position);
touchListener.reloadSwipeStateInView(convertView.findViewById(swipeFrontView), position);
// Clean pressed state (if dismiss is fire from a cell, to this cell, with a press drawable, in a swipelistview
// when this cell will be recycle it will still have his pressed state. This ensure the pressed state is
// cleaned.
for (int j = 0; j < ((ViewGroup) convertView).getChildCount(); ++j) {
View nextChild = ((ViewGroup) convertView).getChildAt(j);
nextChild.setPressed(false);
}
}
/**
* Get if item is selected
*
* @param position position in list
* @return
*/
public boolean isChecked(int position) {
return touchListener.isChecked(position);
}
/**
* Get positions selected
*
* @return
*/
public List<Integer> getPositionsSelected() {
return touchListener.getPositionsSelected();
}
/**
* Count selected
*
* @return
*/
public int getCountSelected() {
return touchListener.getCountSelected();
}
/**
* Unselected choice state in item
*/
public void unselectedChoiceStates() {
touchListener.unselectedChoiceStates();
}
/**
* @see android.widget.ListView#setAdapter(android.widget.ListAdapter)
*/
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
touchListener.resetItems();
if (null != adapter) {
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
onListChanged();
touchListener.resetItems();
}
});
}
}
/**
* Dismiss item
*
* @param position Position that you want open
*/
public void dismiss(int position) {
int height = touchListener.dismiss(position);
if (height > 0) {
touchListener.handlerPendingDismisses(height);
} else {
int[] dismissPositions = new int[1];
dismissPositions[0] = position;
onDismiss(dismissPositions);
touchListener.resetPendingDismisses();
}
}
/**
* Dismiss items selected
*/
public void dismissSelected() {
List<Integer> list = touchListener.getPositionsSelected();
int[] dismissPositions = new int[list.size()];
int height = 0;
for (int i = 0; i < list.size(); i++) {
int position = list.get(i);
dismissPositions[i] = position;
int auxHeight = touchListener.dismiss(position);
if (auxHeight > 0) {
height = auxHeight;
}
}
if (height > 0) {
touchListener.handlerPendingDismisses(height);
} else {
onDismiss(dismissPositions);
touchListener.resetPendingDismisses();
}
touchListener.returnOldActions();
}
/**
* Open ListView's item
*
* @param position Position that you want open
*/
public void openAnimate(int position) {
touchListener.openAnimate(position);
}
/**
* Close ListView's item
*
* @param position Position that you want open
*/
public void closeAnimate(int position) {
touchListener.closeAnimate(position);
}
/**
* Notifies onDismiss
*
* @param reverseSortedPositions All dismissed positions
*/
protected void onDismiss(int[] reverseSortedPositions) {
if (swipeListViewListener != null) {
swipeListViewListener.onDismiss(reverseSortedPositions);
}
}
/**
* Start open item
*
* @param position list item
* @param action current action
* @param right to right
*/
protected void onStartOpen(int position, int action, boolean right) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onStartOpen(position, action, right);
}
}
/**
* Start close item
*
* @param position list item
* @param right
*/
protected void onStartClose(int position, boolean right) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onStartClose(position, right);
}
}
/**
* Notifies onClickFrontView
*
* @param position item clicked
*/
protected void onClickFrontView(int position) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onClickFrontView(position);
}
}
/**
* Notifies onClickBackView
*
* @param position back item clicked
*/
protected void onClickBackView(int position) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onClickBackView(position);
}
}
/**
* Notifies onOpened
*
* @param position Item opened
* @param toRight If should be opened toward the right
*/
protected void onOpened(int position, boolean toRight) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onOpened(position, toRight);
}
}
/**
* Notifies onClosed
*
* @param position Item closed
* @param fromRight If open from right
*/
protected void onClosed(int position, boolean fromRight) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onClosed(position, fromRight);
}
}
/**
* Notifies onChoiceChanged
*
* @param position position that choice
* @param selected if item is selected or not
*/
protected void onChoiceChanged(int position, boolean selected) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onChoiceChanged(position, selected);
}
}
/**
* User start choice items
*/
protected void onChoiceStarted() {
if (swipeListViewListener != null) {
swipeListViewListener.onChoiceStarted();
}
}
/**
* User end choice items
*/
protected void onChoiceEnded() {
if (swipeListViewListener != null) {
swipeListViewListener.onChoiceEnded();
}
}
/**
* User is in first item of list
*/
protected void onFirstListItem() {
if (swipeListViewListener != null) {
swipeListViewListener.onFirstListItem();
}
}
/**
* User is in last item of list
*/
protected void onLastListItem() {
if (swipeListViewListener != null) {
swipeListViewListener.onLastListItem();
}
}
/**
* Notifies onListChanged
*/
protected void onListChanged() {
if (swipeListViewListener != null) {
swipeListViewListener.onListChanged();
}
}
/**
* Notifies onMove
*
* @param position Item moving
* @param x Current position
*/
protected void onMove(int position, float x) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
swipeListViewListener.onMove(position, x);
}
}
protected int changeSwipeMode(int position) {
if (swipeListViewListener != null && position != ListView.INVALID_POSITION) {
return swipeListViewListener.onChangeSwipeMode(position);
}
return SWIPE_MODE_DEFAULT;
}
/**
* Sets the Listener
*
* @param swipeListViewListener Listener
*/
public void setSwipeListViewListener(SwipeListViewListener swipeListViewListener) {
this.swipeListViewListener = swipeListViewListener;
}
/**
* Resets scrolling
*/
public void resetScrolling() {
touchState = TOUCH_STATE_REST;
}
/**
* Set offset on right
*
* @param offsetRight Offset
*/
public void setOffsetRight(float offsetRight) {
touchListener.setRightOffset(offsetRight);
}
/**
* Set offset on left
*
* @param offsetLeft Offset
*/
public void setOffsetLeft(float offsetLeft) {
touchListener.setLeftOffset(offsetLeft);
}
/**
* Set if all items opened will be closed when the user moves the ListView
*
* @param swipeCloseAllItemsWhenMoveList
*/
public void setSwipeCloseAllItemsWhenMoveList(boolean swipeCloseAllItemsWhenMoveList) {
touchListener.setSwipeClosesAllItemsWhenListMoves(swipeCloseAllItemsWhenMoveList);
}
/**
* Sets if the user can open an item with long pressing on cell
*
* @param swipeOpenOnLongPress
*/
public void setSwipeOpenOnLongPress(boolean swipeOpenOnLongPress) {
touchListener.setSwipeOpenOnLongPress(swipeOpenOnLongPress);
}
/**
* Set swipe mode
*
* @param swipeMode
*/
public void setSwipeMode(int swipeMode) {
touchListener.setSwipeMode(swipeMode);
}
/**
* Return action on left
*
* @return Action
*/
public int getSwipeActionLeft() {
return touchListener.getSwipeActionLeft();
}
/**
* Set action on left
*
* @param swipeActionLeft Action
*/
public void setSwipeActionLeft(int swipeActionLeft) {
touchListener.setSwipeActionLeft(swipeActionLeft);
}
/**
* Return action on right
*
* @return Action
*/
public int getSwipeActionRight() {
return touchListener.getSwipeActionRight();
}
/**
* Set action on right
*
* @param swipeActionRight Action
*/
public void setSwipeActionRight(int swipeActionRight) {
touchListener.setSwipeActionRight(swipeActionRight);
}
/**
* Sets animation time when user drops cell
*
* @param animationTime milliseconds
*/
public void setAnimationTime(long animationTime) {
touchListener.setAnimationTime(animationTime);
}
/**
* @see android.widget.ListView#onInterceptTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = MotionEventCompat.getActionMasked(ev);
final float x = ev.getX();
final float y = ev.getY();
if (isEnabled() && touchListener.isSwipeEnabled()) {
if (touchState == TOUCH_STATE_SCROLLING_X) {
return touchListener.onTouch(this, ev);
}
switch (action) {
case MotionEvent.ACTION_MOVE:
checkInMoving(x, y);
return touchState == TOUCH_STATE_SCROLLING_Y;
case MotionEvent.ACTION_DOWN:
super.onInterceptTouchEvent(ev);
touchListener.onTouch(this, ev);
touchState = TOUCH_STATE_REST;
lastMotionX = x;
lastMotionY = y;
return false;
case MotionEvent.ACTION_CANCEL:
touchState = TOUCH_STATE_REST;
break;
case MotionEvent.ACTION_UP:
touchListener.onTouch(this, ev);
return touchState == TOUCH_STATE_SCROLLING_Y;
default:
break;
}
}
return super.onInterceptTouchEvent(ev);
}
/**
* Check if the user is moving the cell
*
* @param x Position X
* @param y Position Y
*/
private void checkInMoving(float x, float y) {
final int xDiff = (int) Math.abs(x - lastMotionX);
final int yDiff = (int) Math.abs(y - lastMotionY);
final int touchSlop = this.touchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved) {
touchState = TOUCH_STATE_SCROLLING_X;
lastMotionX = x;
lastMotionY = y;
}
if (yMoved) {
touchState = TOUCH_STATE_SCROLLING_Y;
lastMotionX = x;
lastMotionY = y;
}
}
/**
* Close all opened items
*/
public void closeOpenedItems() {
touchListener.closeOpenedItems();
}
}<|fim▁end|>
|
*/
public SwipeListView(Context context, int swipeBackView, int swipeFrontView) {
super(context);
this.swipeFrontView = swipeFrontView;
|
<|file_name|>attach_loopback.go<|end_file_name|><|fim▁begin|>// +build linux,cgo
package loopback
import (
"errors"
"fmt"
"os"
"github.com/Sirupsen/logrus"
"golang.org/x/sys/unix"
)
// Loopback related errors
var (
ErrAttachLoopbackDevice = errors.New("loopback attach failed")
ErrGetLoopbackBackingFile = errors.New("Unable to get loopback backing file")
ErrSetCapacity = errors.New("Unable set loopback capacity")
)
func stringToLoopName(src string) [LoNameSize]uint8 {
var dst [LoNameSize]uint8
copy(dst[:], src[:])
return dst
}
func getNextFreeLoopbackIndex() (int, error) {
f, err := os.OpenFile("/dev/loop-control", os.O_RDONLY, 0644)
if err != nil {
return 0, err
}
defer f.Close()
index, err := ioctlLoopCtlGetFree(f.Fd())
if index < 0 {
index = 0
}
return index, err
}
func openNextAvailableLoopback(index int, sparseFile *os.File) (loopFile *os.File, err error) {
// Start looking for a free /dev/loop
for {
target := fmt.Sprintf("/dev/loop%d", index)
index++
fi, err := os.Stat(target)
if err != nil {
if os.IsNotExist(err) {
logrus.Error("There are no more loopback devices available.")
}
return nil, ErrAttachLoopbackDevice
}
if fi.Mode()&os.ModeDevice != os.ModeDevice {
logrus.Errorf("Loopback device %s is not a block device.", target)
continue
}
// OpenFile adds O_CLOEXEC
loopFile, err = os.OpenFile(target, os.O_RDWR, 0644)
if err != nil {
logrus.Errorf("Error opening loopback device: %s", err)
return nil, ErrAttachLoopbackDevice
}
// Try to attach to the loop file
if err := ioctlLoopSetFd(loopFile.Fd(), sparseFile.Fd()); err != nil {
loopFile.Close()
// If the error is EBUSY, then try the next loopback
if err != unix.EBUSY {
logrus.Errorf("Cannot set up loopback device %s: %s", target, err)
return nil, ErrAttachLoopbackDevice
}
// Otherwise, we keep going with the loop
continue
}
// In case of success, we finished. Break the loop.
break
}
// This can't happen, but let's be sure
if loopFile == nil {
logrus.Errorf("Unreachable code reached! Error attaching %s to a loopback device.", sparseFile.Name())
return nil, ErrAttachLoopbackDevice
}
return loopFile, nil
}
// AttachLoopDevice attaches the given sparse file to the next
// available loopback device. It returns an opened *os.File.
func AttachLoopDevice(sparseName string) (loop *os.File, err error) {
// Try to retrieve the next available loopback device via syscall.
// If it fails, we discard error and start looping for a
// loopback from index 0.
startIndex, err := getNextFreeLoopbackIndex()
if err != nil {
logrus.Debugf("Error retrieving the next available loopback: %s", err)
}
// OpenFile adds O_CLOEXEC
sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0644)
if err != nil {
logrus.Errorf("Error opening sparse file %s: %s", sparseName, err)
return nil, ErrAttachLoopbackDevice
}
defer sparseFile.Close()
loopFile, err := openNextAvailableLoopback(startIndex, sparseFile)
if err != nil {
return nil, err
}
<|fim▁hole|> loopInfo := &loopInfo64{
loFileName: stringToLoopName(loopFile.Name()),
loOffset: 0,
loFlags: LoFlagsAutoClear,
}
if err := ioctlLoopSetStatus64(loopFile.Fd(), loopInfo); err != nil {
logrus.Errorf("Cannot set up loopback device info: %s", err)
// If the call failed, then free the loopback device
if err := ioctlLoopClrFd(loopFile.Fd()); err != nil {
logrus.Error("Error while cleaning up the loopback device")
}
loopFile.Close()
return nil, ErrAttachLoopbackDevice
}
return loopFile, nil
}<|fim▁end|>
|
// Set the status of the loopback device
|
<|file_name|>numbers_test.go<|end_file_name|><|fim▁begin|>package internal_test
import (
"math"
"testing"
"github.com/twpayne/go-geom/xy/internal"
)
func TestIsSameSignAndNonZero(t *testing.T) {
for i, tc := range []struct {
i, j float64
expected bool
}{
{
i: 0, j: 0,
expected: false,
},
{
i: 0, j: 1,
expected: false,
},
{
i: 1, j: 1,
expected: true,
},
{
i: math.Inf(1), j: 1,
expected: true,
},
{
i: math.Inf(1), j: math.Inf(1),
expected: true,
},
{
i: math.Inf(-1), j: math.Inf(1),
expected: false,
},
{
i: math.Inf(1), j: -1,
expected: false,
},
{
i: 1, j: -1,
expected: false,
},
{
i: -1, j: -1,
expected: true,
},
{
i: math.Inf(-1), j: math.Inf(-1),
expected: true,
},
} {
actual := internal.IsSameSignAndNonZero(tc.i, tc.j)
if actual != tc.expected {
t.Errorf("Test %d failed.", i+1)
}
}
}
func TestMin(t *testing.T) {
for i, tc := range []struct {
v1, v2, v3, v4 float64<|fim▁hole|> expected float64
}{
{
v1: 0, v2: 0, v3: 0, v4: 0,
expected: 0,
},
{
v1: -1, v2: 0, v3: 0, v4: 0,
expected: -1,
},
{
v1: -1, v2: 2, v3: 3, v4: math.Inf(-1),
expected: math.Inf(-1),
},
} {
actual := internal.Min(tc.v1, tc.v2, tc.v3, tc.v4)
if actual != tc.expected {
t.Errorf("Test %d failed.", i+1)
}
}
}<|fim▁end|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.